For Loop in Python (Practice Problem) – Python Tutorial

For Loop in Python (Practice Problem) – Python Tutorial

8 mins read55.2K Views Comment
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Sep 6, 2024 16:08 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.

2022_02_Python-for-Loop-1.jpg

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 Certifications

Content

Example 1: Print the first 10 natural numbers using for loop.


 
# 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
for i in range(1,n):
print(i)
Copy code

Output

1
2
3
4
5
6
7
8
9
10

Also Read: Tutorial: for loop in Python

Acquire in-depth knowledge of Networking, Hardware & Security. Enroll in our top programmes and online courses from the best colleges in India today to take the next step in your career!

Example 2: Python program to print all the even numbers within the given range.


 
# if the given range is 10
given_range = 10
for 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)
Copy code

Output

0
2
4
6
8

Also Read: Understanding Python for loop with example

Example 3: Python program to calculate the sum of all numbers from 1 to a given number.


 
# 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
for i in range(1,given_number+1):
sum+=i
# print the total sum at the end
print(sum)
Copy code

Output

55

Also Read: Python While Loop with Example

Example 4: Python program to calculate the sum of all the odd numbers within the given range.


 
# if the given range is 10
given_range = 10
# set up a variable to store the sum
# with initial value of 0
sum = 0
for 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)
Copy code

Output

25

Also Read: Pattern Program in Python

Example 5: Python program to print a multiplication table of a given number


 
# if the given range is 10
given_number = 5
for i in range(11):
print (given_number," x",i," =",5*i)
Copy code

Output

5 x 0 = 0
5 x 1 = 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: Python program to display numbers from a list using a for loop.


 
# if the below list is given
list = [1,2,4,6,88,125]
for i in list:
print(i)
Copy code

Output

1
2
4
6
88
125

Also Read: How to use Pass statement in Python

Example 7: Python program to count the total number of digits in a number.


 
# 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 = str(given_number)
# declare a variable to store
# the count of digits in the
# given number with value 0
count=0
for i in given_number:
count += 1
# print the total count at the end
print(count)
Copy code

Output

6

Also Read: Iterators in iterators in Python

Packing and Unpacking Arguments in Python
Packing and Unpacking Arguments in Python
When talking about functions in Python, the terms “arguments” and “keyword arguments” are introduced. During the function definition, we frequently encounter *args and **kwargs being passed as arguments. When talking...read more
Python assert (): A Beginner Guide to Understanding and Using Keyword
Python assert (): A Beginner Guide to Understanding and Using Keyword
The assert statement in Python is used for debugging purposes, allowing developers to test assumptions in their code. It evaluates a condition, and if the condition is false, it raises...read more
How to Use float () Function in Python
How to Use float () Function in Python
Float function is a built-in function in python that returns the floating-point number of a numeric value or a string representation of a numeric value. In this article, we will...read more

Example 8: Python program to check if the given string is a palindrome.


 
# given string
given_string = "madam"
# an empty string variable to store
# the given string in reverse
reverse_string = ""
# iterate through the given string
# and append each element of the given string
# to the reverse_string variable
for i in given_string:
reverse_string = i + reverse_string
# if given_string matches the reverse_srting exactly
# the given string is a palindrome
if(given_string == reverse_string):
print("The string", given_string,"is a Palindrome.")
# else the given string is not a palindrome
else:
print("The string",given_string,"is NOT a Palindrome.")
Copy code

Output

The string madam is a Palindrome String.

Also Read: Difference between while and do while loop

 

Example 9: Python program that accepts a word from the user and reverses it.


 
# input string from user
given_string = input()
# an empty string variable to store
# the given string in reverse
reverse_string = ""
# iterate through the given string
# and append each element of the given string
# to the reverse_string variable
for i in given_string:
reverse_string = i + reverse_string
# print the reverse_string variable
print(reverse_string)
Copy code

Input

Naukri

Output

irkuaN

Also Read: Getting started with Python String

Example 10: Python program to check if a given number is an Armstrong number


 
# the given number
given_number = 153
# convert given number to string
# so that we can iterate through it
given_number = str(given_number)
# store the lenght of the string for future use
string_length = 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
for i in given_number:
sum += int(i)**string_length
# if the sum matches the given string
# its an amstrong number
if sum == int(given_number):
print("The given number",given_number,"is an Amstrong number.")
# if the sum do not match with the given string
# its an amstrong number
else:
print("The given number",given_number,"is Not an Amstrong number.")
Copy code

Output

The given number 153 is an Amstrong number.

Also Read: Generators in Python

 

Example 11: Python program to count the number of even and odd numbers from a series of numbers.


 
# given list of numbers
num_list = [1,3,5,6,99,134,55]
# iterate through the list elemets
# using for loop
for 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.")
Copy code

Output

