BackPython Program Structures and the for Loop
Study Guide - Smart Notes
Tailored notes based on your materials, expanded with key definitions, examples, and context.
Structure of Programs
Overview of Program Structures
Python programs are typically organized using three fundamental control structures: sequence, decision, and repetition structures. Understanding these is essential for writing clear and effective code.
Sequence Structure: Executes statements in a linear, step-by-step order.
Decision Structure: Uses conditions to determine which statements to execute (e.g., if statements).
Repetition Structure: Repeats a block of code multiple times, typically using loops (while or for).
Repetition Structures: Loops in Python
The while Loop
The while loop repeatedly executes a block of statements as long as a specified condition is True.
Syntax:
while condition: indented block of statements
Sentinel Values: Special values used to terminate a loop.
break and continue Statements: Used to alter the flow of loops.
The break and continue Statements
break: Immediately exits the nearest enclosing loop, skipping any remaining statements in the loop body.
continue: Skips the rest of the code inside the loop for the current iteration and jumps to the next iteration of the loop.
# Example of break while condition: statement if condition: break statement # Example of continue while condition: statement if condition: continue statement
The for Loop
Introduction to the for Loop
The for loop is used to iterate through a sequence of values, such as lists, strings, or ranges of numbers. It is especially useful when the number of iterations is known in advance.
General form:
for variable in sequence: statement statement ...
Sequence types: List, String, Arithmetic progression (using range()), File object
How the for Loop Works
The variable is successively assigned each value in the sequence.
The indented block of statements is executed after each assignment.
Indentation is crucial in Python to define the scope of the loop body.
Examples of for Loops
Iterating through a list:
list1 = ["one", 23, 17.5, "two", 33, 22.1, 242, "three"] for var in list1: print(var)
Output: Each element of the list is printed on a new line.
Finding the first integer divisible by 11:
list1 = ["one", 23, 17.5, "two", 33, 22.1, 242, "three"] found = False for i in range(len(list1)): if type(list1[i]) == int and list1[i] % 11 == 0: found = True print(list1[i]) break
Iterating through a string:
stateName = "Virginia" for letter in stateName: print(letter)
Comparison: while vs for Loops
while loop: Uses an index variable (e.g., i) to access elements by position.
for loop: Directly assigns each element in the sequence to the loop variable.
# while version stateName = "Virginia" i = 0 while i < len(stateName): letter = stateName[i] print(letter) i = i + 1 # for version stateName = "Virginia" for letter in stateName: print(letter)
Key difference: The while loop requires manual index management, while the for loop automatically iterates over elements.
Using range() in for Loops
Generating Arithmetic Progressions
The range() function generates a sequence of integers, commonly used for count-controlled loops.
Syntax: range([start], stop[, step])
If only stop is provided, the sequence starts at 0 and ends at stop - 1.
If step is provided, it determines the increment (or decrement if negative).
Expression | Generated Sequence | Comment |
|---|---|---|
range(5) | 0, 1, 2, 3, 4 | Executes 5 times, from 0 to 4 |
range(10, 15) | 10, 11, 12, 13, 14 | Ending value is not included |
range(0, 9, 2) | 0, 2, 4, 6, 8 | Step value is 2 |
range(5, 0, -1) | 5, 4, 3, 2, 1 | Negative step for counting down |
Example: Displaying Integers and Their Squares
for i in range(2, 6): print(i, i**2)
Output: Displays 2 4, 3 9, 4 16, 5 25
Example: Population Growth Table
pop = 300000 print("{0:10} {1}".format("Year", "Population")) for year in range(2014, 2019): print("{0:10d} {1:d}".format(year, round(pop))) pop += 0.03 * pop
Output: Displays a table of population growth from 2014 to 2018, increasing by 3% each year.
Counting Matches in a String
Counting Uppercase Letters
To count the number of uppercase letters in a string, iterate through each character and use the isupper() method.
string = "ISE 135" uppercase = 0 for char in string: if char.isupper(): uppercase += 1 print(uppercase)
Boolean String Methods
isupper(): Returns True if all cased characters are uppercase.
isdigit(): Returns True if all characters are digits.
isalpha(): Returns True if all characters are alphabetic.
Looping Through Lists and Tuples
Example: Filtering List Items
To display months containing the letter 'r':
months = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") for month in months: if 'r' in month.lower(): print(month)
Nested for Loops
Definition and Use
A nested for loop is a loop inside another loop. The inner loop must use a different loop variable and is fully contained within the outer loop's body.
Example: Multiplication Table
for m in range(1, 6): for n in range(1, 6): print(f"{m}x{n}={m*n}", end="\t") print()
Output: Prints a 5x5 multiplication table.
Practice Problems
Display a triangle of asterisks: Use nested for loops to print a triangle pattern based on user input.
Average Exam Grades: Use nested loops to compute average grades for multiple students, prompting for each student's grades and whether to continue.
Comments and Additional Notes
The range() function can take one, two, or three arguments: range([start], stop[, step]).
If the step is positive and start ≥ stop, or if the step is negative and start ≤ stop, range() produces an empty sequence.
Use list(range(...)) to display the generated sequence.
Loops can be nested: for loops inside while loops and vice versa.
break and continue are often used inside if statements to control loop execution efficiently.