我希望我的代碼提示用戶輸入圖書詳細資訊,但如果他們沒有輸入正整數/小數或“N/A”作為評級和頁數,他們將被重新提示,直到他們輸入所以。用戶也可以在任何輸入提示下通過輸入“Q”作為輸入退出程式。最后,將填寫 add_details_dict 而不是將 None 作為所有鍵。這是我到目前為止所擁有的:
add_details_dict = {'title':None, 'author':None, 'language':None, 'publisher':None, 'category':None, 'rating':None, 'pages':None}
for key in add_details_dict.keys():
prompt = "Enter the " key " of the book you want to add. To quit: Q)uit\n"
current_input = input(prompt)
if current_input == 'Q':
break
else:
if key in ['rating', 'pages'] and current_input != 'N/A':
try:
add_details_dict[key] = float(current_input)
except ValueError:
print ("The ", key, " must be a positive and a whole number, decimal number, or 'N/A'.", sep='')
else:
add_details_dict[key] = current_input
問題是如果用戶沒有為評級/頁面輸入整數、小數或“N/A”。在通知用戶評分/頁數必須是整數、十進制數或“N/A”后,我希望程式回到 for 回圈當前迭代的開頭,即提示行,即current_input = 輸入(提示)。所以它會重新提示他們評分/頁面,如果他們再次搞砸,它將繼續重新提示,直到評分和頁面都是整數、小數或“N/A”。我希望固定代碼輸出這個:
Enter the title of the book you want to add. To quit: Q)uit:
sometitle
Enter the author of the book you want to add. To quit: Q)uit:
someauthor
Enter the language of the book you want to add. To quit: Q)uit:
English
Enter the publisher of the book you want to add. To quit: Q)uit:
somepublisher
Enter the category of the book you want to add. To quit: Q)uit:
somecategory
Enter the rating of the book you want to add. To quit: Q)uit:
nonsenserating
The rating must be a positive and a whole number, decimal number, or 'N/A'.
Enter the rating of the book you want to add. To quit: Q)uit:
5.7
Enter the pages of the book you want to add. To quit: Q)uit:
nonsensepages
The pages must be a positive and a whole number, decimal number, or 'N/A'.
Enter the pages of the book you want to add. To quit: Q)uit:
557
然后對于 add_details_dict,我應該得到以下資訊:
add_details_dict = {'title':'sometitle', 'author':'someauthor', 'language':'English', 'publisher':'somepublisher', 'category':'somecategory', 'rating':5.7, 'pages':557}
我很欣賞這個問題的修復,以便程式滿足上述結果。
uj5u.com熱心網友回復:
如果您為每個鍵添加一個回圈,并且僅break當用戶輸入一個合適的值時,那么提示將不斷出現,直到他們輸入可接受的內容。當然,break如果他們輸入 Q 將不起作用,因此您可以quit為此使用布爾變數:
add_details_dict = {'title':None, 'author':None, 'language':None, 'publisher':None, 'category':None, 'rating':None, 'pages':None}
quit = False
for key in add_details_dict.keys():
while True:
prompt = "Enter the " key " of the book you want to add. To quit: Q)uit\n"
current_input = input(prompt)
if current_input == 'Q':
quit = True
break
else:
if key in ['rating', 'pages'] and current_input != 'N/A':
try:
add_details_dict[key] = float(current_input)
break
except ValueError:
print ("The ", key, " must be a positive and a whole number, decimal number, or 'N/A'.", sep='')
else:
add_details_dict[key] = current_input
break
if quit:
break
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/456861.html
上一篇:遍歷陣列的一部分
