Menu
Python Loops
In Python programming, there are two primitive loop statements:
- while loop
- for loop
1) while loop:
In this type of loop we can execute a set of statements as long as the condition is true. The following example shows this:
# calculate sum of digits using 'while' loop
num = input("Enter a number: ")
n = int(num)
sum = 0
while n != 0:
m = n % 10
n = n // 10
sum = sum + m
print("Sum of digits:", sum)
Output:
Enter a number: 1234
Sum of digits: 10
2) for loop:
This type of loop is used for iterating over a sequence. In Python, there is no C style of for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for each loop in other languages.
Using the break statement we can also stop the loop before it has looped through all the elements. The following example shows this:
# Checking prime number using 'for' loop
x = input('Enter an integer: ')
num = int(x)
for i in range(2, int(num/2)):
if num % i == 0:
print(num, 'is not a prime number')
break
if i+1 == int(num/2):
print(num, 'is a prime number')
Output:
Enter an integer: 113
113 is a prime number