输出:
Enter a number: 2
Enter an operation: +
Enter a second number: 2
4
Let's do next calculation? (yes/no): yes
Let's do next calculation? (yes/no):
原意: 注意:(从那里继续循环) 我想让用户再次输入数字和运算,所以我需要将它们发送到calculator()
**我的代码如下:**
import sys
def choice():
while True:
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation != "no":
continue
else:
sys.exit()
def calculator():
while True:
num1 = int(input("Enter a number: "))
op = input("Enter an operation: ")
if op == "+":
num2 = int(input("Enter a second number: "))
r = (num1 + num2)
print(str(r))
do = choice()
我尝试了这段代码,并期望它再次询问数字,但它一直询问用户是否要进行下一次计算。是否有任何特定函数可以将它们重定向到计算器()函数?
您需要从
choice
函数返回一个选择,而不是启动新循环。查看您的 continue
所在循环的内容。
def choice():
return input("Let's do next calculation? (yes/no): ")
def calculator():
while True:
num1 = int(input("Enter a number: "))
op = input("Enter an operation: ")
if op == "+":
num2 = int(input("Enter a second number: "))
r = (num1 + num2)
print(str(r))
do = choice()
if do != "no":
continue
else:
sys.exit()