Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 302
Thomas Kerby Avatar asked Dec 31 '22 05:12

Thomas Kerby


1 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
like image 100
Sayandip Dutta Avatar answered Jan 05 '23 15:01

Sayandip Dutta