Part 5: Flow Control

Kerry Back, Rice University

If-Elif-Else Statements

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!

Practice: If-Elif-Else

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.

Logical Operators

Combine conditions with logical operators:

  • and - True if both conditions are True
  • or - True if at least one is True
  • not - True if condition is False
age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive!")
else:
    print("Cannot drive")
You can drive!

Practice: Logical Operators

Exercise 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.

Membership Testing

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!

Practice: Membership Testing

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.

Float Precision Warning

Problem: Floating-point arithmetic can have precision errors:

result = 0.1 + 0.2
print(f"0.1 + 0.2 = {result}")
print(f"0.1 + 0.2 == 0.3: {result == 0.3}")
0.1 + 0.2 = 0.30000000000000004
0.1 + 0.2 == 0.3: False

Solution: Use round() for comparisons:

if round(0.1 + 0.2, 1) == round(0.3, 1):
    print("Equal when rounded!")
Equal when rounded!

Practice: Float Precision

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.

Ternary Operator (Compact If-Else)

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 = -number
15

Syntax: value_if_true if condition else value_if_false

Practice: Ternary Operator

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.

For Loops with range()

range() generates sequences of numbers:

  • range(n) → 0 to n-1
  • range(start, stop) → start to stop-1
  • range(start, stop, step) → with custom increment
# Calculate sum of 1 to 10
total = 0
for i in range(1, 11):
    total += i
print(f"Sum: {total}")
Sum: 55

Practice: For Loops

Exercise 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.

Looping Through Lists

Use for loops to iterate over lists:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

# With indices using enumerate
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")
apple
banana
cherry
0: apple
1: banana
2: cherry

Practice: Looping Through 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

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!

Practice: While 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.

Try/Except Error Handling

Handle errors gracefully instead of crashing:

# Without error handling - crashes
result = 10 / 0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
Cell In[10], line 2
      1 # Without error handling - crashes
----> 2 result = 10 / 0

ZeroDivisionError: division by zero
# With error handling - graceful
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
    result = None
Cannot divide by zero!

Practice: Try/Except

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.

Common Exception Types

Useful exception types to catch:

  • ValueError - invalid value (e.g., int("abc"))
  • ZeroDivisionError - division by zero
  • IndexError - list index out of range
  • KeyError - dictionary key not found
  • FileNotFoundError - file doesn’t exist
  • TypeError - wrong data type
try:
    int("not a number")
except ValueError:
    print("Invalid number format!")
Invalid number format!

Practice: Exception Types

Exercise 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.

List Comprehensions

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]

Practice: List Comprehensions

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.

List Comprehensions with Conditions

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]

Practice: Comprehensions with Conditions

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.

Dictionary Comprehensions

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}

Practice: Dictionary Comprehensions

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.

Summary

  • If-elif-else for decisions with comparison and logical operators
  • Ternary operator for compact if-else: x if condition else y
  • For loops iterate over sequences; use range() for numbers
  • While loops repeat while condition is True
  • Try/except handles errors gracefully
  • List/dict comprehensions create collections compactly

Flow control is essential for writing programs that make decisions and repeat tasks!