将 int 和 str 与打印一起使用



无论我怎么做,我都会得到一个错误。 我错过了什么?

我已经尝试了我知道该怎么做的所有变体,但我认为我需要对变量做一些事情,但是当您输入一个数字时,我会想象它将其存储为整数......

first = input("Enter first number...")  # I input 5
second = input("Enter second number...")  # I input 6
operator = input("Spell out: add, subtract, multiply, or divide..."  # I input add
if operator == "add":
    print("Your answer is " + (int(first) + int(second)))

我也尝试过:

if operator == "add":
   print("Your answer is " + (str(first) + str(second)))

和其他变体...

如果我这样做: print("Your answer is " + str(5 + 6))有效

但: print("Your answer is " + str(first + second)))不起作用...

我希望当用户输入数字时,它将"第一"和"第二"存储为整数。因此,我可以使用"第一"和"第二",就好像它们是数字一样......

输入返回一个字符串,如果你想要一个整数,你必须自己做

first = int(input("Enter first number..."))

也帮自己一个忙并使用 f 字符串,它们的可读性要高得多。

print(f"Your answer is {first + second}")

你也可以像这样做print

first = int(input("Enter first number..."))  # I input 5
second = int(input("Enter second number..."))  # I input 6
operator = input("Spell out: add, subtract, multiply, or divide...")  # I input add
if operator == "add":
    print("Your answer is ", first + second)

试试这段代码:

print("You're answer is ",  (int(first) + int(second)))

您正在尝试连接string + integer

相关内容

最新更新