将变量(字母和数字)组合成Python问题

4

我正在做一个任务,具体内容并不重要 - 这个问题应该非常简单。我需要生成一个随机问题。对于加法,我的代码如下:

num1 = (random.randint(0,12))
num2 = (random.randint(0,12))
question = (num1 + "" + "+" + "" + num2)
print(question)

我遇到了错误:

question = (num1 + "" + "+" + "" + num2) 
TypeError: unsupported operand type(s) for +: 'int' and 'str'

我想我理解问题所在,但不知道如何修复。非常感谢任何帮助。我正在使用Python IDLE 3.8。


2
不是将num1num2相加,而是将str(num1)str(num2)相加。 - Sayandip Dutta
2
或者使用 f-string print(f"{num1}+{num2}") - tomjn
4个回答

3
您正在尝试将intstr相加,这是不允许的,您可以通过以下方式解决此问题:
>>> num1 = (random.randint(0,12))
>>> num2 = (random.randint(0,12))
>>> question = (str(num1) + "" + "+" + "" + str(num2))
# or for python 3.6+ use f-strings [1]
>>> question = f"{num1} + {num2}"

此外,如果您添加的是"",那么这没有任何用处,因为它们是空字符串。相反,要么使用" ",要么将其添加到+运算符本身中,例如:" + "
参考资料:
  1. f-strings

2

您需要将num1和num2中的整数强制转换为字符串类型。

num1 = (random.randint(0,12))
num2 = (random.randint(0,12))
question = (str(num1) + " " + "+" + " " + str(num2))
print(question)

你不能将类型 int 和类型 string 相加,这就是引起错误的原因。


2
您需要使用str()函数将这两个随机生成的数字进行转换。
因此,您更正后的代码将如下所示:
num1 = (random.randint(0,12))
num2 = (random.randint(0,12))
question = (str(num1) + " " + "+" + " " + str(num2))
print(question)

此外,在拼接字符串时,您忘记了添加空格,这会导致出现2+3等错误。
下一次,请尝试在Google上搜索并理解您遇到的错误。它告诉您,您不能使用运算符'+'在两种不同类型:'int'和'str'(相当于整数和字符串)之间进行操作。这些错误不仅是一种秘密语言,而且真正告诉您您的错误所在。让调试器成为您的朋友! :)

2

你不能把一个整数和字符串拼接在一起。有很多方法可以实现这个目的,你可以将整数显式地转换为字符串,或者将它们存储在列表中,并在打印时解包列表,或者我个人偏好使用 Python 的 f-string 格式。

import random
num1 = (random.randint(0,12))
num2 = (random.randint(0,12))
question = (str(num1) + " " + "+" + " " + str(num2))
print(question)

question = (num1, "+", num2)
print(*question)

question = f"{num1} + {num2}"
print(question)

输出

7 + 2
7 + 2
7 + 2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接