[英]How to check user input (Python)
我已經看到了這個問題的許多答案,但正在尋找非常具體的東西。 我需要完成的(用偽代碼)是:
> FOR every ITEM in DICTIONARY, DO:
> PROMPT user for input
> IF input is integer
> SET unique-variable to user input
我是Python的新手,所以代碼可能不正確,但這就是我所擁有的:
def enter_quantity():
for q in menu:
quantities[q] = int(input("How many orders of " + str(q) + "?: "))
因此,除了評估用戶輸入之外,此操作無所不能。 我遇到的問題是,如果輸入不正確,則需要在頂級for循環中為它們再次提示輸入相同的項目。 因此,如果要問“幾片披薩?” 而用戶輸入“十”,我想說“對不起,那不是數字”,然后再次返回提示“幾片比薩餅?”。
任何/所有想法表示贊賞。 謝謝!
我的最終解決方案:
def enter_quantity():
for q in menu:
booltest = False
while booltest == False:
inp = input("How many orders of " + str(q) + "?: ")
try:
int(inp)
booltest = True
except ValueError:
print (inp + " is not a number. Please enter a nermic quantity.")
quantities[q] = int(inp)
您需要使用try / except的while循環來驗證輸入:
def enter_quantity():
for q in menu:
while True:
inp = input("How many orders of {} ?: ".format(q))
try:
inp = int(inp) # try cast to int
break
except ValueError:
# if we get here user entered invalid input so print message and ask again
print("{} is not a number".format(inp))
continue
# out of while so inp is good, update dict
quantities[q] = inp
如果添加了菜單,那么這段代碼會稍微有用一點,否則它會在第一個障礙時崩潰。 我還添加了一個字典來存儲輸入值。
menu = 'pizza', 'pasta', 'vino'
quantities = {}
def enter_quantity():
for q in menu:
while True:
if q == 'pizza':
inp = input(f"How many slices of {q} ?: ")
elif q == 'pasta':
inp = input(f"How many plates of {q} ?: ")
elif q == 'vino':
inp = input(f"How many glasses of {q} ?: ")
try:
inp = int(inp) # try cast to int
break
except ValueError:
# exception is triggered if invalid input is entered. Print message and ask again
print("{} is not a number".format(inp))
continue
# while loop is OK, update the dictionary
quantities[q] = inp
print(quantities)
然后從以下命令運行代碼:
enter_quantity()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.