I am doing an assignment. What it is is not important - this question should be very simple. I need to make a randomly generated question. To do this for addition my code is:
num1 = (random.randint(0,12))
num2 = (random.randint(0,12))
question = (num1 + "" + "+" + "" + num2)
print(question)
I get the error:
question = (num1 + "" + "+" + "" + num2)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I think I understand what the problem is but I don't know how to fix it. I would be grateful for any help. I am using python-idle 3.8
You are trying to add int
with str
, which is not permitted, you could solve this by following ways:
>>> 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}"
Also if you are adding ""
, this is of no use, as those are empty strings. Instead either use " "
, or add it to the +
operator itself, like: " + "
.
References:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With