PYTHON FOR LOOP SS1
PYTHON PROGRAMMING
LANGUAGE
PYTHON FOR LOOPS
The most
powerful thing about computers is that they can repeat things over and over
very quickly. There are several ways to repeat things in Python, the most
common of which is the for loop.
Example 1 .
The following
program will print Godliness, Focus and Excellence
ten times:
for i in
range(10):
print('Godliness, Focus, and
Excellence')
The
structure of a for loop is as follows:
for variable name in range( number of times to
repeat ):
statements to be repeated
The syntax
is important here. The word for must be in lowercase, the first line must end
with a colon, and the statements to be repeated must be indented. Indentation
is used to tell Python which statements will be repeated.
Example 2 .
The program below asks the user for a number
and prints its square, then asks for another number and prints its square, etc.
It does this three times and then prints that the loop is done.
for i in range(3): num = eval(input('Enter a
number: '))
print ('The square of your number is',
num*num)
print('The
loop is now done.')
Comments
Post a Comment