l = list((1, 2, 3, 4, 5))
for x in l:
print(x)
The program will print the following output:
1 2 3 4 5
Now, let’s say, we want to print all odd numbers from a list of numbers. We can implement it easily using the following way:
l = list((1, 2, 3, 4, 5))
for x in l:
if x % 2 == 0:
continue
else:
print(x)
Please note the usage of the continue statement. We are here printing all odd numbers from a list of numbers. So, we are iterating over all the numbers of the list and if the number is even, we are stopping the current iteration of the for loop and continuing with the next iteration. If the number is odd, then the number is printed.
Now, let’s say we do not want to print all the odd numbers of the list. We want to check whether the list contains at least one odd number. We can implement it easily in the following way:
l = list((1, 2, 3, 4, 5))
for x in l:
if x % 2 == 0:
continue
else:
print("The list contains an odd number")
break
Please note the usage of the break statement. Here, we are iterating over all the numbers of the list. If a number in the list is even, we are stopping the current iteration of the loop and continuing with the next iteration. But, if the number is odd, we are using the break statement to come out of the loop.
The above program will print the following output:
The list contains an odd number
In Python, we can also use an else clause with a for loop. For example,








































0 Comments