0

I was trying to make a simple dice in py, and I tried to make so you can change the amount of sides the dice has and if it's left empty, to default to 6. But when I input something, it crashes.

import keyboard #Import keyboard stuff like enter (pip install keyboard)
import random #Import random stuff
import time

sides = 1
sidesSelect = input("Amount of sides the dice has. If empty, 6: ")
is_non_empty= bool(sidesSelect)
if is_non_empty is False:
    sides = 6
else:
    sides = sidesSelect

time.sleep(0.5)

while True: 
    nmb = random.randint(1,sides) #Get random integer
    print("The dice rolled ", nmb) 
    input('Press enter to roll the dice again') #Ask if you want to throw again
    time.sleep(random.uniform(0.2,0.8))

I already tried changing == is, and nothing happened

if is_non_empty is false:
2
  • Thanks, it fixed my problem. bool(sideSelect) was there to check if they input something in the input, although i'll try to remove it Commented Nov 13, 2021 at 23:54
  • What does "it crashes" mean exactly? Please always include detailed information on the problem you are encountering Commented Nov 14, 2021 at 0:40

2 Answers 2

1

One issue your code has is it is trying to use the input directly without taking care of the type.

input() returns a string, so it has to be converted to proper type before using it in randint

Try something like this.


#python3

sidesSelect = int(input("Amount of sides the dice has. If empty, 6: ") or "6")

nmb = random.randint(1, sidesSelect) #Get random integer

input()

Sign up to request clarification or add additional context in comments.

Comments

0

You should instead convert it to an float, with float(input(...)), and then check to make sure that it is not NaN with math.isnan(), and then if it is a valid number, convert it to an int and continue on.

import math
sidesSelect = float(input('Enter sides') or 'nan')
if math.isnan(sidesSelect):
    sides = 6
else:
    sides = int(sidesSelect)
#rest of code

Because float(invalid) will return nan, you can see if the number entered is valid or not, and then if it is, convert to an int. Otherwise, you can use your default and then continue on.

3 Comments

I tried putting that piece of code into mine, but when I test it without any numbers, it brings me this error pastebin.com/ctT8PS83
What is the error?
So if you change the sidesSelect line to sidesSelect = float(input('Enter sides:') or 'nan'), then it will be correct. But if you are doing that, then you might as well go with the other answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.