# 15 Python while Loop Exercises with Solutions for Beginners

While loops are a fundamental control structure in Python (and most programming languages), and they are used whenever you need to execute a block of code repeatedly as long as a certain condition is true. In this article, I will give you 15 Python while loop exercises for beginners which will cover a wide range of programming scenarios.

Course for You: Learn Python in 100 days of coding

## How do you practice while loop in Python?

The basic syntax or structure of a while loop looks like below:

```while condition:
statements
```

In this basic while loop structure, you need to provide your condition and statement to accomplish your desired task in Python. In this article, I will list down some simple and basic while loop exercises practice programs for beginners with solutions, that will help you practice and gain confidence in Python.

## Exercise 1: Print Numbers 1 to 10

This exercise uses a while loop to print numbers from 1 to 10 sequentially.

```num = 1
while num <= 10:
print(num)
num += 1
```
``````1
2
3
4
5
6
7
8
9
10``````

## Exercise 2: Calculate the Sum of Numbers 1 to 100

This exercise calculates the sum of numbers from 1 to 100 using a while loop in Python.

```total = 0
num = 1
while num <= 100:
total += num
num += 1
print("Sum of numbers from 1 to 100:", total)
```
``Sum of numbers from 1 to 100: 5050``

## Exercise 3: Count Down from 10 to 1

Opposite to Exercise 1, this exercise counts down from 10 to 1 and prints each number in the countdown.

```count = 10
while count >= 1:
print(count)
count -= 1
```
``````10
9
8
7
6
5
4
3
2
1``````

## Exercise 4: Find the Factorial of a Number

This Python exercise calculates the factorial of a user-input number using a while loop. If you know more details about this exercise then read this article: 15 Simple Python Programs for Practice with Solutions.

```n = int(input("Enter a number: "))
fact = 1
while n > 0:
fact *= n
n -= 1
print("Factorial:", fact)
```
``````Enter a number: 5
Factorial: 120``````

You noticed I used `input()` function. This function will allow you to take input from the user in the Python prompt. Input from this input() function is always a string. So you need to convert it to an integer with int() function.

## Exercise 5: Check if a Number is Prime

This exercise checks if a user-input number is prime or not by using a while loop and testing divisibility.

```# Python while loop excersise to check if a number is prime or not
num = int(input("Enter a number: "))
is_prime = True
i = 2
while i <= num // 2:
if num % i == 0:
is_prime = False
break
i += 1
if is_prime:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
```
``````Enter a number: 15
15 is not a prime number``````
``````Enter a number: 17
17 is a prime number``````

In this Python script, you noticed that I used if-elif-else statements inside the while loop. I also used break statement inside this while loop. This code can be helpful excesise to understand how to use if-elif-else statements and break statement inside a while loop in Python.

## Exercise 6: Print Fibonacci Series

This exercise Python program generates and prints the Fibonacci series up to a specified number of terms using a while loop.

```# Python while loop exercises to Print Fibonacci Series
a, b = 0, 1
n = int(input("Enter the number of terms: "))
count = 0
while count < n:
print(a)
nth = a + b
a = b
b = nth
count += 1
```
``````Enter the number of terms: 10
0
1
1
2
3
5
8
13
21
34``````

## Exercise 7: Reverse a Number

This exercise Python program reverses a user-input number and prints the reversed number.

```# python while loop exercises with solutions for beginners: Reverse a number
num = int(input("Enter a number: "))
reverse = 0
while num > 0:
digit = num % 10
reverse = reverse * 10 + digit
num //= 10
print("Reversed number:", reverse)
```
``````Enter a number: 25
Reversed number: 52``````
``````Enter a number: 27
Reversed number: 72``````

## Exercise 8: Calculate the Average of Numbers

This while loop exercises calculates the average of a set of user-input numbers in Python.

```# exercises on while loop in python: Calculate the Average of Numbers
count = int(input("Enter the number of values: "))
total = 0
i = 1
while i <= count:
num = float(input("Enter a number: "))
total += num
i += 1
average = total / count
print("Average:", average)
```
``````Enter the number of values: 2
Enter a number: 5
Enter a number: 7
Average: 6.0``````

## Exercise 9: Reverse a String

This exercise Python program reverses a user-input string and prints the reversed string.

```# while loop in python exercises: Reverse a String
input_string = input("Enter a string: ")
reversed_string = ""
index = len(input_string) - 1
while index >= 0:
reversed_string += input_string[index]
index -= 1
print("Reversed string:", reversed_string)
```
``````Enter a string: I like Python
Reversed string: nohtyP ekil I``````

