询问用户是否要再次重复相同的任务

时间:2013-10-09 21:38:22

标签: python

如果用户到达程序的末尾,我希望系统提示他们是否想再试一次。如果他们回答是,我想重新运行该程序。

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")

2 个答案:

答案 0 :(得分:1)

您可以将整个程序包含在另一个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

答案 1 :(得分:0)

只是对已接受的答案进行了逐步改进: 照原样使用,来自用户的任何无效输入(例如空的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