简体   繁体   English

当我输入一个整数时 Python 脚本崩溃

[英]Python script crashes when I input an integer

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.我试图在 py 中制作一个简单的骰子,我尝试制作这样你可以改变骰子的边数,如果它为空,默认为 6。但是当我输入一些东西时,它崩溃了。

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:

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 input()返回一个字符串,因此在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()输入()

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.您应该改为使用float(input(...))将其转换为浮点数,然后使用math.isnan()检查以确保它不是 NaN ,然后如果它是有效数字,则将其转换为一个 int 并继续。

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.因为 float(invalid) 会返回 nan,所以可以查看输入的数字是否有效,如果有效,则转换为 int。 Otherwise, you can use your default and then continue on.否则,您可以使用默认设置,然后继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM