🔁 Python Loops for Beginners: for and while Explained
Blog post description.
PYTHON
4/30/20255 min read


Here's a concise and beginner-friendly explanation of Python for and while loops along with example programs.
In Python, loops are used to repeat a block of code multiple times. There are two main types of loops:
✅ for Loop
The for loop is used to iterate over a sequence (like a list, tuple, string, or range). It automatically picks the next item in the sequence for each iteration.
Syntax:
for variable in sequence:
# code to execute
#Print numbers from 1 to 5
for i in range(1, 6):
print(i)
OUTPUT:
1 2 3 4 5
#Loop through a list of fruits
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
while Loop
A while loop repeats as long as a condition is True. It's useful when you don't know ahead of time how many times you'll need to loop.
Syntax:
while condition:
# code to execute
#Print numbers from 1 to 5
i = 1
while i <= 5:
print(i)
i += 1
Output:
1 2 3 4 5
#User input until correct password
correct_password = "python123"
user_input = ""
while user_input != correct_password:
user_input = input("Enter password: ")
print("Access granted!")
🔁 for Loop Examples
#Calculate the sum of numbers from 1 to 100
total = 0
for i in range(1, 101):
total += i
print("Sum is:", total)
OUTPUT:
Sum is: 5050
#Print the multiplication table of a number
num = int(input("enter a number"))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
OUTPUT:
enter a number 4
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40
#Print even numbers from a list
numbers = [1, 4, 7, 10, 13, 16]
for num in numbers:
if num % 2 == 0:
print(num)
OUTPUT:
4 10 16
#Find the maximum number in a list
numbers = [3, 7, 2, 9, 5]
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
print("Maximum number:", max_num)
OUTPUT:
Maximum number: 9
#Calculate the average of a list
numbers = [10, 20, 30, 40]
total = 0
for num in numbers:
total += num
average = total / len(numbers)
print("Average:", average)
OUTPUT:
Average: 25.0
#Print numbers and their squares
for i in range(1, 11):
print(f"{i}^2 = {i**2}")
OUTPUT:
1^2 = 1
2^2 = 4
3^2 = 9
4^2 = 16
5^2 = 25
6^2 = 36
7^2 = 49
8^2 = 64
9^2 = 81
10^2 = 100
#Nested loop – multiplication tables from 1 to 3
for i in range(1, 4):
print(f"Multiplication table for {i}")
for j in range(1, 6):
print(f"{i} x {j} = {i * j}")
print()
OUTPUT:
Multiplication table for 1
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
Multiplication table for 2
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
Multiplication table for 3
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
#Print all prime numbers from 1 to 50
for num in range(2, 51):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
OUTPUT:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
#Count vowels in a string
text = "Python is fun"
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
print("Number of vowels:", count)
OUTPUT:
Number of vowels: 3
#Reverse a string
text = "hello"
reversed_text = ""
for char in text:
reversed_text = char + reversed_text
print("Reversed:", reversed_text)
OUTPUT:
Reversed: olleh
#Print characters of a string with their index
word = "Python"
for index in range(len(word)):
print(f"Character at index {index} is {word[index]}")
OUTPUT:
Character at index 0 is P
Character at index 1 is y
Character at index 2 is t
Character at index 3 is h
Character at index 4 is o
Character at index 5 is n
#Convert all items in a list to uppercase
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
fruits[i] = fruits[i].upper()
print(fruits)
OUTPUT:
['APPLE', 'BANANA', 'CHERRY'
while loop examples
#Guess the number game
secret_number = 7
guess = None
while guess != secret_number:
guess = int(input("Guess the number (1-10): "))
print("Congratulations! You guessed it!")
OUTPUT:
Guess the number (1-10): 5
Guess the number (1-10): 4
Guess the number (1-10): 7
Congratulations! You guessed it!
#Countdown timer
count = 5
while count > 0:
print(count)
count -= 1
print("Liftoff!")
OUTPUT:
5
4
3
2
1
Liftoff!
#Validate input until it's a digit
user_input = input("Enter a number: ")
while not user_input.isdigit():
user_input = input("Invalid input. Enter a number: ")
print("Thank you! You entered:", user_input)
OUTPUT:
Enter a number: a
Invalid input.
Enter a number: 3
Thank you! You entered: 3
#Find the factorial of a number
num = 5
factorial = 1
while num > 0:
factorial *= num
num -= 1
print("Factorial:", factorial)
OUTPUT:
Factorial: 120
#Keep asking until the user types "exit"
command = ""
while command.lower() != "exit":
command = input("Type 'exit' to quit: ")
print("Exited.")
Type 'exit' to quit: hi
Type 'exit' to quit: good morning
Type 'exit' to quit: exit
Exited.
#Sum positive numbers until a negative number is entered
total = 0
num = 0
while num >= 0:
num = int(input("Enter a number (negative to stop): "))
if num >= 0:
total += num
print("Total sum:", total)
OUTPUT:
Enter a number (negative to stop): 4
Enter a number (negative to stop): 10
Enter a number (negative to stop): 1
Enter a number (negative to stop): -10
Total sum: 15
#Print digits of a number one by one
num = 12345
while num > 0:
digit = num % 10
print(digit)
num = num // 10
OUTPUT:
5 4 3 2 1
#Sum digits of a number
num = 1234
total = 0
while num > 0:
total += num % 10
num //= 10
print("Sum of digits:", total)
OUTPUT:
Sum of digits: 10
#Reverse an integer
num = 1234
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num = num // 10
print("Reversed number:", reversed_num)
OUTPUT:
Reversed number: 4321
#Check if a number is a palindrome
num = int(input("Enter a number: "))
original = num
reverse = 0
while num > 0:
digit = num % 10
reverse = reverse * 10 + digit
num = num // 10
if original == reverse:
print("Palindrome!")
else:
print("Not a palindrome.")
OUTPUT:
Enter a number: 121
Palindrome!
#Repeat menu until user quits
choice = ""
while choice != "3":
print("1. Say Hello")
print("2. Say Goodbye")
print("3. Exit")
choice = input("Choose an option: ")
if choice == "1":
print("Hello!")
elif choice == "2":
print("Goodbye!")
OUTPUT:
1. Say Hello
2. Say Goodbye
3. Exit
Choose an option: 1
Hello!
1. Say Hello
2. Say Goodbye
3. Exit
Choose an option: 2
Goodbye!
1. Say Hello
2. Say Goodbye
3. Exit
Choose an option: 1
Hello!
1. Say Hello
2. Say Goodbye
3. Exit
Choose an option: 3
#Print powers of 2 less than 100
num = 1
while num < 100:
print(num)
num *= 2
OUTPUT:
1 2 4 8 16 32 64
#Count how many times a digit appears
number = 1123581123
digit = 1
count = 0
while number > 0:
if number % 10 == digit:
count += 1
number //= 10
print(f"Digit {digit} appears {count} times.")
OUTPUT:
Digit 1 appears 4 times.
#Simulate a login system with 3 tries
correct_password = "python123"
attempts = 0
success = False
while attempts < 3:
pwd = input("Enter password: ")
if pwd == correct_password:
success = True
break
attempts += 1
if success:
print("Login successful!")
else:
print("Access denied.")
OUTPUT:
Enter password: python
Enter password: python 123
Enter password: python12
Access denied.
#Repeat until user enters a palindrome word
while True:
word = input("Enter a word: ")
if word == word[::-1]:
print("Palindrome detected!")
break
else:
print("Try again.")
OUTPUT:
Enter a word: abc
Try again.
Enter a word: aba
Palindrome detected!
#Simulate a dice roll until you get a 6
import random
roll = 0
while roll != 6:
roll = random.randint(1, 6)
print("Rolled:", roll)
OUTPUT:
Rolled: 4
Rolled: 5
Rolled: 2
Rolled: 5
Rolled: 1
Rolled: 2
Rolled: 1
Rolled: 4
Rolled: 1
Rolled: 2
Rolled: 4
Rolled: 5
Rolled: 2
Rolled: 5
Rolled: 3
Rolled: 6


Kishore Babu Valluri
Senior Data Scientist | Freelance Consultant | AI/ML & GenAI Expert
With deep expertise in machine learning, artificial intelligence, and Generative AI, I work as a Senior Data Scientist, freelance consultant, and AI agent developer. I help businesses unlock value through intelligent automation, predictive modeling, and cutting-edge AI solutions.