Python For loops with examples
In python we will use for loops for iterative process. We can iterate strings, lists, tuples, dictionaries with sequence order.
Syntax:
for variable in sequence
body
Example :
#python for loop example program
values = [5,8,9,7,8,9,10]
# iterate over the list
for val in values:
print(val)
Output:
5 8 9 7 8 9
python for loop program to add 2 with list.
values = [5,8,9,7,8,9,10]
#addition all list values with 2
# iterate over the list
for val in values:
print(val+2)
Output:
7 10 11 9 10 11 12
For loop with range :
Range function: It is used to print the sequence numbers, it has start and stop function, By using this we can print specific range numbers.
Example:
print(list(range(10)))
Output:
print(list(range(2,10)))
Output:
Example:
for i in range(10):
print(i)
Output:
0 1 2 3 4 5 6 7 8 9
for i in range(2,10): print(i*2)
Output:
4 6 8 10 12 14 16 18
For loop with if function :
We can use if condition in for loop with range function. In this below example i am printing even numbers.
for i in range(0,10): if i % 2 == 0 : print('Even number :', i)
Output:
Even number : 0 Even number : 2 Even number : 4 Even number : 6 Even number : 8
For loop with if else :
We will use for loop with if else condition. Here i am providing the even and odd number example. First it iterates the value in then go with if condition if the condition is true it prints the even number . Then it will goes to else block it print odd number.
Example Program:
for i in range(0,10): if i % 2 == 0 : print('Even number :', i) else: print('Odd Number :', i)
Output:
Even number : 0 Odd Number : 1 Even number : 2 Odd Number : 3 Even number : 4 Odd Number : 5 Even number : 6 Odd Number : 7 Even number : 8 Odd Number : 9