Course Content
Python Loops Tutorial
Python Loops Tutorial
The First For Loop
Using loops you can iterate over sequences like lists
, strings
, or numerical ranges
, they allow to process large amounts of data with minimal code.
item
is a variable that takes the value of each element in the sequence one at a time;sequence
is the data you are iterating through, such as a list, string, or range;for
statement block is executed for everyitem
in the sequence.
Imagine you have a string variable and want to print each letter of it in a column. Since a string is a sequence of letters, you can use a loop to achieve this.
word = 'iteration' # Printing every letter in the city's name for letter in word: print(letter)
word
variable holds the string'iteration'
;for
loop iterates over each character in the string;letter
takes the value of the next character in the string in each iteration;print(letter)
statement outputs the current character to the console.
Make sure to name the item
variable meaningfully. For example, if you iterate through a list called people
, the appropriate variable name should be person
.
Swipe to start coding
You are a traveler who keeps track of countries you want to visit in countries
list and those you have already visited in visited_countries
. As you travel, it becomes harder to manage everything, so you decide to automate this process.
- Update
travel_list
to include only the countries fromcountries
that are not invisited_countries
.
Solution
Thanks for your feedback!
The First For Loop
Using loops you can iterate over sequences like lists
, strings
, or numerical ranges
, they allow to process large amounts of data with minimal code.
item
is a variable that takes the value of each element in the sequence one at a time;sequence
is the data you are iterating through, such as a list, string, or range;for
statement block is executed for everyitem
in the sequence.
Imagine you have a string variable and want to print each letter of it in a column. Since a string is a sequence of letters, you can use a loop to achieve this.
word = 'iteration' # Printing every letter in the city's name for letter in word: print(letter)
word
variable holds the string'iteration'
;for
loop iterates over each character in the string;letter
takes the value of the next character in the string in each iteration;print(letter)
statement outputs the current character to the console.
Make sure to name the item
variable meaningfully. For example, if you iterate through a list called people
, the appropriate variable name should be person
.
Swipe to start coding
You are a traveler who keeps track of countries you want to visit in countries
list and those you have already visited in visited_countries
. As you travel, it becomes harder to manage everything, so you decide to automate this process.
- Update
travel_list
to include only the countries fromcountries
that are not invisited_countries
.
Solution
Thanks for your feedback!