gpt4 book ai didi

python - 当用户输入0时,如何打印程序并继续而不是崩溃?

转载 作者:行者123 更新时间:2023-12-03 08:20:10 24 4
gpt4 key购买 nike

我正在让用户输入骰子的边数。如果有人输入0,程序将崩溃。如果他们输入字母或浮点数,则会打印出来,请输入一个整数。用户输入0时如何打印程序? IndexError:无法从空序列中选择。

class Dice():

def __init__(self, numberOfSides):
self.numberOfSides = numberOfSides


def rollDice(self):

Dice.diceSides = list(range(1, self.numberOfSides + 1))
return random.choice(Dice.diceSides)

def startRolling():

while True:

try:
userInput = int(input("Enter the number of sides your dice has: "))
except (ValueError, IndexError):
print("Please enter a whole number.")
continue
else:
break

diceRolled = Dice(numberOfSides=userInput).rollDice()
print("You rolled a {}.".format(diceRolled))

到目前为止,我已经尝试过了,但没有成功:
try:
except (ValueError, IndexError):
print("Please enter a number.")
continue

最佳答案

检查try/except之后的数字。

def startRolling():

while True:

try:
userInput = int(input("Enter the number of sides your dice has: "))

except ValueError:
print("Please enter a whole number: ")
continue

if userInput != 0:
break
else:
print("Please enter a non-zero number")

关于python - 当用户输入0时,如何打印程序并继续而不是崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59672337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com