Reputation: 25
print("What would you like to do:\n1. Enter new information\n2. House-
based statsitics\n3. Specific Criteria statistics")
while True:
try:
option = input("Enter 1 2 or 3: ")
except ValueError:
option = input("Enter 1 2 or 3: ")
if option < 1 and option > 3:
option = input("Enter 1 2 or 3: ")
else:
break
print(option)
I'm trying to make sure my input is between 1 to 3, when I do this I'll get a TypeError, but if I change it to int(option = input("Enter 1 2 or 3: "))
it will return an error if a string is entered.
Upvotes: 0
Views: 60
Reputation: 46849
or just that:
option = None
while option not in {'1', '2', '3'}: # or: while option not in set('123')
option = input("Enter 1 2 or 3: ")
option = int(option)
with the restriction to the 3 strings '1', '2', '3'
there is not even the need to catch a ValueError
when casting to an int
.
Upvotes: 2
Reputation: 369
Try this:
def func():
option = int(input("enter input"))
if not abs(option) in range(1,4):
print('Wrong')
sys.exit(0)
else:
print("Correct")
func()
func()
Upvotes: 1
Reputation: 26039
Use range
to check if input is in specified range:
print("What would you like to do:\n1. Enter new information\n2. House- based statsitics\n3. Specific Criteria statistics")
while True:
try:
option = int(input("Enter 1 2 or 3: "))
except ValueError:
option = int(input("Enter 1 2 or 3: "))
if option in range(1, 4):
break
print(option)
Sample run:
What would you like to do:
1. Enter new information
2. House- based statsitics
3. Specific Criteria statistics
Enter 1 2 or 3: 0
Enter 1 2 or 3: 4
Enter 1 2 or 3: a
Enter 1 2 or 3: 2
2
Upvotes: 0