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
Output:
2. Calculate Factorial
Pyground
Calculate the factorial of a given number.
Output:
3. Sum Until Negative
Pyground
Input numbers continuously and stop when a negative number is entered. Then, print their sum.
Output:
4. First N Even Numbers
Pyground
Print the first n even numbers.
Output:
5. Reverse Digits
Pyground
Reverse the digits of a given number.
Output:
6. Count Digits
Pyground
Count the number of digits in an integer.
Output:
7. Fibonacci Series
Pyground
Print the Fibonacci series up to n terms.
Output:
8. GCD Using Subtraction
Pyground
Find the greatest common divisor (GCD) of two numbers using repeated subtraction.
Output:
9. Valid Marks Input
Pyground
Input marks until a valid score (0–100) is entered, then details it.
Output:
10. Input Until Stop
Pyground
Continuously take input using while True and exit the loop only if 'stop' is entered.
Output:
Last updated on