If Statements
Python uses if, elif, and else for conditional execution. Indentation defines code blocks.
# Basic if
age = 18
if age >= 18:
print("Adult")
# if/else
if age >= 18:
print("Adult")
else:
print("Minor")
# if/elif/else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
Comparison Operators
# == Equal
# != Not equal
# > Greater than
# < Less than
# >= Greater or equal
# <= Less or equal
x = 10
print(x == 10) # True
print(x != 5) # True
print(x > 5) # True
Logical Operators
# and, or, not
age = 25
income = 50000
if age >= 18 and income >= 30000:
print("Approved")
if age < 18 or income < 30000:
print("Denied")
if not (age < 18):
print("Adult")
For Loops
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 6): # 2, 3, 4, 5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
# Enumerate
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
While Loops
# Basic while
count = 0
while count < 5:
print(count)
count += 1
# While with break
while True:
user_input = input("Enter quit to exit: ")
if user_input == "quit":
break
# While with continue
count = 0
while count < 10:
count += 1
if count % 2 == 0:
continue # skip even numbers
print(count)
List Comprehensions
# Create a list with a loop in one line
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Nested
matrix = [[i*j for j in range(3)] for i in range(3)]
Summary
- Use if/elif/else for conditional logic
- for loops iterate over sequences, while loops repeat until condition is false
- break exits a loop, continue skips to the next iteration
- List comprehensions are a concise way to create lists
YouTip