-2

So I am starting out with Python and thought to make a dice roller for fun. I have created this:

import random
import keyboard
print("Which dice would you like? 6 side or 20 side?")
dice = input()
print("Press the space key to initiate a roll")
while True:
    if keyboard.is_pressed(' '):
        print(random.randint(0, dice))

Now I go by the assumption that making a random in the range of 0 and a pre-made variable (which has a number in it, not null) should work. I mean, it works in Java and C# so why not here right?

For some reason tho Python hates this, I debugged it and it dies at the print line and gives me this error:

Traceback (most recent call last):
  File "C:/Users/kiril/PycharmProjects/Practice/main.py", line 8, in <module>
    print(random.randint(0, dice))
  File "C:\Python\lib\random.py", line 248, in randint
    return self.randrange(a, b+1)
TypeError: can only concatenate str (not "int") to str

What's the problem here? Does it not accept pre-made variables (I mean the random class)? Is it maybe that the input in Python makes everything String (I don't know if it's true but hey maybe, only second day on this language)? How do I fix this?

4 Answers4

2

The type of the input returned from input is str just do:

dice = int(input())
Or Y
  • 2,088
  • 3
  • 16
  • Oooh I see, thanks, tho now another thing. After I hit space, instead of doing the random 1 time it does it indefinitely. How do I make it so it only gives me a number once? – MrBoomBastic Aug 06 '20 at 11:24
  • @MrBoomBastic try using is_released instead of is_pressed, let me know if it worked. Otherwise, try this: https://stackoverflow.com/questions/47184374/increase-just-by-one-when-a-key-is-pressed – Or Y Aug 06 '20 at 11:27
  • apparently, is_released does not exist for me lol – MrBoomBastic Aug 06 '20 at 11:30
  • 1
    Found a better way: ``` while True: keyboard.wait(' ') print(random.randint(1, dice)) ``` – MrBoomBastic Aug 06 '20 at 11:37
0

Your input function return a string type value. You need to convert it into int type value. For this:

dice = int(input())
Ujjwal Dash
  • 767
  • 1
  • 4
  • 8
odog
  • 31
  • 6
0

dice = int(input()) to convert input to int

Gan3i
  • 95
  • 11
0

You have to do this dice=int(input())

Here is the code

import random
import keyboard
print("Which dice would you like? 6 side or 20 side?")
dice =int(input())
print("Press the space key to initiate a roll")
while True:
    if keyboard.is_pressed(' '):
        print(random.randint(0, dice))

Try it,it will work

Ujjwal Dash
  • 767
  • 1
  • 4
  • 8