Martin McBride, 2018-07-24
Tags for loop range while loop input print
Categories python language beginning python
A loop in Python is a way to run the same code over and over. In Python, there are two different types of loops – for loops and while loops.
About this lesson
In this lesson we will look at:
- for loops
- while loops
A for loop provides a way to execute the same code multiple times. Here is an example:
for i in range(5): print("Hello, world!")
This loop prints Hello, world! five times:
Hello, world! Hello, world! Hello, world! Hello, world! Hello, world!
Anatomy of a for loop
The for loop looks something like this:
if <var> in range(n): <body>
<var> is the loop variable (
i in our case).
range(n) controls how many times the loop will run.
<body> is one or more lines of Python code that are executed each time the loop runs.
Important points are:
- The for statement ends in a colon character :
- Each line of the body is indented by 4 spaces
As with if statements, the indentation is vital – it is the only way Python knows which statements are part of the body, and which ones are part of the rest of the program. Each line of the body should be indented by exactly 4 spaces. At the end of the body, the next line of code should return to the previous level of indentation (the same as the if statement itself):
for i in range(5): print("Hello, world!") print("finished")
In this case, the second print statement is not part of the loop body, because it is not indented. This means that Hello, world! is printed 5 times as part of the loop, but finished is only printed once after the loop has completed.
The loop variable
The loop variable (called
i in the code above) is an important part of the loop. It holds the loop count value, that is, how many times we have been through the loop.
The loop variable doesn't have to be called
i, you can use any name for it. In this example we have called it counter and we will print its value each time through the loop:
for counter in range(5): print(counter)
0 1 2 3 4
On the first pass through the loop,
counter is equal to 0. On the second pass, it is equal to 1, and so on, counting up to 4.
range(n) will count from 0 up to n-1, which means that the loop will execute n times.
The range function
range can be used to create loops that count from 0 to
n-1 as we have seen. There are a couple of other options too.
Changing the start value
You can call range with two parameters, the start value and the end value:
for counter in range(1, 6): print(counter)
1 2 3 4 5
The rule is that the range goes from the start value (1 in this case) up to but not including the end value (6 in this case).
The loop will execute
end – start times.
Using a step value
You can also add a third parameter, a step value:
for counter in range(1, 6, 2): print(counter)
1 3 5
This time the value counts from 1 up to but not including 6, in steps of 2.
Python has another type of loop that works slightly differently. Whereas a for loop typically runs for a fixed number of times, a while loop continues running while ever a particular condition is true. It might run a few times, many times, or even forever. Or it might not run at all.
Here is an example:
x = 5 while x > 0: print(x) x = x – 1 print("finished")
The code starts by assigning a value 5 to the variable
We then enter the loop. The loop will execute while ever
x is greater than zero. Since x is currently equal to 5, it is greater than zero, to the loop executes.
The loop body contains two statements:
- It prints the current value of
- It sets
x – 1, ie 4 in this case.
We are now at the end of the body of the loop, so we go back to the start of the loop. Again we check that
x is greater than 0, print the current value of
x (which is now 4), then decrease
This is repeated with
x set to 3, 2 and 1.
After printing 1, the value of
x is decreased to zero. Now when we start the loop again, the test
x > 0 is no longer true. The loop stops and the program carries on to the next line after the loop, printing 'finished'. The output of this program is:
5 4 3 2 1 finished
Example - getting user input
Here is another example. We will ask the user their name, then print a greeting. However, if the user doesn't enter a name, we will ask them again, and again, and again until they relent:
name = input("What is your name?") while name == "": name = input("Please try again") print("Hello", name)
In the first line, we ask for the user's name. They can either enter a name or just enter nothing and hit return.
We then enter the loop that checks the
name variable. The test checks
name against the empty string "". The operator == checks for two values being equal.
name contains some text, the test fails (
name is not equal to the empty string) so the loop doesn't execute at all. We just print the greeting.
If the user did not enter anything,
name will be an empty string, so the loop will run. The body of the loop asks them to try again. They get another chance to enter their name then the code returns to the start of the loop and tests
name now contains some text, the loop will be skipped and the greeting will be printed. If
name is still empty, we run the loop again. This will continue until the user enters a string.
There are several condition operators similar to > and ==. We will look at these in more detail in the section on if statements.