我有这个循环,我很难让它接受在线整数。没有字符串。
def addItem(menu, order):
# get item no from user
itemNo = int(input('your choice : '))
# validate item no
if itemNo == -1:
return itemNo
while itemNo not in range(1, len(menu) + 1):
itemNo = int(input('Invalid input, try again: '))
if itemNo == -1:
return itemNo
发布于 2021-10-07 22:30:11
您可以在执行此操作的函数中抛出try/catch
def get_input():
not_valid = True
while not_valid:
itemNo = input("your choice: ")
try:
itemNo = int(itemNo) #Try convert the input to an integer
return itemNo
except TypeError: #That fails - start over
print("Enter only integers!")
并使用它
def addItem(menu, order):
# get item no from user
itemNo = get_input()
# validate item no
if itemNo == -1:
return itemNo
while itemNo not in range(1, len(menu) + 1):
itemNo = int(input('Invalid input, try again: '))
if itemNo == -1:
return itemNo
https://stackoverflow.com/questions/69491375
复制相似问题