For Loop in Python (Practice Problem) – Python Tutorial –
Shiksha Online
Shiksha Online
Updated on Dec 29, 2023 16:37 IST
for loop in python is used to iterate over a sequence or an iterable object (such as a
list, tuple, or string). In this article, we will discuss 18 different examples of python for
loop.
For loops in Python is designed to repeatedly execute the code block while iterating
over a sequence or an iterable object such as list, tuple, dictionary, sets. In this
article, we will briefly discuss for loop in Python with different examples.
Must Check: Python Online Course and Certif ications
Content
Example 1: Print the f irst 10 natural numbers using f or loop.
Example 2: Python program to print all the even numbers within the given range.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Example 3: Python program to calculate the sum of all numbers f rom 1 to a given number.
Example 4: Python program to calculate the sum of all the odd numbers within the given
range.
Example 5: Python program to print a multiplication table of a given number
Example 6: Python program to display numbers f rom a list using a f or loop.
Example 7: Python program to count the total number of digits in a number.
Example 8: Python program to check if the given string is a palindrome.
Example 9: Python program that accepts a word f rom the user and reverses it.
Example 10: Python program to check if a given number is an Armstrong number
Example 11: Python program to count the number of even and odd numbers f rom a series
of numbers.
Example 12: Python program to display all numbers within a range except the prime
numbers.
Example 13: Python program to get the Fibonacci series between 0 to 50.
Example 14: Python program to f ind the f actorial of a given number.
Example 15: Python program that accepts a string and calculates the number of digits and
letters.
Example 16: Write a Python program that iterates the integers f rom 1 to 25.
Example 17: Python program to check the validity of password input by users.
Example 18: Python program to convert the month name to a number of days.
Example 1: Print t he f irst 10 nat ural numbers using f or loop.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Copy code
# between 0 to 10
# there are 11 numbers
# therefore, we set the value
# of n to 11
n = 11
# since for loop starts with
# the zero indexes we need to skip it and
# start the loop from the first index
f or i in range(1,n):
print (i)
Output
1
2
3
4
5
6
7
8
9
10
Also Read: T utorial: f or loop in Python
Acquire in-depth knowledge of Networking, Hardware & Security. Enroll in our top
programmes and online courses f rom the best colleges in India today to take the next step in
your career!
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Example 2: Pyt hon program t o print all t he even numbers wit hin t he given
range.
Copy code
# if the given range is 10
given_range = 10
f or i in range(given_range):
# if number is divisble by 2
# then it's even
if i%2==0:
# if above condition is true
# print the number
print (i)
Output
0
2
4
6
8
Also Read: Understanding Python f or loop with example
Example 3: Pyt hon program t o calculat e t he sum of all numbers f rom 1 t o a
given number.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Copy code
# if the given number is 10
given_number = 10
# set up a variable to store the sum
# with initial value of 0
sum = 0
# since we want to include the number 10 in the sum
# increment given number by 1 in the for loop
f or i in range(1,given_number+1):
sum+=i
# print the total sum at the end
print (sum)
Output
55
Also Read: Python While Loop with Example
Example 4: Pyt hon program t o calculat e t he sum of all t he odd numbers wit hin
t he given range.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Copy code
# if the given range is 10
given_range = 10
# set up a variable to store the sum
# with initial value of 0
sum = 0
f or i in range(given_range):
# if i is odd, add it
# to the sum variable
if i%2!=0:
sum+=i
# print the total sum at the end
print (sum)
Output
25
Also Read: Pattern Program in Python
Example 5: Pyt hon program t o print a mult iplicat ion t able of a given number
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Copy code
# if the given range is 10
given_number = 5
f or i in range(11):
print (given_number," x",i," =",5*i)
Output
5x0=0
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Also Read: Flow Control in Python
Example 6: Pyt hon program t o display numbers f rom a list using a f or loop.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Copy code
# if the below list is given
list = [1,2,4,6,88,125]
f or i in list :
print (i)
Output
1
2
4
6
88
125
Also Read: How to use Pass statement in Python
Example 7: Pyt hon program t o count t he t ot al number of digit s in a number.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Copy code
# if the given number is 129475
given_number = 129475
# since we cannot iterate over an integer
# in python, we need to convert the
# integer into string first using the
# str() function
given_number = st r(given_number)
# declare a variable to store
# the count of digits in the
# given number with value 0
count =0
f or i in given_number:
count += 1
# print the total count at the end
print (count )
Output
Also Read: Iterators in iterators in Python
Packing and Unpacking Argument s in Pyt hon
When talking abo ut functio ns in Pytho n, the terms “arguments” and “keywo rd
arguments” are intro duced. During the functio n definitio n, we frequently
enco unter *args and **kwargs being passed as arguments.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Pyt hon assert (): A Beginner Guide t o Underst anding and…
Using Keyword
In this article, we will learn ho w, and when to use the assert() statement in
pytho n with the help o f examples. Later in the article we will also discuss the...re ad m o re
How t o Use f loat () Funct ion in Pyt hon
Flo at functio n is a built-in functio n in pytho n that returns the flo ating-po int
number o f a numeric value o r a string representatio n o f a numeric value. In this
article, we will...re ad m o re
Example 8: Pyt hon program t o check if t he given st ring is a palindrome.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Copy code
# given string
given_st ring = "madam"
# an empty string variable to store
# the given string in reverse
reverse_st ring = ""
# iterate through the given string
# and append each element of the given string
# to the reverse_string variable
f or i in given_st ring:
reverse_st ring = i + reverse_st ring
# if given_string matches the reverse_srting exactly
# the given string is a palindrome
if (given_st ring == reverse_st ring):
print ("T he st ring", given_st ring,"is a Palindrome.")
# else the given string is not a palindrome
else:
print ("T he st ring",given_st ring,"is NOT a Palindrome.")
Output
The string madam is a Palindrome String.
Also Read: Dif f erence between while and do while loop
Example 9: Pyt hon program t hat accept s a word f rom t he user and reverses it .
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Copy code
# input string from user
given_st ring = input ()
# an empty string variable to store
# the given string in reverse
reverse_st ring = ""
# iterate through the given string
# and append each element of the given string
# to the reverse_string variable
f or i in given_st ring:
reverse_st ring = i + reverse_st ring
# print the reverse_string variable
print (reverse_st ring)
Input
Naukri
Output
irkuaN
Also Read: Getting started with Python String
Example 10: Pyt hon program t o check if a given number is an Armst rong
number
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Copy code
# the given number
given_number = 153
# convert given number to string
# so that we can iterate through it
given_number = st r(given_number)
# store the lenght of the string for future use
st ring_lengt h = len(given_number)
# initialize a sum variable with
# 0 value to store the sum of the product of
# each digit
sum = 0
# iterate through the given string
f or i in given_number:
sum += int (i)**st ring_lengt h
# if the sum matches the given string
# its an amstrong number
if sum == int (given_number):
print ("T he given number",given_number,"is an Amst rong number.")
# if the sum do not match with the given string
# its an amstrong number
else:
print ("T he given number",given_number,"is Not an Amst rong number.")
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Output
The given number 153 is an Amstrong number.
Also Read: Generators in Python
Example 11: Pyt hon program t o count t he number of even and odd numbers
f rom a series of numbers.
Copy code
# given list of numbers
num_list = [1,3,5,6,99,134,55]
# iterate through the list elemets
# using for loop
f or i in num_list :
# if divided by 2, all even
# number leave a remainder of 0
if i%2==0:
print (i,"is an even number.")
# if remainder is not zero
# then it's an odd number
else:
print (i,"is an odd number.")
Output
1 is an odd number.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
3 is an odd number.
5 is an odd number.
6 is an even number.
99 is an odd number.
134 is an even number.
55 is an odd number.
Also Read : Lists in Python
Example 12: Pyt hon program t o display all numbers wit hin a range except t he
prime numbers.
Copy code
# import the math library
import mat h
# function to print all
# non-primes in a range
def is_not _prime(n):
# flag to track
# if no. is prime or not
# initially assume all numbers are
# non prime
f lag = False
# iterate in the given range
# using for loop starting from 2
# as 0 & 1 are neither prime
# nor composite
f or i in range(2, int (mat h.sqrt (n)) + 1):
# condition to check if a
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
# condition to check if a
# number is prime or not
if n % i == 0:
f lag = T rue
ret urn f lag
# lower bound of the range
range_st art s = 10
# upper bound of the range
range_ends = 30
print ("Non-prime numbers bet ween",range_st art s,"and", range_ends,"are:")
f or number in f ilt er(is_not _prime, range(range_st art s, range_ends)):
print (number)
Output
Non-prime numbers between 10 and 30 are:
10
12
14
15
16
18
20
21
22
24
25
26
27
28
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Also Read: Python Sets Practice Program f or Beginners
Example 13: Pyt hon program t o get t he Fibonacci series bet ween 0 t o 50.
Copy code
# given upper bound
num = 50
# initial values in the series
f irst _value,second_value = 0, 1
# iterate in the given range
# of numbers
f or n in range(0, num):
# if no. is less than 1
# move to next number
if (n <= 1):
next = n
# if number is within range
# execute the below code block
if next num:
break
# print each element that
# satisfies all the above conditions
print (next )
Output
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
2
3
5
8
13
21
34
Example 14: Pyt hon program t o f ind t he f act orial of a given number.
Copy code
# given number
given_number= 5
# since 1 is a factor
# of all number
# set the factorial to 1
f act orial = 1
# iterate till the given number
f or i in range(1, given_number + 1):
f act orial = f act orial * i
print ("T he f act orial of ", given_number, " is ", f act orial)
Output
The factorial of 5 is 120
Example 15: Pyt hon program t hat accept s a st ring and calculat es t he number
of digit s and let t ers.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Copy code
# take string input from user
user_input = input ()
# declare 2 variable to store
# letters and digits
digit s = 0
let t ers = 0
# iterate through the input string
f or i in user_input :
# check if the character
# is a digit using
# the isdigit() method
if i.isdigit ():
# if true, increment the value
# of digits variable by 1
digit s=digit s+1
# check if the character
# is an alphabet using
# the isalpha() method
elif i.isalpha():
# if true, increment the value
# of letters variable by 1
let t ers=let t ers+1
print (" T he input st ring",user_input , "has", let t ers, "let t ers and", digit s,"digit s.")
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Input
Naukri1234
Output
The input string Naukri12345 has 6 letters and 5 digits.
Example 16: Writ e a Pyt hon program t hat it erat es t he int egers f rom 1 t o 25.
Copy code
# given range
given_range = 25
# iterate using a for loop till the
# given range
f or i in range(given_range+1):
# if no. is multiple of 4 and 5
# print fizzbuzz
if i % 4 == 0 and i % 5 == 0:
print ("f izzbuzz")
# continue with the loop
cont inue
# if no. is divisible by 4
# print fizz and no by 5
if i % 4 == 0 and i%5!=0:
print ("f izz")
# continue with the loop
cont inue
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
# if no. is divisible by 5
# print buzz and not by 4
if i % 5 == 0 and i % 4!= 0:
print ("buzz")
else:
# else just print the no.
print (i)
Output
fizzbuzz
1
2
3
fizz
buzz
6
7
fizz
9
buzz
11
fizz
13
14
buzz
fizz
17
18
19
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
fizzbuzz
21
22
23
fizz
buzz
Example 17: Pyt hon program t o check t he validit y of password input by users.
Copy code
# input password from user
password = input ()
# set up flags for each criteria
# of a valid password
has_valid_lengt h = False
has_lower_case = False
has_upper_case = False
has_digit s = False
has_special_charact ers = False
# first verify if the length of password is
# higher or equal to 8 and lower or equal to 16
if (len(password) >= 8) and (len(password)<=16):
has_valid_lengt h = T rue
# iterate through each characters
# of the password
f or i in password:
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
# check if there are lowercase alphabets
if (i.islower()):
has_lower_case = T rue
# check if there are uppercase alphabets
if (i.isupper()):
has_upper_case = T rue
# check if the password has digits
if (i.isdigit ()):
has_digit s = T rue
# check if the password has special characters
if (i=="@" or i=="$" or i=="_"or i=="# " or i=="^" or i=="&" or i=="*"):
has_special_charact ers = T rue
if (has_valid_lengt h==T rue and has_lower_case ==T rue and has_upper_case
== T rue and has_digit s == T rue and has_special_charact ers == T rue):
print ("Valid Password")
else:
print ("Invalid Password")
Input
Naukri12345@
Output
Naukri12345@
Example 18: Pyt hon program t o convert t he mont h name t o a number of days.
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
Copy code
# given list of month name
mont h = ["January", "April", "August ","June","Dovember"]
# iterate through each mont in the list
f or i in mont h:
if i == "February":
print ("T he mont h of February has 28/29 days")
elif i in ("April", "June", "Sept ember", "November"):
print ("T he mont h of ",i,"has 30 days.")
elif i in ("January", "March", "May", "July", "August ", "Oct ober", "December"):
print ("T he mont h of ",i,"has 31 days.")
else:
print (i,"is not a valid mont h name.")
Output
The month of January has 31 days.
The month of April has 30 days.
The month of August has 31 days.
The month of June has 30 days.
November is not a valid month name
T op T rending Articles:
Data Analyst Interview Questions | Data Science Interview Questions | Machine Learning
Applications | Big Data vs Machine Learning | Data Scientist vs Data Analyst | How to Become
a Data Analyst | Data Science vs. Big Data vs. Data Analytics | What is Data Science | What is
a Data Scientist | What is Data Analyst
FAQs
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.
What is a f or loop in Python?
How do I use a f or loop in Python?
What is the range() f unction in Python?
Can I use a f or loop with a dictionary in Python?
Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 30 -Dec-20 23.