请有人帮助您如何提示用户退出,如果他们拒绝,请返回并重新运行该程序?我对此非常头痛,互联网也无济于事。
这是我的代码:
print("Hello, this program will ask for two numbers, then show the product
of those numbers that many times")
value = input("Please enter number")
value = int(value)
value2 = input("Please enter a second number")
value2 = int(value2)
for i in range(value*value2):
print(value*value2)
while True:
answer = input("Do you wih to exit? Enter Yes or No:")
if answer in ('No', 'Yes'):
break
print ("Invalid input.")
if answer == 'No':
continue
else:
print ("Goodbye")
break
这只是乘法,然后显示总和次数,但是我不知道如何提示用户退出,如果他们拒绝则再次运行程序。我听说过将整个代码放在一个循环中,但是我尝试过,但没有成功。我可以帮忙吗?
答案 0 :(得分:0)
您可以将其设为递归函数,并在用户回答“否”时执行循环。
例如:
def ask():
print("Hello, this program will ask for two numbers, then show the product of those numbers that many times")
value = input("Please enter number")
value = int(value)
value2 = input("Please enter a second number")
value2 = int(value2)
for i in range(value * value2):
print(value * value2)
answer = input("Do you wih to exit? Enter Yes or No:")
if answer not in ('No', 'Yes'):
print("Invalid input.")
if answer == 'No':
ask()
else:
print("Goodbye")
ask()
答案 1 :(得分:0)
基于所写的答案,但未编写函数:
这里的关键是您需要循环播放,直到用户输入“是”为止。您的while
循环永远不会为假,因此您将永远提示。这是另一种解决方案(尽管@Ricky Kim有更多的Python答案)
answer=""
while answer!= "yes":
print("Hello, this program will ask for two numbers, then show the product \
of those numbers that many times")
value = input("Please enter number")
value = int(value)
value2 = input("Please enter a second number")
value2 = int(value2)
for i in range(value*value2):
print(value*value2)
#use lower so that the user can enter "Yes" or "yes"
answer = str.lower(input("Do you wih to exit? Enter Yes or No:"))
print ("Goodbye")