Python for loop:
The for loop in Python is used to iterate over the elements of a sequence such as a string, tuple, list, or other iterable objects.
The signature for the
for statement is as shown below. Here, else block is optional.
for target_list in expression_list : suite/Block of statements [else: suite/block of statements]
Flow diagram – for statement :
Python for statement Examples:
Example 1: In this example, we will create a list of odd and even numbers from an existing list.
#Initializing l=[11,12,30,41,25,6] ev= od= #Using for loop for i in l: if(i%2==0): ev.append(i) else: od.append(i) #Printing print(ev) print(od)
[12, 30, 6] [11, 41, 25]
Example 2: In this case, we will print even numbers less than 10 using for loop.
#Initializing for i in range(1,10): if i%2!=0: i=i+1 continue else: print(i) i=i+1
2 4 6 8
Example 3: In this example, We will check whether a number is a prime number or not using the range() function.
#Initializing n=19 # Using for statement with else clause and printing for i in range(2, int(n/2)+1): if (n % i) == 0: print(n, "is not a prime number") break else: print(n, "is a prime number")
19 is a prime number
Happy Learning 🙂