We use loops if some code must be repeated multiple times. It can be either a fixed number of times or an indefinite number of times, until a condition is met. There are two types of loops: for loops and while loops. Let’s talk about for loops first.
Table of Contents
for Loops
We can use the for loop to iterate over the elements of a collection. The collection may be a sequence (like a string), a set, or a dictionary.
The syntax is: After the for keyword we use a loop variable that will be set to each of the elements iterated over during the loop execution in turn and after that we use the name of the collection and finally there’s a colon. After the colon, in the next line, the block of code begins with instructions to be executed on each loop run. This repeated code is called the body of the loop.
Here’s a simple example with a string collection:
word = "good"
number = 1
for letter in word:
print("Letter number " + str(number) + ": " + letter)
number = number + 1
Output:
Letter number 1: g
Letter number 2: o
Letter number 3: o
Letter number 4: d
while Loops
The while loop is used if we don’t know how many times the code should be repeated, but usually the loop runs as long as there’s a condition that is met. So, this is a condition-controlled loop.
Right after the while keyword we write the condition. It will be checked on each loop run. As long as it’s met, the loop will run. As soon as the condition is no longer met, the loop stops. After the condition we use a colon, and in the next line we start writing the code that will be repeated – the body of the loop. Naturally, this block of code is indented appropriately. The variables that we’re using have to be initialized before.
Here’s an example:
letter_to_guess = "p"
your_guess = ""
while your_guess != letter_to_guess:
your_guess = input("Enter a letter: ")
if your_guess != letter_to_guess:
print("Wrong. Try again.")
else:
print("Correct!")
Possible output:
Enter a letter: e
Wrong. Try again.
Enter a letter: s
Wrong. Try again.
Enter a letter: y
Wrong. Try again.
Enter a letter: p
Correct!
Infinite loops
It may happen that the condition in the while statement is always true. Then the loop never stops. We call such loops infinite loops. Oftentimes they’re a result of our mistake. If we happen to be trapped in such a loop, we can use the Keyboard Interrupt combination (Ctrl + C) to get out of it. Here’s an example of such an infinite loop:
number = 1
while number == 1:
x = input("Enter a number: ")
print(x)
As number is equal to 1 all the time (its value isn’t changed inside the loop), the condition is always true and the loop is infinite.
QUIZ
1. In Python we don’t have the … loop: |
A) for |
B) foreach |
C) while |
TRUE OR FALSE?
1) After the for keyword we use a loop variable that will be set to each of the elements iterated over during the loop execution in turn. |
2) In infinite loops the condition in the while statement is always true. |
WHAT’S THE OUTPUT?
1)
>>> letters = "help"
>>> message = ""
>>> for letter in letters:
... message = message + "**" + letter + "**"
...
>>> print(message)
2)
>>> x = 5
>>> while x < 10:
... print(x)
... x = x + 1
...
SOLUTION
QUIZ
1. In Python we don’t have the … loop: |
A) for |
B) foreach |
C) while |
TRUE OR FALSE?
1) After the for keyword we use a loop variable that will be set to each of the elements iterated over during the loop execution in turn. True |
2) In infinite loops the condition in the while statement is always true. True |
WHAT’S THE OUTPUT?
1)
>>> letters = "help"
>>> message = ""
>>> for letter in letters:
... message = message + "**" + letter + "**"
...
>>> print(message)
Output:
**h****e****l****p**
2)
>>> x = 5
>>> while x < 10:
... print(x)
... x = x + 1
...
Output:
5
6
7
8
9
PROJECT
'''
Loops - Project
CONSONANTS AND VOWELS
__________________________________________________________
Your task is to write a program that runs as many times as the user
wants it to. The user is asked to enter a word and the program prints
a message about each letter in the word, informing us whether the letter
is a consonants or a vowel.
And here's how you should write this program:
#1. First of all we must tell the program what vowels and consonants are.
The easiest way to do it is to tell it what vowels are and any letter
that is not a vowel, is automatically a consonant. We could use a list
of vowels to this end, but as we didn't talk about lists yet, let's
use a string. The program can loop over all the letters in the string.
So, create a string variable called vowels and assign to it a string
containing all the vowels: a, e, i, o, u.
#2. Create the loops.
When the program finishes execution, the user should be able to decide
whether or not to run it again. So, we'll need the following:
- a variable that stores the user's decision (yes or no), let's call it
run_again
- a condition-controlled loop that will run as long as run_again is equal
to "yes"
If a condition-controlled loop is what we need, which do we choose: for
or while? Definitely while. The main body of the program is going to be
enclosed in this loop.
As we're going to use the variable run_again in the condition of loop,
we have to define it before the loop and set it to "yes" so that the loop
executes at least once.
What do we want to put in the while loop? Well, first the user must be
asked to enter a word and the word should be saved in a variable called
word.
And then comes the main body of our program, which is another loop.
This loop should loop over all the letters of the word entered by the user
and print a message like this (if the user entered the word "one"):
o - vowel
n - consonant
e - vowel
This time, a for loop seems a better option. So, write a for loop that
loops over all the letters and prints a line of text like the ones above.
Use concatenation to format the strings. Inside the for loop make use
of conditional statements to decide which version to print for any particular
letter (consonant or vowel).
Hint: Use the in membership operator to check whether an element belongs to a string. For example:
'a' in 'hat'
returns True because the character a belongs to the string 'hat'.
Before the while loop is finished, the user should be asked if they want
to run the program again. The user input should be assigned to the variable
run_again so that the condition may be checked again in the while loop.
So, to sum it up, here's what we have to do in this step:
- create the run_again variable
- create the main program loop (while loop)
- create the for loop inside the while loop
- write code that asks the user if they want to run the program again
Be very careful about indentation! What belongs to the while loop? What
to the for loop?
'''
PROJECT SOLUTION
##1.
vowels = "aeiou"
##2.
run_again = "yes"
while run_again == "yes":
word = input("Enter a word: ")
for letter in word:
if letter in vowels:
print(letter + " - vowel")
else:
print(letter + " - consonant")
run_again = input("Wanna run the program again (yes / no)? ")