Repetition with for loops
Introduction to For Loops in Python
For loops allow for the repetition of code a fixed number of times, making it a suitable option for tasks where the number of repetitions is predetermined.
When to Use For Loops
Useful when you want to repeat code a specific number of times.
Example: “I want to repeat this code three times.”
Introduced example of a Pomeranian named Pom-pom who barks five times.
Basic Structure of a For Loop
Structure:
for variable in range(n):Example:
for num in range(5): print("bork!")
Demonstrates the function by executing the code, yielding output: "bork!" printed five times.
Understanding range() Function
The
range()function generates an iterable, yielding items from 0 up to but not including the specified number.The variable in the for loop is reassigned during each repetition:_
Example:
for num in range(3): print("num is", num)Outputs values of
num: 0, 1, 2.
Indexing with range()
range()starts at 0 by default, aligning with string indexing principles (0-based indexing).To print each character of a string one at a time using
range(), the following code can be used:Example:
string = "CMPUT175" for num in range(len(string)): print(string[num])
Outputs each character on a new line, reinforcing index-based access.
Customizing range()
range()can start at values other than 0 or increment by values greater than 1—even stepping backwards.Encouraged to explore a range's flexibility by using
help(range)in the console.
Iterating Directly Over Sequences
Instead of using
range()to index, you can directly iterate over characters in a string:Example:
for char in string: print(char)
In this case, the for loop handles character access directly, simplifying the code.
Example: Counting Consonants and Vowels
A practical application of for loops involves counting the ratio of consonants to vowels in a word:
Input a word from standard input.
Initialize counts for vowels and consonants.
For loop iterates through each letter of the word:
Increment respective counts based on vowel checks.
Calculate and print the ratio:
Example Code:
ratio = consonants / vowels print(word, "has", ratio, "consonants to vowels")
Tested examples:
"schmaltz" (many consonants to a few vowels)
"ouabaio" (many vowels, few consonants).
Conclusion
For loops serve as a primary tool for iterating through sequences and repeating actions, allowing for effective programming practices.
Next video topic: Flexible repetition using while loops.