您不需要重新启动脚本,只需在编写代码之前对设计进行一点思考。根据您提供的脚本,此问题有两个更改:def playagain():
while True:
again = input("Again? Yes/No: ")
if again == "Yes" or again == "yes":
return True
elif again == "No" or again == "no":
return False
else:
print("Nope..")
然后,在调用playagain()时,将其更改为:
^{pr2}$
我想我知道你为什么要重新启动脚本,你有一个bug。在
Python函数和其他对象一样。当你说:
^{3}$
它将对operation函数的引用重新分配给该函数返回的字符串。因此,第二次在重新启动时调用它时失败:TypeError: 'str' object is not callable
将operation函数重命名为foperation:def fopertion():
然后:operation = foperation()
因此,完整的代码变成:import sys
OPTIONS = ["Divide", "divide", "Multiply", "multiply", "Add", "add", "Subtract", "subtract"]
def userinput():
while True:
try:
number = int(input("Number: "))
break
except ValueError:
print("NOPE...")
return number
def foperation():
while True:
operation = input("Multiply/Divide/Add: ")
if operation in OPTIONS:
break
else:
print("Not an option.")
return operation
def playagain():
while True:
again = input("Again? Yes/No: ")
if again == "Yes" or again == "yes":
return True
elif again == "No" or again == "no":
return False
else:
print("Nope..")
def multiply(x,y):
z = x * y
print(z)
def divide(x,y):
z = x / y
print(z)
def add(x,y):
z = x + y
print(z)
def subtract(x,y):
z = x - y
print(z)
while True:
operation = foperation()
x = userinput()
y = userinput()
if operation == "add" or operation == "Add":
add(x,y)
elif operation == "divide" or operation == "Divide":
divide(x,y)
elif operation == "multiply" or operation == "Multiply":
multiply(x,y)
elif operation == "subtract" or operation == "Subtract":
subtract(x,y)
if not playagain(): break
我可以对这段代码做很多其他的改进,但是让我们先让它工作起来。在