Definition of for loop :
A for loop in Python is used to iterate over a sequence (like a list, tuple, or range) and execute a block of code for each item in that sequence.
Real time example of for loop:
Question 1:
Write a Python program using a for
loop to print numbers between two inputs, excluding the start and end.
Program:
start = int(input("Enter the starting number: ")) end = int(input("Enter the ending number: ")) for i in range(start + 1, end): print(i)
Output:
Start: 4 End: 14 5 6 7 8 9 10 11 12 13
Question 2 :
Print Even Numbers Between 1 to 10
Program:
start = int(input("Enter the starting number: ")) end = int(input("Enter the ending number: ")) for i in range(start, end + 1): if i % 2 == 0: print(i)
Output:
Enter the starting number: 1 Enter the ending number: 10 2 4 6 8 10
Question 3 :
Print Odd Numbers Between 1 to 10
Program:
start = int(input("Enter the starting number: ")) end = int(input("Enter the ending number: ")) for i in range(start, end + 1): if i % 2 == 1: print(i)
Output:
Enter the starting number: 1 Enter the ending number: 10 1 3 5 7 9
Question 4 :
Count odd and even numbers from 1 to 4 using a for
loop, then print the counts.
Program:
even_count = 0 odd_count = 0 start = int(input("Enter the starting number: ")) end = int(input("Enter the ending number: ")) for i in range(start, end + 1): if i % 2 == 1: odd_count += 1 else: even_count += 1 print(f"Odd count: {odd_count}") print(f"Even count: {even_count}")
Output:
Enter the starting number: 1 Enter the ending number: 5 Odd count: 3 Even count: 2
Question 5 :
Count numbers divisible by 3 and 5 between two user inputs.
Program :
# Get user input for the starting and ending range start = int(input("Enter the starting number: ")) end = int(input("Enter the ending number: ")) count = 0 for i in range(start, end + 1): if i % 3 == 0 and i % 5 == 0: count += 1 print(f"Count of numbers divisible by 3 and 5 between {start} and {end}: {count}")
Output:
Enter the starting number: 1 Enter the ending number: 100 Count of numbers divisible by 3 and 5 between 1 and 100: 6
0 Comments