【发布时间】:2022-01-25 18:14:15
【问题描述】:
我是 python 新手,做了一个计算器程序作为练习。我有 java 方面的经验,所以我可以轻松起步,但即使我是一名 java 程序员,我仍然不熟悉变量声明和函数。所以,如果你能帮我解决这个错误,将不胜感激。
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
oper = str(input("Enter the operator: "))
def my_func(answer):
print("The answer is " + answer)
if oper == "+":
calc = num1 + num2
my_func(calc)
if oper == "-":
calc = num1 + num2
my_func(calc)
if oper == "/":
calc = num1 + num2
my_func(calc)
if oper == "*":
calc = num1 + num2
my_func(calc)
else:
print("You have not entered a valid operator")
运行此代码时出现以下错误。
Traceback(最近一次调用最后一次):文件“(文件位置)”,第 13 行, 在 my_func(calc) 文件“(文件位置)”,第 6 行,在 my_func 中 print("答案是" + answer) TypeError: can only concatenate str (not "int") to str
【问题讨论】:
-
作为与您遇到的问题无关的样式注释,您的
ifs 系列应为if/elif/else。
标签: python calculator