Python Forum

Full Version: What is wrong with the random
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import random
print('You have rolled: ' + random.randint(1, 6))
what is wrong with this code?

Output:
Traceback (most recent call last): File "C:\Users\brand\OneDrive\Desktop\Python\throwDie.py", line 2, in <module> print('You have rolled: ' + random.randint(1, 6)) TypeError: can only concatenate str (not "int") to str
As the error says, you are trying to add a str(ing) to an int(eger). 'You have rolled: ' is a string,k, random.randint returns an int (hence it's name). You can't add the two together. You should use some string formatting:

import random
print(f'You have rolled: {random.randint(1, 6)}')  # note the f
Or if you want it to work with Python 3.5 or earlier:

import random
print('You have rolled: {}'.format(random.randint(1, 6)))
Hi ichabod801 I have a book here that is published in 2018 but the python code is from 3.6.0, would that be the problem? and I'm working with the newest update of Python? also the books name is Begin to Code with Python by Rob Miles.
All versions before 3.6 supports only the format method, the % operator and some other methods.
Also Python 2.7 supports the format method.
If you want to use format strings, you apply what you've learned about the format method.
In addition you can put f-strings in you code, to guarantee that's not executed below Python 3.6.

The benefit with formatting is, that you don not have to convert the datatypes by yourself.
If you just concatenate strings with the + operator, all objects must be strings.