Python Programming

For loop in Python

In Programming, Python by Baqir Ali

For loop is used to repeat one or multiple statements any number of times. We use a for loop when the number of iteration is known to the user.

Syntax for for loop in Python

<for keyword> <counter variable> in expression:
      statements to be executed

Here are few examples of for loop in Python

Example 1: Prints ‘Hello’ 10 times

for i in range(10):
    print("Hello")

Output:

Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello

in the above example variable ‘i’ is the counter variable that counts to 10 and each time increments by 1 until reaches 10.

Example 2: looping through each character of the sentence

phrase="Hello Programmers"
for letter in phrase:
    print(letter)

Output:

H
e
l
l
o

P
r
o
g
r
a
m
m
e
r
s

Start for loop initial value from 1 instead of 0 in Python

Example 3: Asking a number to print the table

val=input("Enter number for table ")
val=int(val)
for i in range(1, 10):
    print(val," x ",i," = ",(i*val))

Output:

Enter number for table 3
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27

Support us by sharing this post