Python Forum
What is wrong with the random
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What is wrong with the random
#1
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
Reply
#2
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)))
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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.
Reply
#4
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Am I wrong or is Udemy wrong? String Slicing! Mavoz 3 2,388 Nov-05-2022, 11:33 AM
Last Post: Mavoz
  python gives wrong string length and wrong character thienson30 2 2,945 Oct-15-2019, 08:54 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020