如何修复文本计算器中的错误?

我试图制作一个非常简单的文本计算器,但我一直遇到这个问题。


这是我的代码:


num1 = input("Enter in the first number")

num2 = input("Enter in the second number")

sign = input("Enter in the calculator operator you would like")


elif sign = "+":

   print(num1 + num2)

elif sign = "-":

   print(num1 - num2)

elif sign = "*":

   print(num1*num2)

elif sign = "/":

   print(num1/num2)

抱歉,我是 python 新手...


慕桂英546537
浏览 122回答 3
3回答

MMTTMM

您的代码不起作用的原因是因为您只是将两个数字相乘/除/加/减,而这两个数字现在声明为一个字符串。在 python 中,您不能将字符串作为整数进行加/减/乘/除。您需要将 num1 和 num2 声明为整数。num1 = int(input("Enter in your first number"))num2 = int(input("Enter in your second number"))sign = input("Enter in the calculator operator you would like")if sign == "+":   print(num1 + num2)elif sign == "-":   print(num1 - num2)elif sign == "*":   print(num1*num2)elif sign =="/":   print(num1/num2)

偶然的你

您的代码中有很多语法错误,请查看注释以了解可以改进的地方,底部有一些阅读材料!num1 = int(input("Enter in the first number")) # You need to cast your input to a int, input stores strings.num2 = int(input("Enter in the second number")) # Same as above, cast as INTsign = input("Enter in the calculator operator you would like")# You cannot use `elif` before declaring an `if` statement. Use if first!if sign == "+": # = will not work, you need to use the == operator to compare values   print(num1 + num2)elif sign == "-": # = will not work, you need to use the == operator to compare values   print(num1 - num2)elif sign == "*": # = will not work, you need to use the == operator to compare values   print(num1*num2)elif sign == "/": # = will not work, you need to use the == operator to compare values   print(num1/num2)代码可以很好地适应这些更改,但是您应该阅读Python 语法和运算符!

大话西游666

您收到此错误是因为默认情况下输入会给出一个字符串。在使用它之前,您必须将其转换为 int。num1 = int(input("Enter in the first number"))num2 = int(input("Enter in the second number"))sign = input("Enter in the calculator operator you would like")if sign == "+":   print(num1 + num2)elif sign == "-":   print(num1 - num2)elif sign == "*":   print(num1*num2)elif sign == "/":   print(num1/num2)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python