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
whileloop. - 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
neven numbers. - Reverse the digits of a given number.
- Count the number of digits in an integer.
- Print the Fibonacci series up to
nterms. - 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 Trueand 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!
1. Print Numbers
Pyground
Print numbers from 1 to 10 using a while loop.
Expected Output:
1 2 3 4 5 6 7 8 9 10