1 is an odd number.
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: Python program to display all numbers within a range except the prime numbers.


 
# import the math library
import math
# 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
flag = False
# iterate in the given range
# using for loop starting from 2
# as 0 & 1 are neither prime
# nor composite
for i in range(2, int(math.sqrt(n)) + 1):
# condition to check if a
# number is prime or not
if n % i == 0:
flag = True
return flag
# lower bound of the range
range_starts = 10
# upper bound of the range
range_ends = 30
print("Non-prime numbers between",range_starts,"and", range_ends,"are:")
for number in filter(is_not_prime, range(range_starts, range_ends)):
print(number)
Copy code

Output

Non-prime numbers between 10 and 30 are:
10
12
14
15
16
18
20
21
22
24
25
26
27
28

Also Read: Python Sets Practice Program for Beginners

Example 13: Python program to get the Fibonacci series between 0 to 50.


 
# given upper bound
num = 50
# initial values in the series
first_value,second_value = 0, 1
# iterate in the given range
# of numbers
for 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 nextnum:
break
# print each element that
# satisfies all the above conditions
print(next)
Copy code

Output

1
2
3
5
8
13
21
34

Example 14: Python program to find the factorial of a given number.


 
# given number
given_number= 5
# since 1 is a factor
# of all number
# set the factorial to 1
factorial = 1
# iterate till the given number
for i in range(1, given_number + 1):
factorial = factorial * i
print("The factorial of ", given_number, " is ", factorial)
Copy code

Output

The factorial of 5 is 120

Example 15: Python program that accepts a string and calculates the number of digits and letters.


 
# take string input from user
user_input = input()
# declare 2 variable to store
# letters and digits
digits = 0
letters = 0
# iterate through the input string
for 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
digits=digits+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
letters=letters+1
print(" The input string",user_input, "has", letters, "letters and", digits,"digits.")
Copy code

Input

Naukri1234

Output

The input string Naukri12345 has 6 letters and 5 digits.

Example 16: Write a Python program that iterates the integers from 1 to 25.


 
# given range
given_range = 25
# iterate using a for loop till the
# given range
for 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("fizzbuzz")
# continue with the loop
continue
# if no. is divisible by 4
# print fizz and no by 5
if i % 4 == 0 and i%5!=0:
print("fizz")
# continue with the loop
continue
# 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)
Copy code

Output

fizzbuzz
1
2
3
fizz
buzz
6
7
fizz
9
buzz
11
fizz
13
14
buzz
fizz
17
18
19
fizzbuzz
21
22
23
fizz
buzz

Example 17: Python program to check the validity of password input by users.


 
# input password from user
password = input()
# set up flags for each criteria
# of a valid password
has_valid_length = False
has_lower_case = False
has_upper_case = False
has_digits = False
has_special_characters = 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_length = True
# iterate through each characters
# of the password
for i in password:
# check if there are lowercase alphabets
if (i.islower()):
has_lower_case = True
# check if there are uppercase alphabets
if (i.isupper()):
has_upper_case = True
# check if the password has digits
if (i.isdigit()):
has_digits = True
# check if the password has special characters
if(i=="@" or i=="$" or i=="_"or i=="#" or i=="^" or i=="&" or i=="*"):
has_special_characters = True
if (has_valid_length==True and has_lower_case ==True and has_upper_case == True and has_digits == True and has_special_characters == True):
print("Valid Password")
else:
print("Invalid Password")
Copy code

Input
Naukri12345@
Output

Naukri12345@

Example 18: Python program to convert the month name to a number of days.


 
# given list of month name
month = ["January", "April", "August","June","Dovember"]
# iterate through each mont in the list
for i in month:
if i == "February":
print("The month of February has 28/29 days")
elif i in ("April", "June", "September", "November"):
print("The month of",i,"has 30 days.")
elif i in ("January", "March", "May", "July", "August", "October", "December"):
print("The month of",i,"has 31 days.")
else:
print(i,"is not a valid month name.")
Copy code

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

Top Trending 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

What is a for loop in Python?

A for loop is a control flow statement that iterates over a sequence of elements in Python, such as a list, tuple, or string.

How do I use a for loop in Python?

To use a for loop in Python, you can use the "for" keyword followed by a variable name, the "in" keyword, and then the sequence you want to iterate over. For example: my_list = [1, 2, 3] for num in my_list: print(num).

What is the range() function in Python?

The range() function is a built-in function in Python that returns a sequence of numbers, starting from 0 (by default) and incrementing by 1 (by default), and stopping before a specified number. It can be used with a for loop to iterate a specific number of times. For example: for num in range(5): print(num) This will print the numbers 0 through 4, one at a time.

Can I use a for loop with a dictionary in Python?

Yes, you can use a for loop with a dictionary in Python. By default, a for loop will iterate over the keys of a dictionary. For example: my_dict = {"a": 1, "b": 2, "c": 3} for key in my_dict: print(key, my_dict[key]) This will print each key-value pair in the dictionary, one at a time.

About the Author
author-image
Vikram Singh
Assistant Manager - Content

Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio