Operators in Python
Operators are special symbols in Python that allow you to perform actions on values and variables. They are the foundation of calculations, comparisons, and logic in programming. Understanding operators is essential for writing expressions that drive your code’s behavior.
Arithmetic Operators
Arithmetic operators are used for basic mathematical calculations.
- Example:
a = 10
b = 3
print(a + b) # Addition → 13
print(a - b) # Subtraction → 7
print(a * b) # Multiplication → 30
print(a / b) # Division → 3.333...
print(a // b) # Floor division → 3
print(a % b) # Modulus (remainder) → 1
print(a ** b) # Exponentiation → 1000
These operators are frequently used in numerical computations.
Comparison Operators
Comparison operators compare values and return a boolean (True or False).
- Example:
x = 5
y = 10
print(x == y) # Equal → False
print(x != y) # Not equal → True
print(x > y) # Greater than → False
print(x < y) # Less than → True
print(x >= 5) # Greater or equal → True
These are widely used in conditions and loops.
⚙️ Logical Operators
Logical operators are used to combine conditions.
- Example:
is_adult = True
has_ticket = False
print(is_adult and has_ticket) # True only if both are True → False
print(is_adult or has_ticket) # True if at least one is True → True
print(not is_adult) # Negation → False
Logical operators make decision-making more powerful.
Assignment Operators
Assignment operators are used to assign values to variables, often with shorthand updates.
- Example:
x = 5
x += 3 # Same as x = x + 3 → 8
x -= 2 # Same as x = x - 2 → 6
x *= 4 # Same as x = x * 4 → 24
x /= 6 # Same as x = x / 6 → 4.0
These are useful for updating variables without rewriting the whole expression.
Other Operators
Python also has some special-purpose operators.
- Membership operators:
print("a" in "apple") # True
print("z" not in "apple") # True
- Identity operators:
a = [1, 2, 3]
b = a
print(a is b) # True (same object in memory)
print(a is not b) # False
These operators are often used in more advanced logic and data handling.
Conditional Statements (if, elif, else)
Programs often need to make decisions based on certain conditions. In Python, this is done using conditional statements. These allow the program to execute different blocks of code depending on whether a condition is True or False. Mastering if, elif, and else is essential for building logic-driven applications.
The `if` Statement
The if statement checks whether a condition is true. If it is, the indented block of code will execute.
- Example:
- Here, the condition
age >= 18is evaluated, and since it is True, the message is displayed.
age = 18
if age >= 18:
print("You are an adult.")
The `else` Clause
The else clause provides an alternative block of code to run if the condition is false.
- Example:
- Since the condition is False, the program runs the
elseblock.
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
The `elif` Statement
The elif (short for _else if_) allows checking multiple conditions in sequence.
- Example:
- The program checks each condition in order and executes the first block where the condition is true.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 75:
print("Grade: B")
elif score >= 60:
print("Grade: C")
else:
print("Grade: F")
Nested Conditions
You can place if statements inside other if statements for more complex logic.
- Example:
age = 20
has_id = True
if age >= 18:
if has_id:
print("Access granted.")
else:
print("ID required.")
else:
print("Access denied.")
- Nested conditions provide more control but should be used carefully to keep code readable.
Loops in Python (for, while)
Loops allow programs to repeat actions automatically instead of writing the same code multiple times. Python provides two main types of loops: for loops for iterating over sequences, and while loops for repeating actions as long as a condition is true. Mastering loops is essential for handling repetitive tasks efficiently.
The `for` Loop
The for loop is used to iterate over a sequence such as a list, string, or range of numbers.
- Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
- Output:
apple
banana
cherry
- With the
range()function, you can loop through numbers:
for i in range(5):
print(i)
- Output:
0
1
2
3
4
The for loop is best for known ranges or sequences.
The `while` Loop
The while loop runs as long as a condition is true.
- Example:
count = 0
while count < 3:
print("Counting:", count)
count += 1
- Output:
Counting: 0
Counting: 1
Counting: 2
The while loop is best for unknown ranges, where you keep looping until a condition changes.
Infinite Loops
A while loop can accidentally run forever if the condition never becomes false.
- Example (⚠️ problematic):
while True:
print("This will never stop!")
- Always ensure a condition will eventually end the loop, or use
breakto exit when needed.
Combining Loops with Conditions
Loops can also include condition checks inside them for more control.
- Example:
for i in range(10):
if i % 2 == 0:
print(i, "is even")
- This combines looping with conditional logic for smarter programs.
Loop Control (break, continue, pass)
Sometimes you need more control inside a loop—whether to stop it early, skip certain iterations, or simply leave a placeholder for future code. Python provides three special keywords—break, continue, and pass—to handle these situations.
The `break` Statement
The break statement is used to exit a loop immediately, regardless of the loop’s condition.
- Example:
for num in range(10):
if num == 5:
break
print(num)
- Output:
0
1
2
3
4
Here, the loop stops as soon as num reaches 5.
The `continue` Statement
The continue statement skips the rest of the code in the current loop iteration and moves on to the next one.
- Example:
for num in range(5):
if num == 2:
continue
print(num)
- Output:
0
1
3
4
When num == 2, the print statement is skipped, and the loop continues.
The `pass` Statement
The pass statement does nothing—it acts as a placeholder when code is required syntactically but you don’t want to write anything yet.
- Example:
for num in range(3):
if num == 1:
pass # Placeholder for future code
print("Number:", num)
- Output:
Number: 0
Number: 1
Number: 2
This is often used during development to keep the code structure valid while leaving parts empty.
Practical Exercises with Flow Control
Understanding the theory of conditionals and loops is essential, but the best way to master them is through hands-on practice. Flow control exercises help you apply if, elif, else, loops, and loop-control statements (break, continue, pass) in real-world scenarios.
Exercise 1: Even or Odd Checker
Write a program that asks the user for a number and checks whether it is even or odd.
num = int(input("Enter a number: "))
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
- This uses conditionals to make decisions based on user input.
Exercise 2: Multiplication Table
Use a loop to print the multiplication table of a number.
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
- This demonstrates for loops and iteration with a range.
Exercise 3: Password Checker
Simulate a password prompt that allows the user up to 3 attempts.
correct_password = "python123"
attempts = 0
while attempts < 3:
password = input("Enter password: ")
if password == correct_password:
print("Access granted.")
break
else:
print("Wrong password, try again.")
attempts += 1
else:
print("Too many attempts. Access denied.")
- This combines while loops, if statements, and the break statement.
Exercise 4: Skipping Values
Print numbers from 1 to 10, but skip multiples of 3.
for i in range(1, 11):
if i % 3 == 0:
continue
print(i)
- This demonstrates continue to skip specific iterations.
Exercise 5: Placeholder for Future Code
Create a program that checks grades but hasn’t implemented all rules yet.
grade = 85
if grade >= 90:
print("Excellent!")
elif grade >= 75:
pass # To be implemented later
else:
print("Needs improvement.")
- This uses pass as a placeholder while keeping the program valid.