簡體   English   中英

詢問用戶是否要再次重復相同的任務

[英]Ask the user if they want to repeat the same task again

如果用戶到達程序的末尾,我希望提示他們一個問題,詢問他們是否要重試。 如果他們回答是,我想重新運行該程序。

import random
print("The purpose of this exercise is to enter a number of coin values") 
print("that add up to a displayed target value.\n") 
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.") 
print("Hit return after the last entered coin value.")
print("--------------------") 
total = 0 
final_coin = random.randint(1, 99)
print("Enter coins that add up to", final_coin, "cents, on per line") 
user_input = int(input("Enter first coin: "))
total = total + user_input

if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
   print("invalid input")

while total != final_coin:
    user_input = int(input("Enter next coin: "))
    total = total + user_input

if total > final_coin:
    print("Sorry - total amount exceeds", (final_coin)) 

if total < final_coin:
    print("Sorry - you only entered",(total))

if total== final_coin: 
    print("correct")

您可以將整個程序放在另一個while循環中,該循環詢問用戶是否要重試。

while True:
  # your entire program goes here

  try_again = int(input("Press 1 to try again, 0 to exit. "))
  if try_again == 0:
      break # break out of the outer while loop

只是對已接受答案的逐步改進:照原樣使用,來自用戶的任何無效輸入(例如空的str或字母“ g”等)都將在int()函數所在的位置導致異常。叫。

解決此問題的一種簡單方法是使用try / except-嘗試執行任務/代碼,如果可行,則行之有效,但否則(除了此處就像else:一樣)執行其他操作。

在一種可以嘗試的三種方法中,我認為下面的第一種是最簡單的方法,不會使程序崩潰。

# Opt1: Just use the string value entered with one option to go again
while True:
    # your entire program goes here

    try_again = input("Press 1 to try again, any other key to exit. ")
    if try_again != "1":
        break # break out of the outer while loop


# Opt2: if using int(), safeguard against bad user input    
while True:
    # your entire program goes here

    try_again = input("Press 1 to try again, 0 to exit. ")
    try:
        try_again = int(try_again)  # non-numeric input from user could otherwise crash at this point
        if try_again == 0:
            break # break out of this while loop
    except:
        print("Non number entered")


# Opt3: Loop until the user enters one of two valid options
while True:
    # your entire program goes here

    try_again = ""
    # Loop until users opts to go again or quit
    while (try_again != "1") or (try_again != "0"):
        try_again = input("Press 1 to try again, 0 to exit. ")
        if try_again in ["1", "0"]:
            continue  # a valid entry found
        else:
            print("Invalid input- Press 1 to try again, 0 to exit.)
    # at this point, try_again must be "0" or "1"
    if try_again == "0":
        break

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM