If Statements
An if statement lets your program make decisions. It runs a block
of code only when a condition is true.
age = 18
if age >= 18:
print("You are an adult.")
print("You can vote!")
Python uses indentation (4 spaces) to define code blocks. The indented
lines after the if statement only run when the condition is true.
This is different from most other languages that use braces {}.
If-Else
Add an else block to handle what happens when the condition is false:
temperature = 35
if temperature > 30:
print("It's hot outside!")
else:
print("The weather is nice.")
If-Elif-Else
Use elif (short for "else if") to check multiple conditions:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your grade: {grade}") # Your grade: B
Python checks each condition from top to bottom and runs the first one that's true.
If none match, the else block runs.
Comparison and Logical Operators
Use these operators in your conditions:
# Comparison operators
x == y # Equal to
x != y # Not equal to
x > y # Greater than
x < y # Less than
x >= y # Greater than or equal
x <= y # Less than or equal
# Logical operators (combine conditions)
x > 0 and x < 100 # Both must be true
x < 0 or x > 100 # At least one must be true
not (x > 0) # Inverts the result
Example with logical operators:
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive!")
else:
print("You cannot drive.")
For Loops
A for loop repeats code for each item in a sequence:
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# Output:
# I like apple
# I like banana
# I like cherry
The range() Function
Use range() to loop a specific number of times:
# Count from 0 to 4
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# Count from 1 to 5
for i in range(1, 6):
print(i) # 1, 2, 3, 4, 5
# Count by 2s
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
Looping Through Strings
for char in "Python":
print(char) # P, y, t, h, o, n
While Loops
A while loop repeats code as long as a condition remains true:
count = 0
while count < 5:
print(f"Count: {count}")
count += 1 # Don't forget to update!
# Output: Count: 0, Count: 1, ... Count: 4
If you forget to update the condition variable, the loop runs forever. Always make sure the condition will eventually become false. Press Ctrl + C to stop an infinite loop.
Practical While Loop Example
# Simple password checker
password = ""
while password != "secret123":
password = input("Enter password: ")
if password != "secret123":
print("Wrong password, try again.")
print("Access granted!")
Break and Continue
break exits the loop immediately. continue skips to
the next iteration:
# break example: stop at the first negative number
numbers = [10, 25, -3, 8, 15]
for num in numbers:
if num < 0:
print("Negative number found! Stopping.")
break
print(num)
# Output: 10, 25, Negative number found! Stopping.
# continue example: skip even numbers
for i in range(10):
if i % 2 == 0:
continue
print(i)
# Output: 1, 3, 5, 7, 9
Nested Loops
You can put loops inside loops:
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i * j}")
print("---")
# Output:
# 1 x 1 = 1
# 1 x 2 = 2
# 1 x 3 = 3
# ---
# 2 x 1 = 2
# ...
Summary
if/elif/elselet your program make decisions based on conditionsforloops iterate over sequences (lists, strings, ranges)whileloops repeat while a condition is truebreakexits a loop;continueskips to the next iteration- Indentation (4 spaces) defines code blocks in Python
- Logical operators (
and,or,not) combine conditions
Your programs can now make decisions and repeat tasks. Next up: functions and modules — organizing your code into reusable building blocks.