Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Python For Loops

name = input(“Enter your name: ”)


for x in range(1,3):
print(name)
This will ask the user to enter their name and it will use a loop to display it. The variable “x” is a
temporary variable used to count the position in the loop. The range section states the starting
value of x and the end value of x. When the end value (in this case 3) is reached the loop will stop so
this loop will display the name twice as when it gets to the third loop it will stop before the name is
displayed.
for x in range(1,10,2):
print(x)
This program will display the value of x and in this instance it will be 1, 3, 5, 7, 9 as it wills start at 1,
end when it gets to 10 (without displaying the final value) and will step up in values of 2.

word = input(“Enter a word: ”)


for x in word:
print(x)
This will ask the user to enter a word and will display each letter in that word on a separate line.

Using the range statement


Read each for loop and write the output you will get. You may want to type it into Python and test it
out to help you get the answer.

Program Output
for x in range(1,10):
print(x)

for x in range(1,10,2):
print(x)

for x in range(100,0,-10):
print(x)

for x in range(0,21,5):
print(x)

Page 1
© Nichola Lacey 2018
Correcting Code
The user wants to display a count down from 10 to 1 and then display “Blast Off” but the following
code is not working. Why is this.?

Create your own code


Make sure you save each program with a sensible name. To save time you
can reuse and adapt your old programs to help you create new programs.

1. Create a program that will ask the user to a word and display that word 5 times.

2. Create a program that will ask the user to input a number and their name and display their
name that number of times.

3. Create a loop that will create a variable called total which will have a starting value of 0. Use
a loop to ask the user to enter three numbers and add them to the total. At the end display
the total.

4. Ask the user to enter a word and display each letter in that word on a separate numbered
line. For instance if they enter “hello”, it should display:

Page 2
© Nichola Lacey 2018

You might also like