Beginner Exercises for "While" Statements in Python

Arzath AreeffArzath Areeff
2 min read

1. Password Checker

Keep asking until user enters "admin123". Then print “Access Granted”.

2. Countdown from N

Ask for a number, then count down to 0.

3. Number Until Even

Keep asking the user for a number until they enter an even number.

4. Sum Until Negative

Keep asking for numbers. Add them. Stop when the user enters a negative number.

5. Guess the Secret Number

Secret number = 5. Keep asking for guesses until the user gets it right. Print how many attempts it took.


ANSWERS

1. Password Checker

password = ""
while password != "admin123":
    password = input("Enter password: ")
print("Access Granted")

2. Countdown from N

num = int(input("Enter number: "))
while num >= 0:
    print(num)
    num -= 1

3. Number Until Even

num = 1
while num % 2 != 0:
    num = int(input("Enter a number: "))
print("You entered an even number.")

4. Sum Until Negative

total = 0
num = int(input("Enter a number: "))
while num >= 0:
    total += num
    num = int(input("Enter a number: "))
print("Total sum is", total)

5. Guess the Secret Number

secret = 5
guess = -1
attempts = 0

while guess != secret:
    guess = int(input("Guess the number: "))
    attempts += 1
print("Correct! Attempts:", attempts)
0
Subscribe to my newsletter

Read articles from Arzath Areeff directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Arzath Areeff
Arzath Areeff

I co-founded digizen.lk to promote online safety and critical thinking. Currently, I’m developing an AI app to fight misinformation. As Founder and CEO of ideaGeek.net, I help turn startup dreams into reality, and I share tech insights and travel stories on my YouTube channels, TechNomad and Rz Omar.