我正在尝试用 Python 创建一个计算器,它只给出输入的第一个数字的平方。num1 = float(input("Enter the first number: "))operator = input("Enter an operator: ")num2 = float(input("Enter the second number: "))if operator == "+": print(num1 + num2)elif operator == "-": print(num1 - num2)elif operator == "*": print(num1 * num2)elif operator == "/": print(num1 / num2)elif operator == "^": print(num1 * num1) and print(num2 * num2)else: print("Invalid operator")
1 回答
红糖糍粑
TA贡献1815条经验 获得超6个赞
Python 在逻辑条件中使用短路- 简而言之,如果它确定有足够的信息,以便整个条件是True或False它不会继续执行条件语句中的其余代码 - 所以在你的情况下并不是所有代码你打算被处决。
为您的代码执行您想要的操作的一个简单修复方法是拆分print语句:
num1 = float(input("Enter the first number: "))
operator = input("Enter an operator: ")
num2 = float(input("Enter the second number: "))
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
elif operator == "/":
print(num1 / num2)
elif operator == "^":
print(num1 * num1)
print(num2 * num2)
else:
print("Invalid operator")
添加回答
举报
0/150
提交
取消