Reputation: 23
I'm quite new to programming in Python. I have always written my int
inputs like the following example to ensure a user inputs an int
. This is a specific example I have in my code that I'm sure I can shorten and thus learn for future projects.
This ensures a three digit number is input by creating a loop that breaks when a three digit number is entered.
while 1 == 1:
print("Input a 3 digit number")
#The try statement ensures an INTEGER is entered by the user
try:
x = int(input())
if 100 <= x < 1000:
break
else:
print()
except ValueError:
print()
Upvotes: 2
Views: 224
Reputation: 7242
You can do something like this:
while True:
x = input("Input a 3 digit number: ")
if x.isdigit() and 100 <= int(x) <= 999:
break
isdigit()
checks whether the string consists of digits only (won't work for floats). Since Python uses short-circuiting to evaluate boolean expressions using the operator and
, the second expression 100 <= int(x) <= 999
will not be evaluated unless the first (x.isdigit()
) is true, so this will not throw an error when a string is provided. If isdigit()
evaluates to False, the second expression won't be evaluated anyway.
Another option is the following:
condition = True
while condition:
x = input("Input a 3 digit number: ")
condition = not (x.isdigit() and 100 <= int(x) <= 999)
Upvotes: 5
Reputation: 4653
Here's a fun alternative that avoids the need for a break or an exception at all:
x = ""
while not x.isdigit() or (100 > int(x) or int(x) > 999):
x = input("Input a 3 digit number")
x = int(x)
Upvotes: 2
Reputation: 11075
If you want to handle the two different failures separately (not an int vs not 3 digit) you could do something like this:
while True:
try:
x = int(input('enter a 3 digit number'))
assert(100 <= x <= 999)
except ValueError: print('not an int')
except AssertionError: print('int not 3 digit')
else: break
It's not worlds shorter, but it is still very readable, and gives extra information to the user. Additionally if your intent is to make it re-usable, you should make it a function (just replace break
with return x
and add def funcname():
to the beginning (don't forget indentation)).
Upvotes: 3