For Loop in Python
The for
loop is used to iterate over a sequence (like a list, tuple, or string) or a range of numbers. It’s one of the fundamental tools for iteration in Python. Here are some beginner-friendly exercises to help you practice using for
loops.
Practice Problems
Problems Index
- Print numbers from 1 to 10 using a
for
loop. - Input a number and print its multiplication table.
- Input a string and print each character on a new line.
- Input a list of numbers and calculate their sum.
- Print all even numbers between 1 and 50.
- Input a number and calculate its factorial.
- Print a pattern of stars for
n
rows (e.g., a right-angled triangle). - Input a number and check if it’s prime using a
for
loop. - Print all numbers divisible by 3 and 5 in the range 1 to 100.
- Input a string and count the number of vowels in it.
Try It Yourself
Now that you’ve reviewed the problems, practice them below using the code runner!
Pyground
Play with Python!
Output:
Solutions
Solutions
-
Print numbers from 1 to 10 using a
for
loop.Show Code
for i in range(1, 11): print(i)
-
Input a number and print its multiplication table.
Show Code
num = int(input("Enter a number: ")) for i in range(1, 11): print(num, "x", i, "=", num * i)
-
Input a string and print each character on a new line.
Show Code
text = input("Enter a string: ") for char in text: print(char)
-
Input a list of numbers and calculate their sum.
Show Code
numbers = input("Enter numbers separated by spaces: ").split() total = 0 for num in numbers: total += int(num) print("Sum of numbers:", total)
-
Print all even numbers between 1 and 50.
Show Code
for i in range(1, 51): if i % 2 == 0: print(i)
-
Input a number and calculate its factorial.
Show Code
num = int(input("Enter a number: ")) factorial = 1 for i in range(1, num + 1): factorial *= i print("Factorial of", num, "is", factorial)
-
Print a pattern of stars for
n
rows (e.g., a right-angled triangle).Show Code
n = int(input("Enter the number of rows: ")) for i in range(1, n + 1): print("*" * i)
-
Input a number and check if it’s prime using a
for
loop.Show Code
num = int(input("Enter a number: ")) is_prime = True for i in range(2, num): if num % i == 0: is_prime = False break if is_prime and num > 1: print(num, "is a prime number") else: print(num, "is not a prime number")
-
Print all numbers divisible by 3 and 5 in the range 1 to 100.
Show Code
for i in range(1, 101): if i % 3 == 0 and i % 5 == 0: print(i)
-
Input a string and count the number of vowels in it.
Show Code
text = input("Enter a string: ").lower() vowels = "aeiou" count = 0 for char in text: if char in vowels: count += 1 print("Number of vowels:", count)