score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Score: {score}, Grade: {grade}")Score: 85, Grade: B
Conditional statements let your program make decisions:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Score: {score}, Grade: {grade}")Score: 85, Grade: B
Key points: Use comparison operators (==, !=, <, >, <=, >=) and indentation is crucial!
Exercise 1 (with Gemini): Ask Gemini to “write Python code that checks if a temperature is hot, warm, or cold”
Exercise 2 (on your own): Type x = 15 then if x > 10: print("big") and run it.
Combine conditions with logical operators:
and - True if both conditions are Trueor - True if at least one is Truenot - True if condition is FalseExercise 1 (with Gemini): Ask Gemini to “write Python code that checks if a number is between 10 and 20 using ‘and’”
Exercise 2 (on your own): Type print(True and False) and run it.
Check if an item is in a collection:
vowels = "aeiou"
letter = "a"
if letter in vowels:
print(f"{letter} is a vowel")
else:
print(f"{letter} is a consonant")a is a vowel
Works with strings, lists, dictionaries, and more!
Exercise 1 (with Gemini): Ask Gemini to “write Python code that checks if ‘apple’ is in a list of fruits”
Exercise 2 (on your own): Type print("x" in "example") and run it.
Problem: Floating-point arithmetic can have precision errors:
0.1 + 0.2 = 0.30000000000000004
0.1 + 0.2 == 0.3: False
Solution: Use round() for comparisons:
Exercise 1 (with Gemini): Ask Gemini to “explain why 0.1 + 0.2 doesn’t equal 0.3 in Python”
Exercise 2 (on your own): Type print(round(3.14159, 2)) and run it.
Write simple if-else in one line:
number = -15
abs_value = number if number >= 0 else -number
print(abs_value)
# Equivalent to:
# if number >= 0:
# abs_value = number
# else:
# abs_value = -number15
Syntax: value_if_true if condition else value_if_false
Exercise 1 (with Gemini): Ask Gemini to “write Python code that uses a ternary operator to find the maximum of two numbers”
Exercise 2 (on your own): Type x = 10 then result = "big" if x > 5 else "small" then print(result) and run it.
range() generates sequences of numbers:
range(n) → 0 to n-1range(start, stop) → start to stop-1range(start, stop, step) → with custom incrementExercise 1 (with Gemini): Ask Gemini to “write Python code that uses a for loop to print numbers 1 to 5”
Exercise 2 (on your own): Type for i in range(3): print(i) and run it.
Use for loops to iterate over lists:
Exercise 1 (with Gemini): Ask Gemini to “write Python code that loops through a list of colors and prints each one”
Exercise 2 (on your own): Type for x in [1, 2, 3]: print(x * 2) and run it.
While loops repeat while a condition is True:
# Find first power of 2 > 1000
power = 0
result = 1
while result <= 1000:
power += 1
result = 2 ** power
print(f"2^{power} = {result}")2^10 = 1024
Warning: Make sure the condition eventually becomes False to avoid infinite loops!
Exercise 1 (with Gemini): Ask Gemini to “write Python code that uses a while loop to count from 1 to 5”
Exercise 2 (on your own): Type x = 0 then while x < 3: print(x); x += 1 and run it.
Handle errors gracefully instead of crashing:
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) Cell In[10], line 2 1 # Without error handling - crashes ----> 2 result = 10 / 0 ZeroDivisionError: division by zero
Exercise 1 (with Gemini): Ask Gemini to “write Python code that uses try/except to handle division by zero”
Exercise 2 (on your own): Type try: print(10/2) then except: print("error") and run it.
Useful exception types to catch:
ValueError - invalid value (e.g., int("abc"))ZeroDivisionError - division by zeroIndexError - list index out of rangeKeyError - dictionary key not foundFileNotFoundError - file doesn’t existTypeError - wrong data typeExercise 1 (with Gemini): Ask Gemini to “write Python code that catches a ValueError when converting a string to int”
Exercise 2 (on your own): Type try: int("hello") then except ValueError: print("Not a number") and run it.
Create lists in a compact, readable way:
# Traditional approach
squares = []
for i in range(1, 6):
squares.append(i ** 2)
print(squares)
# List comprehension
squares = [i**2 for i in range(1, 6)]
print(squares)[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
Syntax: [expression for item in iterable]
Exercise 1 (with Gemini): Ask Gemini to “write Python code that uses a list comprehension to create cubes of 1 to 5”
Exercise 2 (on your own): Type nums = [x * 2 for x in range(3)] then print(nums) and run it.
Add conditions to filter items:
# Only even squares
even_squares = [i**2 for i in range(1, 11) if i % 2 == 0]
print(even_squares)
# Transform strings
words = ["hello", "world", "python"]
upper_words = [w.upper() for w in words]
print(upper_words)[4, 16, 36, 64, 100]
['HELLO', 'WORLD', 'PYTHON']
Syntax: [expression for item in iterable if condition]
Exercise 1 (with Gemini): Ask Gemini to “write Python code that uses a list comprehension to get only odd numbers from 1 to 10”
Exercise 2 (on your own): Type evens = [x for x in range(10) if x % 2 == 0] then print(evens) and run it.
Create dictionaries compactly:
# Map words to their lengths
words = ["cat", "dog", "elephant", "bird"]
word_lengths = {word: len(word) for word in words}
print(word_lengths)
# Create from two lists
keys = ["a", "b", "c"]
values = [1, 2, 3]
my_dict = {k: v for k, v in zip(keys, values)}
print(my_dict){'cat': 3, 'dog': 3, 'elephant': 8, 'bird': 4}
{'a': 1, 'b': 2, 'c': 3}
Syntax: {key_expr: value_expr for item in iterable}
Exercise 1 (with Gemini): Ask Gemini to “write Python code that uses a dictionary comprehension to create squares for numbers 1-5”
Exercise 2 (on your own): Type d = {x: x*2 for x in range(3)} then print(d) and run it.
x if condition else yrange() for numbersFlow control is essential for writing programs that make decisions and repeat tasks!