Python Coding Exercise #44: Input Validation
Part of the series Python Practice Exercise — part 44
Before you start: Know input() and int() · Know if, elif and else · Know while True and break
The question
Please write a program which asks the user for integer numbers.
If the number is below zero, the program should print out the message “Invalid number”.
If the number is above zero, the program should print out the square root of the number using the Python
sqrtfunction.In either case, the program should then ask for another number.
If the user inputs the number zero, the program should stop asking for numbers and exit the loop.
Below you’ll find a reminder of how the
sqrtfunction is used. Remember toimportit in the beginning of the program.
# sqrt function will not work without this line in the beginning of the program
from math import sqrt
print(sqrt(9))
3.0
An example of expected behaviour of your program:
Please type in a number: 16
4.0
Please type in a number: 4
2.0
Please type in a number: -3
Invalid number
Please type in a number: 1
1.0
Please type in a number: 0
Exiting...
What “input validation” means
Input validation means checking what the user typed before the program uses it. Here, a negative number can’t be used with sqrt(), so the program checks the number first and prints Invalid number instead of trying to calculate. (sqrt() is also used in Exercise #28, which solves a quadratic equation.)
This exercise puts together two things from earlier posts: the while True loop with break from Exercise #43, and the if / elif / else chain from the conditionals exercises.
Before coding: three kinds of numbers
Every integer is exactly one of these three, so the program needs one branch for each:
| The number is | What the program does |
|---|---|
| Below zero | Prints Invalid number, then asks again |
| Above zero | Prints the square root, then asks again |
| Zero | Leaves the loop, then prints Exiting... |
Zero is neither below zero nor above zero, so it can’t share a branch with the other two. It has its own job: it is the signal to stop.
My Solution
from math import sqrt
while True:
number = int(input("Please type in a number: "))
if number == 0:
break
elif number < 0:
print("Invalid number")
else:
print(sqrt(number))
print("Exiting...")
How My Solution Works
1. Import sqrt once, at the top
from math import sqrt is written before the loop, so it runs only once. It brings the sqrt() function in from the math module, so it can be called by its plain name. (The same style was used for sqrt in Exercise #27.)
2. The loop asks for a number every time
Inside while True:, the line number = int(input("Please type in a number: ")) asks for a number and converts the answer to an integer. It is inside the loop, so it runs again at the start of every round. That is how the program keeps asking for numbers.
3. One if / elif / else chain with three branches
if number == 0:runsbreak, which ends the loop right away.elif number < 0:printsInvalid number.else:prints the square root. By the time Python reaches theelse, the number can’t be zero and can’t be negative, so it must be positive.
After the elif or else branch finishes, the loop goes back to the top and asks for another number, as the exercise says.
4. print("Exiting...") is outside the loop
It isn’t indented, so it runs only once, after break has ended the loop.
Following the sample
| Step | User types | Branch | Python prints |
|---|---|---|---|
| 1 | 16 | else | 4.0 |
| 2 | 4 | else | 2.0 |
| 3 | -3 | elif number < 0 | Invalid number |
| 4 | 1 | else | 1.0 |
| 5 | 0 | if number == 0, then break | Exiting... |
University Solution
from math import sqrt
while True:
number = int(input("Please type in a number: "))
if number == 0:
break
if number > 0:
print(sqrt(number))
else:
print("Invalid number")
print("Exiting...")
The University Solution has the same three branches, written in a slightly different way:
- Zero is handled first, on its own. The
if number == 0: breakis a separateif, not part of the chain below it. This works becausebreakleaves the loop, so Python never reaches the next lines when the number is zero. - A second
if/elsehandles the rest.if number > 0:prints the square root, and theelse:printsInvalid number. At that point, the number can’t be zero, so anything that isn’t positive must be negative. - The order of the last two branches is swapped. My Solution checks for a negative number and leaves the positive case for the
else. The University Solution checks for a positive number and leaves the negative case for theelse.
Both programs give identical output for the sample and for every other integer, including 0 typed straight away, which prints only Exiting....
Things to notice
sqrt() always returns a float. That’s why 16 gives 4.0 and not 4. Most numbers don’t have a whole-number square root, so they print with a long decimal, such as 1.4142135623730951 for 2 and 1.7320508075688772 for 3. This is floating-point behaviour, not a mistake in the program (see also Exercise #31). (More in Exercise #27.)
The validation is what protects sqrt(). If the program passed a negative number to sqrt(), Python would stop with a ValueError. Checking for the negative number first, and printing Invalid number, keeps the program running.
It only validates the sign, not the type. The exercise says the user types integers, so int() is enough. But if the user types a decimal like 0.5 or a word like abc, int() raises a ValueError and the program stops. Handling that needs more tools than we have so far.
Key takeaways
- Input validation means checking the input before using it.
- Every integer is below zero, above zero or exactly zero, so three branches cover all the cases.
- Zero is the stop signal, so it needs its own branch with
break. - Put the
input()inside the loop, so the program asks again in every round. - Put the
importat the top, outside the loop, so it runs once. - An unindented line after the loop, like
print("Exiting..."), runs once when the loop ends. - The same logic can be written in more than one order, as long as each number reaches exactly one branch.
✦ This is part of my Python Practice Exercise series, where I work through exercises while learning Python and explain each answer in plain language. ✦
Practice Source: This exercise is taken from the Python Programming MOOC 2026 by the University of Helsinki. I’m working through the exercises as part of my Python learning journey and documenting my answers and explanations here.