## Exercise 10: Print Even Numbers

This exercise Python practice program prints even numbers from 2 to 20 using a while loop.

```# python while loops exercises: Print Even Numbers
num = 2
while num <= 20:
print(num)
num += 2
```
``````2
4
6
8
10
12
14
16
18
20``````

## Exercise 11: Calculate the Sum of Digits in a Number

This Python practice exercise program calculates the sum of the digits in a user-input number using a while loop.

```# python while loops exercises: Calculate the Sum of Digits in a Number
num = int(input("Enter a number: "))
sum_of_digits = 0
while num > 0:
digit = num % 10
sum_of_digits += digit
num //= 10
print("Sum of digits:", sum_of_digits)
```
``````Enter a number: 27
Sum of digits: 9``````
``````Enter a number: 13
Sum of digits: 4``````

## Exercise 12: Print a Triangle of Stars

This special Python exercise code prints a triangle pattern of stars with a user-specified number of rows using a while loop.

```# Good exercises on while loop in python: Print a Triangle of Stars
n = int(input("Enter the number of rows: "))
row = 1
while row <= n:
print("*" * row)
row += 1
```
``````Enter the number of rows: 10
*
**
***
****
*****
******
*******
********
*********
**********``````

## Exercise 13: Break and Continue statement in while loops

#### Break Statement:

The `break` statement is used to exit a loop before its normal termination condition is met. It is often used to terminate a loop when a specific condition is satisfied.

```# Example: Using 'break' to exit a while loop

while True:
user_input = input("Enter 'q' to quit: ")
if user_input == 'q':
break
print("You entered:", user_input)

print("Loop exited!")
```
``````Enter 'q' to quit: hi
You entered: hi
Enter 'q' to quit: hello
You entered: hello
Enter 'q' to quit: q
Loop exited!``````

In this code, we have a while loop that runs indefinitely (`while True`). Inside the loop, we continuously ask the user for input using `input()` function. We check if the user input is equal to ‘q‘. If it is, we use the `break` statement to exit the loop immediately. If the user doesn’t enter ‘q’, we print the input.

#### Continue Statement:

The `continue` statement is used to skip the current iteration of a loop and move to the next iteration. It’s handy when you want to skip some specific values or conditions within a loop.

```# Example: Using 'continue' to skip even numbers in a while loop

num = 1

while num <= 10:
if num % 2 == 0:
num += 1
continue
print("Current number:", num)
num += 1
```
``````Current number: 1
Current number: 3
Current number: 5
Current number: 7
Current number: 9``````

In this code, we have a while loop that iterates from 1 to 10 (`while num <= 10`). Inside the loop, we check if the current value of `num` is even (using `num % 2 == 0`).

If `num` is even, we use the `continue` statement to skip the rest of the loop body and move to the next iteration. If `num` is odd, we print its value and increment `num`.

## Exercise 14: Adding elements to a list using while loop

You can add or append a list element using while loop in Python. In the below code, we are appending an empty list with random numbers. The code will stop when the length of the list is 5 (`num_elements`).

```# # Python code to append list elements using while loop
import random

# Initialize an empty list
random_numbers = []

# Set the desired number of random elements
num_elements = 5

# Use a while loop to append random numbers to the list
while len(random_numbers) < num_elements:
random_num = random.randint(1, 100)  # Generates a random number between 1 and 100
random_numbers.append(random_num)  # Append the random number to the list

# Display the list of random numbers
print("Random Numbers:", random_numbers)
```
``Random Numbers: [98, 79, 82, 5, 32]``
``Random Numbers: [62, 32, 92, 67, 86]``

## Exercise 15: Removing elements from a list using while loop

Opposite to the above exercise, in this practice Python code, we will remove some elements from a list using while loop. In the below Python code, list elements greater than threshold value (20) will be removed from the `my_list`.

```# Initialize a list with some elements
my_list = [15, 20, 5, 30, 10, 25, 35]

# Define the value above which elements should be removed
threshold = 20

# Use a while loop and list comprehension to remove elements greater than the threshold
my_list = [x for x in my_list if x <= threshold]

# Display the modified list
print("List after removing elements greater than", threshold, ":", my_list)
```
``List after removing elements greater than 20 : [15, 20, 5, 10]``

## Conclusion

In this article, I listed down some example Python program exercises to practice while loop. These Python while loop exercises for beginners cover a wide range of programming scenarios which will give you confidence while writing code in Python.