Python 9a Notes - updated 1
Python 9a Notes - updated 1
1 of 12
Contents
Syntax:
if condition:
# code block if condition is True
elif another_condition:
# code block if another_condition is True
else:
# code block if all conditions are False
Example Output:
P. 3 of 12
2. Looping
Loops are used to repeat a block of code.
Example 1 – colors.py:
ch = input("")
Write a Python program that uses a for loop and the range() function to
calculate and display the squares of numbers from 1 to 5. The program should print
the output in the following format:
Example 1 – whileCounterVar.py:
This is a typical while loop controlled by a counter variable.
ch = input("")
P. 5 of 12
We are going to write a Python program (tempCat.py) that will process the list of
cities above, then determine the maximum temperature for each city and categorize
the weather based on predefined thresholds. The results are printed in a neatly
formatted table as shown below:
P. 7 of 12
# Print header
print(f"{'City':<15}{'Max Temp':<15}{'Weather':<10}")
print("-" * 40)
ch = input("")
P. 9 of 12
Elaboration of tempCat.py
1. Constants for Weather Categorization
COLD_THRESHOLD = 10
MODERATE_THRESHOLD = 20
Reference Diagram
cities List
0 1 2
name: temperatures: name: temperatures: name: temperatures:
“New (10, 15, 14) “London” (7, 8, 5) “Tokyo” (20, 23, 25)
York”
➢ The tuple format is used for temperatures because tuples are immutable,
making them a good choice for storing fixed temperature data for each city.
P. 10 of 12
➢ The built-in max() function is used to find the highest temperature in the
temperatures tuple for the current city.
P. 11 of 12
2. Looping:
➢ The for loop iterates over the list of cities.
3. Lists:
➢ The cities list stores dictionaries representing each city's data.
4. Dictionaries:
➢ Each city is represented as a dictionary with keys "name" and
"temperatures".
5. Tuples:
➢ The temperatures tuple stores the daily temperatures, which are
immutable.
6. String Formatting:
➢ The f-string formatting ensures aligned and readable output.
This code is a great example of combining Python's basic data structures and control
flow to solve a real-world problem!