Hi, In this article we are about to explore Python While loop questions and answers with the help of the examples. If you are a Python programmer and go for an interview or want to test your Python while loop understanding then stay with this tutorial because throughout this Python while loop exercise, we will see various Python while loop questions along with proper examples.
We are about to see basic to advanced Python while loop questions and answers so that you can get an understanding of While loop in Python.
Before jumping to the Python while loop exercise, Let’s understand the Python while loop.
Headings of Contents
- 1 What is While Loop in Python?
- 2 Python While Loop Questions and Answers by Examples
- 2.1 Simple Countdown
- 2.2 The sum of Positive Numbers
- 2.3 Password Validation
- 2.4 Fibonacci Sequence
- 2.5 Print Even numbers from 0 to 20
- 2.6 Factorial of a Number
- 2.7 Print Square of Numbers
- 2.8 Print Multiplication Table
- 2.9 Print the number until the user type ‘exit’
- 2.10 Generate a Random Number between 1 to 100
- 2.11 Reverse a String
- 2.12 Print all the prime numbers up to a number
- 2.13 Guess a number
- 2.14 Print age of the user
- 2.15 Calculate the cost of the items
- 2.16 Calculate the average grades
- 2.17 Find the largest number
- 2.18 Count event and odd numbers
- 2.19 Email validation
- 2.20 Count the total of a specific number in digits
- 2.21 Calculation based on the base and exponent
- 2.22 Count Hello in user entered string
- 2.23 Check Leap Year
- 2.24 ATM Money Withdraw
- 2.25 The sum of all the numbers
- 2.26 Display all the divisors of a number
- 3 Conclusion
What is While Loop in Python?
While loop in Python is used to execute a block of code as long as a certain condition is true. In other words, You can say that Python While loop is a control flow statement that executes a block of code as long as repeatedly as long a certain condition is True.
Python while loop syntax:
while condition: # block of code to be executed
You can explore our Python while loop tutorial for more understanding.
To understand all the Python while loop programs, You should know about the following Python topics.
Now Let’s start Python While Loop Programs one by one using examples.
Python While Loop Questions and Answers by Examples
Simple Countdown
Write a Python program that counts from 10 to 1 and print each number with the help of the while loop.
count = 10 while count > 0: print(count) count -= 1 print("Blast off!")
The sum of Positive Numbers
Create a Python while loop program that continuously asks the user for a positive number and keeps a running total. The loop must stop when the user enters a negative number.
total = 0 while True: number = float(input("Enter a positive number (or a negative number to stop): ")) if number < 0: break total += number print("Total sum of positive numbers:", total)
Password Validation
Write a Python program that continuously the user for the correct password until then enters the correct one. For now, Assuming the correct password is “ProgrammingFunda@1“.
correct_password = "ProgrammingFunda@1" user_input = "" while user_input != correct_password: user_input = input("Enter the password: ") print("Access granted!")
Fibonacci Sequence
The Fibonacci Sequence in Python is one of the most asked questions during the Python interviews. I faced this question so many times in Python interviews.
Fibonacci Sequence:- The Fibonacci Sequence is a sequence of some numbers where one is the sum of two preceding numbers like 0, 1, 1, 2, 3, etc
Let’s write a Python code to generate the Fibonacci series in Python.
num = int(input("Enter a number:- ")) if num > 0: i = 0 a = 0 b = 1 while i < num: print(a, end=' ') a, b = b, a + b i = i + 1
Print Even numbers from 0 to 20
Write a Python code to print event numbers from 0 to 20.
num = 0 while num <= 20: print(num) num += 2
Factorial of a Number
Create a program that prompts the user for a number and prints the factorial of that number using a while loop. This is also the most asked question in Python interviews.
num = int(input("Enter a number:- ")) if num > 0: fact = 1 count = 1 if num == 1: fact = 1 else: while count <= num: fact = fact * count count = count + 1 print(f"factorial of {num} is {fact}")
Print Square of Numbers
Write a while loop that prints the squares of numbers from 1 to 10.
num = 1 while num <= 10: print(num ** 2) num += 1
Print Multiplication Table
Write a program that prints the multiplication table of a given number (from 1 to 10) using a Python while loop. The number should be asked by the user.
number = int(input("Enter a number for its multiplication table: ")) i = 1 while i <= 10: print(number, "x", i, "=", number * i) i += 1
Print the number until the user type ‘exit’
Create a program that continuously asks the user for input until they enter “exit” and also print all inputs received before “exit“.
inputs = [] while True: user_input = input("Enter something (or type 'exit' to quit): ") if user_input.lower() == "exit": break inputs.append(user_input) print("You entered:", inputs)
Generate a Random Number between 1 to 100
Write a program that generates random numbers between 1 and 100 until a number greater than 90 is generated. Count how many numbers were generated.
import random count = 0 number = 0 while number <= 90: number = random.randint(1, 100) count += 1 print(number) print("Total numbers generated:", count)
Reverse a String
Create a program that reverses a user-inputted string using Python while loop technique.
text = input("Enter a string: ") output = "" index = len(text) - 1 while index >= 0: output = output + text[index] index -= 1 print(f"The reverse value of '{text}' is '{output}'.")
Print all the prime numbers up to a number
Write a Python program where the user will enter a number and all the prime numbers up to that number will be displayed with the help of the Python while loop.
Prime Number:- A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of prime numbers are 2, 3, 5, 7, 11, etc.
Let’s write a Python code to print all the prime numbers up to a number.
def is_prime(n): if n <= 1: return False for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True upper_limit = int(input("Enter a number: ")) num = 2 print("Prime numbers up to", upper_limit, ":") while num <= upper_limit: if is_prime(num): print(num) num += 1
Guess a number
Create a program that prompts the user to guess a number between 1 and 100. Keep track of the number of attempts it takes to guess correctly.
secret_number = 25 # You can randomize this if desired guess_value = 0 attempts = 0 while guess_value != secret_number: guess_value = int(input("Guess the number (between 1 and 100): ")) if guess_value > 0: attempts += 1 if guess_value < secret_number: print("Too low! Try again.") elif guess_value > secret_number: print("Too high! Try again.") else: print("Negative value not allowed, try Again!") print("Congratulations! You guessed the number in", attempts, "attempts.") print("-------------------------------------")
Print age of the user
Write a program that continuously asks the user for their age until a valid age (0-120) is entered.
age = -1 while age < 0 or age > 120: age = int(input("Please enter your age (0-120): ")) print("Your age is:", age)
Calculate the cost of the items
Create a program that calculates the total cost of items purchased. The program should continue to ask for item prices until a price of zero is entered.
total_cost = 0 while True: price = float(input("Enter the price of the item (or 0 to finish): ")) if price == 0: break total_cost += price print("Total cost of items:", total_cost)
Calculate the average grades
Create a program that calculates the average of user-entered scores in multiple subjects until a grade of -1 is entered.
total = 0 count = 0 while True: score = int(input("Enter score (or -1 to finish):")) if score == -1: break else: total = total + score count += 1 if count > 0: print(f"You have got total {total} numbers and average of all scores will be {total / count}") else: print(f"No scores were entered.")
Find the largest number
Write a program that finds the largest number entered by the user. The program should stop when the user enters a negative number.
largest = float('-inf') while True: number = float(input("Enter a number (or a negative number to stop): ")) if number < 0: break if number > largest: largest = number print("Largest number entered:", largest)
Count event and odd numbers
Create a program that asks the user for a series of integers and counts how many are even and how many are odd, stopping when the user enters 0.
even_count = 0 odd_count = 0 while True: number = int(input("Enter an integer (or 0 to stop): ")) if number == 0: break if number % 2 == 0: even_count += 1 else: odd_count += 1 print("Even numbers:", even_count) print("Odd numbers:", odd_count)
Email validation
Create a program that keeps asking the user to enter a valid email address until they do. An email is considered valid if it contains “@” and “.”.
email = "" while True: email = input("Enter a valid email address: ") if "@" in email and "." in email: print("Valid email address entered:", email) break else: print("Invalid email address. Please try again.")
Count the total of a specific number in digits
Write a program that takes an integer input and counts how many times the digit ‘7’ appears in that number.
number = input("Enter an integer: ") count_sevens = 0 index = 0 while index < len(number): if number[index] == '7': count_sevens += 1 index += 1 print("The digit '7' appears", count_sevens, "times.")
Calculation based on the base and exponent
Create a program that asks the user for a base and an exponent, then calculates the result using a while loop (without using the ** operator).
base = int(input("Enter the base: ")) exponent = int(input("Enter the exponent: ")) result = 1 count = 0 while count < exponent: result *= base count += 1 print(f"{base} raised to the power of {exponent} is {result}.")
Count Hello in user entered string
Write a program that repeatedly prompts the user to enter a string and counts how many times the user enters “hello”.
count_hello = 0 while True: user_input = input("Enter a string (or type 'exit' to quit): ") if user_input.lower() == 'exit': break if user_input.lower() == "hello": count_hello += 1 print("You entered 'hello' a total of", count_hello, "times.")
Check Leap Year
Create a program that prompts the user to enter a year, and checks if it’s a leap year. Keep asking until the user enters a valid year (greater than 0).
Leap Year:- A leap year has 366 days instead of 365 days, with extra days added to February month. This happens every four years to keep the calendar in sync with the Earth’s orbit.
while True: year = int(input("Enter a year (greater than 0): ")) if year > 0: break print("Please enter a valid year.") if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print(year, "is a leap year.") else: print(year, "is not a leap year.")
ATM Money Withdraw
Write a program that simulates a simple ATM. It should allow users to withdraw money, check balance, and exit. Start with a balance of 10000.
balance = 10000 while True: print("\nATM Menu:") print("1. Check Balance") print("2. Withdraw Money") print("3. Exit") choice = input("Select an option: ") if choice == '1': print("Your balance is: $", balance) elif choice == '2': amount = float(input("Enter amount to withdraw: ")) if amount <= balance: balance -= amount print("Withdrawal successful. New balance: $", balance) else: print("Insufficient funds.") elif choice == '3': print("Thank you for using the ATM. Goodbye!") break else: print("Invalid option. Please try again.")
The sum of all the numbers
Create a program that takes a list of numbers from the user until they enter a non-numeric value. Then, print the sum of the numbers.
total = 0 while True: user_input = input("Enter a number (or non-numeric number to exit): ") try: total += float(user_input) except ValueError: break print("Total sum of entered numbers:", total)
Display all the divisors of a number
Write a program that prompts the user for a positive integer and prints all the divisors of that number.
divisors_list = [] initial_divisors = 1 number = int(input("Enter a positive integer: ")) while initial_divisors <= number: if number % initial_divisors == 0: divisors_list.append(initial_divisors) initial_divisors += 1 print(f"Divisors of number {number} is {divisors_list}")
Conclusion
So throughout this article, we have seen almost more than 25 Python While loop questions and answers along with examples. All these Python while programs are useful when you want to brush up your while concepts and you will get more familiar with Python while loop as long you will solve more questions using Python while loop.
While loop in Python is one of the most useful because it allows to execution of a block of code repeatedly as long as a certain condition remains True. Keep practicing with different programs for different scenarios to deepen your Python while loop understanding and build confidence in using while loop in your Python projects.
This article was written and verified by Vishvajit Rao.
Thanks for your time. Keep learning and keep growing.