DEV Community

Lameck Odhiambo
Lameck Odhiambo

Posted on

Python basics, Operators and Conditions

Introduction

Python is a high-level language (its closer to the natural language such as English compared to C++, Assembly which are low level languages - closer to the Machine language), general-purpose programming language known for its clear syntax and readability.

How python works

  • Python code in your source code is Compiled, the converted to Byte Code (which is a low level language) then to a Virtual Machine (which converts the code to 1s and 0s to be understood by the machine) after these steps the Output is produced.
  • The step from compiler to virtual machine is called Interpreter

Common Uses

  • Python is applied across many different industries and technical fields:
  1. Web Development: Building server-side applications with frameworks like Django and FastAPI.

  2. Data Science & Machine Learning: Processing numbers and training models using Pandas, NumPy, and PyTorch.

  3. Automation: Writing simple scripts to handle repetitive daily file management or data entry tasks

Getting started with Python

Print()

  • Print() function displays values or text on the screen. It shows the result of a particular program that was run. Basically it displays an output of a program.

print("Hello World")

  • You can also use single quotes

print('Hello World')

  • A variable can also be printed as shown but in this case we do not use quatation

age = 30
print(age)

Variables

  • Variables are containers or box holding a particular value. It can be text, number or a float
first_name = 'Lameck' 
first_name = "Lameck"

print(first_name)
Enter fullscreen mode Exit fullscreen mode
  • first_name here is a variable.

Data types in Python

Strings

  • Strings are surrounded by either single quatation marks or double quatation.
first_name = 'Lameck' 
first_name = "Lameck"

print(first_name)
Enter fullscreen mode Exit fullscreen mode
  • 'Lameck' here is a string

Integer

  • Integers are whole numbers and are not inside any quatatation.
age = 30
quantity = 3
number_of_students = 68
Enter fullscreen mode Exit fullscreen mode

Float

  • Float are numbers containing a decimal point, also they are not put inside quatations.
price = 10.99
weight = 75.3
Enter fullscreen mode Exit fullscreen mode

Booleans

  • These are True of False values. The are also not put inside the quatations and the first letters must be capital.
is_student = True
is_adult = False
Enter fullscreen mode Exit fullscreen mode

Type Casting

  • Type casting is converting a variable to another data type. For example converting a float to an integer or a string to an integer and so forth.
gpa = 3.2
new_gpa = int(gpa)
print(new_gpa)
Enter fullscreen mode Exit fullscreen mode
age = 32
new_age = float(age)
print(new_age)
Enter fullscreen mode Exit fullscreen mode

F - Strings / String formatting

  • Format strings, f-strings or String formatting inserts variables, expressions, or specific formatting rules directly into a text string.
age = 33
name = "Nashon"
print(f"{name} is {age} years old.")
Enter fullscreen mode Exit fullscreen mode

Input()

  • This is a function that prompts the user to enter data. It returns the entered value as a string.
name = input("Enter your name: ")
print(f"Hello {name}")
Enter fullscreen mode Exit fullscreen mode

Operators in Python

1. Arithmetic operators

  • Used to perform standard mathematical calculations

2. Comparison (Relational) Operators

  • Used to compare two values. They always return a Boolean value: either True or False

3. Logical Operators

  • Used to combine conditional statements

and: Returns True if both statements are true

or: Returns True if at least one statement is true

not: Inverts the result (returns False if the result is true)

4. Membership Operators

  • Used to test if a sequence (like a string, list, or tuple) is present in an object.

in: Returns True if a sequence with the specified value is present in the object (e.g., 'a' in 'apple' → True).

not in: Returns True if a sequence with the specified value is not present in the object.

5. Identity Operators

  • Used to compare objects, not if they are equal, but if they are actually the same object with the same memory location.

is: Returns True if both variables point to the same object.

is not: Returns True if both variables do not point to the same object.

Conditions in Python

  • Conditional statements control the flow of execution by evaluating expressions to either True or False.
  • Operators discussed above can be used within these conditional statements.

1. The if Statement

  • Executes a block of code only if the condition evaluates to True
age = 20
if age >= 18:
    print("You are an adult.")  # Runs because the condition is True
Enter fullscreen mode Exit fullscreen mode

2. The if-else Statement

  • Executes one block if the condition is True, and an alternate block if it is False
score = 45
if score >= 50:
    print("Passed")
else:
    print("Failed")
Enter fullscreen mode Exit fullscreen mode

3. The if-elif-else Chain

  • Used to evaluate multiple sequential conditions. It stops evaluating as soon as it finds the first True condition
temperature = 25

if temperature > 30:
    print("It's hot.")
elif temperature >= 15:
    print("It's warm.")  # Runs and skips the rest
else:
    print("It's cold.")
Enter fullscreen mode Exit fullscreen mode

Nested Conditions

  • Nested conditionals occur when you place a conditional statement (if, elif, or else) inside another conditional statement. They are used to test a secondary condition only after a primary condition has already passed.
is_logged_in = True
age = 20

if is_logged_in:
    print("User is authenticated.")

    # Secondary check inside the first one
    if age >= 21:
        print("Purchase approved.")
    else:
        print("Purchase denied: You must be at least 21.")

else:
    print("Purchase denied: Please log in first.")
Enter fullscreen mode Exit fullscreen mode

Conclusion

  • Python operators and conditional statements are the fundamental building blocks that give programs the ability to process data, make decisions, and control execution flow.

Top comments (0)