为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕桂英546537 2022-07-05 17:35:56
我试图制作一个非常简单的文本计算器,但我一直遇到这个问题。这是我的代码: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 新手...
查看完整描述

3 回答

?
MMTTMM

TA贡献1869条经验 获得超4个赞

您的代码不起作用的原因是因为您只是将两个数字相乘/除/加/减,而这两个数字现在声明为一个字符串。


在 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)


查看完整回答
反对 回复 2022-07-05
?
偶然的你

TA贡献1841条经验 获得超3个赞

您的代码中有很多语法错误,请查看注释以了解可以改进的地方,底部有一些阅读材料!


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 INT

sign = 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 语法和运算符!


查看完整回答
反对 回复 2022-07-05
?
大话西游666

TA贡献1817条经验 获得超14个赞

您收到此错误是因为默认情况下输入会给出一个字符串。在使用它之前,您必须将其转换为 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)


查看完整回答
反对 回复 2022-07-05
  • 3 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信