For Loop in Python (Practice Problem) – Python Tutorial
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 Certifications
Content
- Example 1: Print the first 10 natural numbers using for loop.
- Example 2: Python program to print all the even numbers within the given range.
- Example 3: Python program to calculate the sum of all numbers from 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 from a list using a for 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 from 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 from 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 find the factorial 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 from 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 the first 10 natural numbers using for loop.
# between 0 to 10# there are 11 numbers# therefore, we set the value# of n to 11n = 11 # since for loop starts with# the zero indexes we need to skip it and# start the loop from the first indexfor i in range(1,n): print(i)
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 10given_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)
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 10given_number = 10 # set up a variable to store the sum# with initial value of 0sum = 0 # since we want to include the number 10 in the sum# increment given number by 1 in the for loopfor i in range(1,given_number+1): sum+=i # print the total sum at the endprint(sum)
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 10given_range = 10 # set up a variable to store the sum# with initial value of 0sum = 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 endprint(sum)
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 10given_number = 5 for i in range(11): print (given_number," x",i," =",5*i)
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 givenlist = [1,2,4,6,88,125] for i in list: print(i)
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 129475given_number = 129475 # since we cannot iterate over an integer# in python, we need to convert the# integer into string first using the# str() functiongiven_number = str(given_number) # declare a variable to store# the count of digits in the# given number with value 0count=0 for i in given_number: count += 1 # print the total count at the endprint(count)
Example 8: Python program to check if the given string is a palindrome.
# given stringgiven_string = "madam" # an empty string variable to store# the given string in reversereverse_string = "" # iterate through the given string# and append each element of the given string# to the reverse_string variablefor i in given_string: reverse_string = i + reverse_string # if given_string matches the reverse_srting exactly# the given string is a palindromeif(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.")
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 usergiven_string = input() # an empty string variable to store# the given string in reversereverse_string = "" # iterate through the given string# and append each element of the given string# to the reverse_string variablefor i in given_string: reverse_string = i + reverse_string # print the reverse_string variableprint(reverse_string)
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 numbergiven_number = 153 # convert given number to string# so that we can iterate through itgiven_number = str(given_number) # store the lenght of the string for future usestring_length = len(given_number) # initialize a sum variable with# 0 value to store the sum of the product of# each digitsum = 0 # iterate through the given stringfor i in given_number: sum += int(i)**string_length # if the sum matches the given string# its an amstrong numberif 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 numberelse: print("The given number",given_number,"is Not an Amstrong number.")
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 numbersnum_list = [1,3,5,6,99,134,55] # iterate through the list elemets# using for loopfor 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.
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 libraryimport math # function to print all# non-primes in a rangedef 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 rangerange_starts = 10 # upper bound of the rangerange_ends = 30print("Non-prime numbers between",range_starts,"and", range_ends,"are:") for number in filter(is_not_prime, range(range_starts, 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
Also Read: Python Sets Practice Program for Beginners
Example 13: Python program to get the Fibonacci series between 0 to 50.
# given upper boundnum = 50 # initial values in the seriesfirst_value,second_value = 0, 1 # iterate in the given range# of numbersfor 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)
Output
1
2
3
5
8
13
21
34
Example 14: Python program to find the factorial of a given number.
# given numbergiven_number= 5 # since 1 is a factor # of all number # set the factorial to 1factorial = 1 # iterate till the given numberfor i in range(1, given_number + 1): factorial = factorial * i print("The factorial of ", given_number, " is ", factorial)
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 useruser_input = input() # declare 2 variable to store# letters and digitsdigits = 0letters = 0 # iterate through the input stringfor 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.")
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 rangegiven_range = 25 # iterate using a for loop till the# given rangefor 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)
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 userpassword = input() # set up flags for each criteria# of a valid passwordhas_valid_length = Falsehas_lower_case = Falsehas_upper_case = Falsehas_digits = Falsehas_special_characters = False # first verify if the length of password is# higher or equal to 8 and lower or equal to 16if (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")
Input
Naukri12345@
Output
Naukri12345@
Example 18: Python program to convert the month name to a number of days.
# given list of month namemonth = ["January", "April", "August","June","Dovember"] # iterate through each mont in the listfor 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.")
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.
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