0% found this document useful (0 votes)
5 views12 pages

Python 9a Notes - updated 1

The document provides Python revision notes covering key concepts such as selection (conditionals) and looping (for and while loops). It includes practical examples, specifically a weather categorizer program that categorizes temperatures for different cities based on predefined thresholds. The document emphasizes the use of lists, dictionaries, tuples, and string formatting in Python programming.

Uploaded by

gigicho0815
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views12 pages

Python 9a Notes - updated 1

The document provides Python revision notes covering key concepts such as selection (conditionals) and looping (for and while loops). It includes practical examples, specifically a weather categorizer program that categorizes temperatures for different cities based on predefined thresholds. The document emphasizes the use of lists, dictionaries, tuples, and string formatting in Python programming.

Uploaded by

gigicho0815
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

P.

1 of 12

Contents

Python Revision Notes ................................................................................................... 2


1. Selection (Conditionals) ..................................................................................... 2
Class Practice of Selection – simpleTemerature.py: ...................................... 2
2. Looping ............................................................................................................... 3
2.1 for Loop .................................................................................................... 3
Class Practice of for loop – byRange.py: ................................................ 4
2.2 while Loop ................................................................................................ 4
3. Practical example – Weather Categorizer .......................................................... 6
Elaboration of tempCat.py ............................................................................. 9
P. 2 of 12

Python Revision Notes


1. Selection (Conditionals)
Selection helps make decisions in Python using if, elif, and else.

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

Class Practice of Selection – simpleTemerature.py:


Write a Python program, simpleTemperature.py that asks the user to input a
temperature in Celsius. Based on the input, the program should categorize the
temperature into one of the following:

1. "It's freezing!" if the temperature is below 0°C.


2. "It's cold." if the temperature is between 0°C and 20°C (inclusive).
3. "It's warm." if the temperature is above 20°C.

Example Output:
P. 3 of 12

2. Looping
Loops are used to repeat a block of code.

2.1 for Loop


Used to iterate over a sequence (e.g., list, range).

Example 1 – colors.py:

colors = ["red", "green", "blue"]

for color in colors:


print(f"The color is {color}.")

ch = input("")

The above code will give output as follows:


P. 4 of 12

Class Practice of for loop – byRange.py:

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:

2.2 while Loop


Repeats as long as the condition is True.

Example 1 – whileCounterVar.py:
This is a typical while loop controlled by a counter variable.

# initialization should be set


# before enter while loop
counter = 0

# set condition for the while loop


while counter < 3:
print(f"Counter: {counter}")

#increment should be carried out


# within while loop
counter += 1

ch = input("")
P. 5 of 12

The above code will give output as follows:


P. 6 of 12

3. Practical example – Weather Categorizer


Suppose the following table figure showing the initial temperatures of each city:

City Temperatures (°C)


New York 10, 15, 14
London 7, 8, 5
Tokyo 20, 23, 25

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

This is the code of tempCat.py

# Selection, Looping, List, Dictionary, and Tuple Example

# Constants for weather categorization


COLD_THRESHOLD = 10
MODERATE_THRESHOLD = 20

# List of cities with temperatures (in Celsius)


cities = [
{"name": "New York", "temperatures": (10, 15, 14)},
{"name": "London", "temperatures": (7, 8, 5)},
{"name": "Tokyo", "temperatures": (20, 23, 25)}
]

# Print header
print(f"{'City':<15}{'Max Temp':<15}{'Weather':<10}")
print("-" * 40)

# Loop through each city


for city in cities:
name = city["name"]
temperatures = city["temperatures"]

# Find the maximum temperature


max_temp = max(temperatures)

# Selection to determine weather category


if max_temp < COLD_THRESHOLD:
weather = "Cold"
elif max_temp <= MODERATE_THRESHOLD:
weather = "Moderate"
else:
weather = "Warm"
P. 8 of 12

# Print result with aligned formatting


print(f"{name:<15}{max_temp:<15.2f}{weather:<10}")

ch = input("")
P. 9 of 12

Elaboration of tempCat.py
1. Constants for Weather Categorization
COLD_THRESHOLD = 10
MODERATE_THRESHOLD = 20

➢ The constants COLD_THRESHOLD and MODERATE_THRESHOLD are used


to define temperature ranges for categorizing weather:
✓ Temperatures below 10°C are categorized as "Cold."
✓ Temperatures between 10°C and 20°C (inclusive) are categorized as
"Moderate."
✓ Temperatures above 20°C are categorized as "Warm."

2. List of Cities with Temperatures


cities = [
{"name": "New York", "temperatures": (10, 15, 14)},
{"name": "London", "temperatures": (7, 8, 5)},
{"name": "Tokyo", "temperatures": (20, 23, 25)}
]

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”

➢ A list named cities is created, where each element is a dictionary


representing a city. Each dictionary contains:
✓ "name": The name of the city (e.g., "New York").
✓ "temperatures": A tuple of daily temperatures (in Celsius).

➢ 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

3. Printing the Header


print(f"{'City':<15}{'Max Temp (°C)':<15}{'Weather':<10}")
print("-" * 40)

➢ This prints a header row for the output table:


✓ Column 1: "City" (left-aligned, width 15).
✓ Column 2: "Max Temp (°C)" (left-aligned, width 15).
✓ Column 3: "Weather" (left-aligned, width 10).

➢ The "-" * 40 creates a separator line made of 40 dashes (-).

4. Looping Through Each City


for city in cities:
name = city["name"]
temperatures = city["temperatures"]

➢ A for loop iterates over the cities list.

➢ For each city:


✓ The name of the city is extracted from the name key in the dictionary.
✓ The temperatures tuple is extracted from the temperatures key.

5. Finding the Maximum Temperature


max_temp = max(temperatures)

➢ The built-in max() function is used to find the highest temperature in the
temperatures tuple for the current city.
P. 11 of 12

6. Decision-Making for Weather Categorization


if max_temp < COLD_THRESHOLD:
weather = "Cold"
elif max_temp <= MODERATE_THRESHOLD:
weather = "Moderate"
else:
weather = "Warm"

➢ An if-elif-else conditional structure is used to determine the weather


category based on the max_temp:
✓ If the max_temp is less than COLD_THRESHOLD (10°C), the weather is
categorized as "Cold."
✓ If the max_temp is between COLD_THRESHOLD (10°C) and
MODERATE_THRESHOLD (20°C), the weather is "Moderate."
✓ Otherwise, the weather is "Warm."

7. Printing the Results


print(f"{name:<15}{max_temp:<15.2f}{weather:<10}")

➢ The results for each city are printed in a tabular format:


✓ The city name (name) is left-aligned with a width of 15 characters.
✓ The maximum temperature (max_temp) is formatted to two decimal
places (.2f) and left-aligned with a width of 15 characters.
✓ The weather category (weather) is left-aligned with a width of 10
characters.
P. 12 of 12

Key Concepts Demonstrated


1. Selection (Decision-Making):
➢ The if-elif-else structure is used to categorize the weather.

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!

You might also like