curriculum/challenges/english/blocks/lecture-working-with-loops-and-sequences/6839e3ea328b630cf5fca9ac.md
As you learned in earlier modules, loops are used to repeat a block of code for a set number of times. In this lesson you will learn how to work with different types of loops in Python.
The first loop we will go over is the for loop. Here is an example of using a for loop to iterate through a list and print each item to the console:
programming_languages = ['Rust', 'Java', 'Python', 'C++']
for language in programming_languages:
print(language)
The result would be:
Rust
Java
Python
C++
Notice that the print(language) is indented inside of the loop. Without that indentation, you would get an IndentationError:
"""
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
IndentationError: expected an indented block after 'for' statement on line 3
"""
You can also use a for loop to iterate through other iterables like a string. Here is an example of using a for loop to loop through the string code and print out each character:
for char in 'code':
print(char)
The result would be:
c
o
d
e
Just like in JavaScript, you can also nest for loops in Python. Here is an example of using a nested for loop:
categories = ['Fruit', 'Vegetable']
foods = ['Apple', 'Carrot', 'Banana']
for category in categories:
for food in foods:
print(category, food)
The outer loop will iterate through each category in the categories list. For each category, the inner loop will iterate through each food in the foods list. Here is the result that will be printed to the console:
Fruit Apple
Fruit Carrot
Fruit Banana
Vegetable Apple
Vegetable Carrot
Vegetable Banana
Another type of loop you can use in Python is the while loop. This type of loop will repeat a block of code until the condition is False. Here is an example of using a while loop for a guessing game:
secret_number = 3
guess = 0
while guess != secret_number:
guess = int(input('Guess the number (1-5): '))
if guess != secret_number:
print('Wrong! Try again.')
print('You got it!')
In this example we have a secret_number variable with the value of 3 and an initial guess of 0. Then we use the input function to get input from the user, then convert the input string into an integer with the int() function, and assign it to the guess variable. If the user guesses correctly by inputting 3, the while loop is broken out of and the message You got it! is printed to the console. Otherwise, the message Wrong! Try again. is printed to the console, and the loop repeats, prompting the user to guess again.
Here's an example result:
Guess the number (1-5): 2
Wrong! Try again.
Guess the number (1-5): 1
Wrong! Try again.
Guess the number (1-5): 3
You got it!
Just like in JavaScript, Python supports the break and continue statements.
The break statement is used to stop the execution of a loop. Here is an example of using the break statement for a list of developer_names:
developer_names = ['Jess', 'Naomi', 'Tom']
for developer in developer_names:
if developer == 'Naomi':
break
print(developer)
In this example, we iterate through a list of developer_names and print each name to the console. If the name is equal to Naomi, then we break out of the loop. This results in only the name Jess being printed to the console.
The continue statement is used to skip the current iteration of a loop and move onto the next iteration. Let's modify the example from earlier to use the continue statement instead of break:
developer_names = ['Jess', 'Naomi', 'Tom']
for developer in developer_names:
if developer == 'Naomi':
continue
print(developer)
Now the result in the console will be different. The names Jess and Tom are printed because the continue statement skips the second iteration of the loop when developer is equal to Naomi, and does not print that name to the console.
Both for and while loops can be combined with an else clause, which is executed only when the loop is not terminated by a break statement. Here is an example of using multiple for loops:
words = ['sky', 'apple', 'rhythm', 'fly', 'orange']
for word in words:
for letter in word:
if letter.lower() in 'aeiou':
print(f"'{word}' contains the vowel '{letter}'")
break
else:
print(f"'{word}' has no vowels")
In this example we have a list of random words, and a for loop is used to loop through each word. Inside the outer for loop, we have another for loop to loop through each letter of each word. If the lowercase version of the letter is a vowel, we print the word followed by what vowels it contains, then break out of the inner loop. If the word contains no vowels, then we print a message indicating that.
Here is what the result looks like in the console:
'sky' has no vowels
'apple' contains the vowel 'a'
'rhythm' has no vowels
'fly' has no vowels
'orange' contains the vowel 'o'
Loops are very common in Python, so it's important to get comfortable with them. In the next few lessons, you will learn how to work with the enumerate() and range() functions in loops.
What will the following code print to the console?
programming_languages = ['Rust', 'Java', 'Python', 'C++']
for language in programming_languages:
print(language)
Rust
Java
Python
C++
Rust
Python
C++
Review the beginning of the lesson for the answer.
Rust
Java
Review the beginning of the lesson for the answer.
Rust
Python
Java
C++
Review the beginning of the lesson for the answer.
1
Which of the following loops is used to repeat a block of code until a condition is False?
list
Only one of these options is a real type of loop used in both Python and JavaScript.
while
continue
Only one of these options is a real type of loop used in both Python and JavaScript.
break
Only one of these options is a real type of loop used in both Python and JavaScript.
2
Which of the following is used to stop the execution of a loop?
stop
Review the end of the lesson for the answer.
end
Review the end of the lesson for the answer.
break
halt
Review the end of the lesson for the answer.
3