Python – For Loop Examples

Example 1
mycity=["Kalugumalai","Chennai","Madurai"]

for citynames in mycity:
        print (citynames)
        print ("hi")
Output:
======
Kalugumalai
hi
Chennai
hi
Madurai
hi
Example 2
mynumbers=[1,2,3,4,5]

for n in mynumbers:
        print (n)
Output:
======
1
2
3
4
5
Example.3
mynumbers=[2,4,6,8,10]

for n in mynumbers:
        print (n-1)
output:
1
3
5
7
9
Example 4: To Prints the numbers from 1 to 5
for i in range(1, 6):
    print(i)

Output :

1
2
3
4
5
Example 4 : To Prints charactors
# Define a string
word = "Hello"

# Start the for loop
for char in word:
    print(char)

Output :

H
e
l
l
o
Example 5 : Printing the Elements of a List
colors = ["red", "green", "blue"]

for color in colors:
    print(color)

Output :

red
green
blue
Example 6 : To Sum the Numbers in a List
numbers = [1, 2, 3, 4, 5]

total = 0

for number in numbers:
    total = total + number 

print("Total sum:", total)

Output :

Total sum: 15
Example 7:to Print Multiplication Table
# Define the number for which to print the multiplication table
number = 7

# Start the for loop
for i in range(1, 11):
    print(f"{number} x {i} = {number * i}")

Output :

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
...
7 x 10 = 70
Example 8: To Print Odd Numbers Only
mynumbers=[1,2,3,4,5,6,7,8,9,10]

for n in mynumbers:
    if(n%2=1)
        print (n)
Output : 
1
3
5
7
9
Example 9 : To Print Even Numbers from 1 to 100
for n in range(1,101):
    if(n%2=0)
        print (n)
Output :
2
4
6
.
.
.100
Example 10 :
mytable=2
for i in range(1,10):
     print(f"{i}  x  {mytable}  = {mytable* i}")
Output : 
1  x  2  = 2
2  x  2  = 4
3  x  2  = 6
4  x  2  = 8
5  x  2  = 10
6  x  2  = 12
7  x  2  = 14
8  x  2  = 16
9  x  2  = 18

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *