Home > Back-end >  Python script crashes when I input an integer
Python script crashes when I input an integer

Time:11-14

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:

CodePudding user response:

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()

CodePudding user response:

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.

  • Related