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

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

本文介绍了询问用户是否要再次重复相同的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户到达程序的末尾,我希望他们被提示一个问题,询问他们是否想再试一次.如果他们回答是,我想重新运行该程序.

If the user gets to the end of the program I want them to be prompted with a question asking if they wants to try again. If they answer yes I want to rerun the program.

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 循环中,询问用户是否要重试.

You can enclose your entire program in another while loop that asks the user if they want to try again.

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

这篇关于询问用户是否要再次重复相同的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:37