Reputation: 383
So I need to gather input from a user but I have to ensure that they can only enter a number between 1 and 0 before the program accepts their input. Here is what I've got so far:
def user_input():
try:
initial_input = float(input("Please enter a number between 1 and 0"))
except ValueError:
print("Please try again, it must be a number between 0 and 1")
user_input()
Could someone edit this or explain to me how I can add another rule as well as the ValueError
so that it only accepts numbers between 1 and 0?
Upvotes: 0
Views: 270
Reputation: 1457
You can't check the value in the same line as you catch the exception. Try this:
def user_input():
while True:
initial_input = input("Please enter a number between 1 and 0")
if initial_input.isnumeric() and (0.0 <= float(initial_input) <= 1.0):
return float(initial_input)
print("Please try again, it must be a number between 0 and 1")
EDIT
Removed the try/except and used isnumeric()
instead.
Upvotes: 5