While Loop
The while
loop is used to repeat a block of code as long as a given condition is true. It’s a fundamental tool for creating loops when the number of iterations isn’t predetermined. Here are some beginner-friendly exercises to practice the while
loop.
Practice Problems
Problems Index
- Print numbers from 1 to 10 using a
while
loop. - Calculate the factorial of a given number.
- Input numbers continuously and stop when a negative number is entered. Then, print their sum.
- Print the first
n
even numbers. - Reverse the digits of a given number.
- Count the number of digits in an integer.
- Print the Fibonacci series up to
n
terms. - Find the greatest common divisor (GCD) of two numbers using repeated subtraction.
- Input marks until a valid score (0–100) is entered, then details it.
- Continuously take input using
while True
and exit the loop only if “stop” is entered.
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
while
loop.Show Code
i = 1 while i <= 10: print(i) i += 1
-
Calculate the factorial of a given number.
Show Code
num = int(input("Enter a number: ")) factorial = 1 while num > 0: factorial *= num num -= 1 print("Factorial is:", factorial)
-
Input numbers continuously and stop when a negative number is entered. Then, print their sum.
Show Code
total = 0 while True: num = int(input("Enter a number: ")) if num < 0: break total += num print("Sum of numbers:", total)
-
Print the first
n
even numbers.Show Code
n = int(input("Enter how many even numbers to print: ")) count = 0 num = 2 while count < n: print(num) num += 2 count += 1
-
Reverse the digits of a given number.
Show Code
num = int(input("Enter a number: ")) reverse = 0 while num > 0: digit = num % 10 reverse = reverse * 10 + digit num //= 10 print("Reversed number:", reverse)
-
Count the number of digits in an integer.
Show Code
num = int(input("Enter a number: ")) count = 0 while num > 0: num //= 10 count += 1 print("Number of digits:", count)
-
Print the Fibonacci series up to
n
terms.Show Code
n = int(input("Enter the number of terms: ")) a, b = 0, 1 count = 0 while count < n: print(a) a, b = b, a + b count += 1
-
Find the greatest common divisor (GCD) of two numbers using repeated subtraction.
Show Code
a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) while a != b: if a > b: a -= b else: b -= a print("GCD is:", a)
-
Input marks until a valid score (0–100) is entered, then details it.
Show Code
while True: marks = int(input("Enter marks (0-100): ")) if 0 <= marks <= 100: print("Valid marks:", marks) break else: print("Invalid input. Try again.")
-
Continuously take input using
while True
and exit the loop only if “stop” is entered.Show Code
while True: text = input("Enter something (type 'stop' to exit): ") if text.lower() == "stop": print("Exiting the loop.") break print("You entered:", text)