combining variables (letters and numbers) into a question in python

Viewed 710

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

4 Answers

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:

  1. f-strings

You need to typecast the integers in num1 and num2 to the type strings.

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

You cannot add a type int and type string, which is what caused the error.

You need to convert these two randomly generated numbers with the str() function.

So, your corrected code will be like that:

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

Also, you forgot the spaces while concatenating and it will result in 2+3 and so on.

For the next time, try to search the error, you get, on Google and try to understand the error. It says to you, that you can't do the operation with the operator '+' on two different types: 'int' and 'str' (equivalently, on integer and string). These errors aren't just some sort of Chinese, but they really tell you about your mistake. Let the debugger be your friend! :)

You cannot concat an int with a str. There are many ways you can acheive this, you can explicitly convert the ints to strings, or you can store them in a list and unpack the list when you print, or my personal preferance is to use pythons f-string format.

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)

OUTPUT

7 + 2
7 + 2
7 + 2
Related