The for loop in python is used to iterate over a sequence or other iterable objects.
The range() function returns the sequence of numbers from 0(by default) with an increment with 1(by default) , and ends at that fixed number.
Syntax: for (variable_name) in range: # body of for
#basic for loop program in python
for i in range(1,11):
print(i)
Output:
1
2
3
4
5
6
7
8
9
10
# Python program to find the factorial of a number provided by the user.
# change the value for a different result
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num < 0:
print("Sorry, factorial does not exist for negative numbers") elif
num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num+1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Output:
Enter a number: 5
The factorial of 5 is 120
#use of break statement
# Python program to display all the prime numbers within an interval
lower = int(input("Enter lower range: "))
upper = int(input("Enter upper range: "))
#print("Prime numbers between",lower,"and",upper,"are:")
for num in range(lower,upper + 1):
# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)