-4

I am currently learning Python so I have no idea what is going on.

import random

x=10
while x>0:
    print(x+'='+(random.randint(1,100)))
    x-=1

When I run the program

Traceback (most recent call last):

  File "C:\Users\black\.spyder-py3\temp.py", line 12, in <module>
    print(x+'='+(random.randint(1,100)))

TypeError: unsupported operand type(s) for +: 'int' and 'str'


  • 3
    you can use f-string `print(f'{x} = {random.randint(1,100)}')` – deadshot Aug 22 '20 at 06:33
  • Or simply `print(x,'=',random.randint(1,100))` - items will be space-separated. Actually you could write `print(x, '=', random.randint(1,100))` *not* because the extra whitespace here makes any difference to the output, but just because it is more readable with the spaces. – alani Aug 22 '20 at 06:38
  • This will help you learn about f-strings, which can solve your issue: (https://realpython.com/python-f-strings/) – Liana Aug 22 '20 at 06:46

1 Answers1

2

Your x is integer, but you are trying to concatenate it with string (equal sign).

You need to convert both x and the random value after equal sign to string:

import random

x=10
while x>0:
    print(str(x)+'='+str(random.randint(1,100)))
    x-=1
Pavel Botsman
  • 773
  • 1
  • 11
  • 25