在 Python 中重新启动代码



我是Python的新手,这是我尝试的第一门语言。我开始有点掌握它,只是需要一些帮助。我正在用下面的代码制作一个简单的计算器,我想知道如何从头开始重新启动我的代码(你可以在底部看到我的尝试(。

import math
import time
def game():
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("What would you like to do?")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
a = int(input("Please choose 1, 2, 3, or 4."))
def choice():
if a == 1:
print("You are now adding.")
elif a == 2:
print("You are now subtracting.")
elif a == 3:
print("You are now multiplying.")
elif a == 4:
print("You are now dividing.")
choice()
first_num = int(input("What is the first number you want to use?"))
time.sleep(2)
second_num = int(input("What is the second number you want to use?"))
time.sleep(2)
def execute():
if a == 1:
print(first_num, "+", second_num, "=", add(first_num,second_num))
elif a == 2:
print(first_num, "-", second_num, "=", subtract(first_num,second_num))
elif a == 3:
print(first_num, "x", second_num, "=", multiply(first_num,second_num))
elif a == 4:
print(first_num, "/", second_num, "=", divide(first_num,second_num))
execute()
game()
def playagain():
input("Would you like to calculate another problem? Yes or No")
playagain()
while playagain == "Yes":
game()

您可以使用简单的loop来执行此操作,例如:

play_again = True
while play_again:
# your code goes here
inp = input("Would you like to calculate another problem? Yes or No")
play_again = inp.lower() == 'yes'

如果输入不是"是",这会将play_again更改为False

您非常接近可行的解决方案:

def playagain():
return input("Would you like to calculate another problem? Yes or No")
while playagain() == "Yes":
game()

您需要return他们从输入中键入的值,然后playagain()会询问他们并将该值插入其位置,因此将其与"是"进行比较。

您当前的方法没有什么特别的问题。

你真的接近最后的逻辑。不需要 while 语句,只需 if 语句即可。

playagain = input("Would you like to calculate another problem? Yes or No")
if playagain == "Yes":
game()

如果你想在问题解决后继续询问,那么你可以在游戏函数内部而不是外部执行 if else,因此在提出问题后它将继续请求 playagain 变量。

playagain = raw_input("Would you like to calculate another problem? Yes or No")
if playagain == "Yes":
game()
else:
return

最新更新