我有这段代码(用于练习):
def choose_dice():
while True:
try:
dice_quantity = int(input("How many dice would you like to use? "))
dice_sides = []
for current_dice in range(1, dice_quantity + 1):
sides = int(input("How many sides on {} dice? ".format(str(current_dice) + ordinal(current_dice))))
dice_sides.append([str(current_dice) + ordinal(current_dice) + " dice", sides])
# print(dice_sides)
return dice_sides
except (TypeError, ValueError) as _:
print("Oops, it seems you have entered a non integer ")
提示用户输入一个数字,然后输入范围内的x(1,数字),提示用户选择一个数字。
如果用户在for循环中键入非整数或没有任何内容,我想返回for循环的当前迭代而不是从头开始。
我怎样才能优雅地实现这一目标?
即当前的行为是这样的:
“你想用多少骰子?3
第一个骰子有多少个? 6
第二个骰子有多少个? 0
第3个骰子有多少个?
哎呀,好像你输入了一个非整数
您想要使用多少骰子? “
如果用户没有输入任何内容,则会在异常中捕获并且整个过程重新开始。我想让它重试当前的“骰子上有多少个方面?”而不是从头开始循环
答案 0 :(得分:0)
试试这个:
def choose_dice():
while True:
try:
dice_quantity = int(input("How many dice would you like to use? "))
except (TypeError, ValueError) as _:
print("Oops, it seems you have entered a non integer ")
dice_sides = []
current_dice = 1
while current_dice != dice_quantity + 1:
try:
sides = int(input("How many sides on {} dice? ".format(str(current_dice) + ordinal(current_dice))))
dice_sides.append([str(current_dice) + ordinal(current_dice) + " dice", sides])
current_dice += 1
except (TypeError, ValueError, NameError) as _:
print("Oops, it seems you have entered a non integer ")
print(dice_sides)
return dice_sides
答案 1 :(得分:0)
替换此行:
sides = int(input("How many sides on {} dice? ".format(str(current_dice) + ordinal(current_dice))))
使用此功能:
getSidesOnDice()
这是getSidesOnDice的定义:
def getSidesOnDice():
while True:
try:
sides = int(input("How many sides on {} dice? ".format(str(current_dice) + ordinal(current_dice))))
break
except (TypeError, ValueError) as _:
print("Oops, it seems you have entered a non integer ")
return sides
所以你的代码看起来像这样:
def getSidesOnDice(current_dice):
while True:
try:
sides = int(input("How many sides on {} dice? ".format(str(current_dice) + ordinal(current_dice))))
break
except (TypeError, ValueError) as _:
print("Oops, it seems you have entered a non integer ")
return sides
def choose_dice():
while True:
try:
dice_quantity = int(input("How many dice would you like to use? "))
dice_sides = []
for current_dice in range(1, dice_quantity + 1):
sides = getSidesOnDice(current_dice)
dice_sides.append([str(current_dice) + ordinal(current_dice) + " dice", sides])
print(dice_sides)
return dice_sides
except (TypeError, ValueError) as _:
print("Oops, it seems you have entered a non integer ")
您也可以在代码中内联函数。简单的解释是,如果没有获得有效值,则不希望获得current_dice边的行更进一步。因此,最简单的方法是用函数替换它,然后处理函数以使其按预期执行。然后,如果您觉得您希望在主代码中内联函数,请将其放在那里并删除该函数。即使在您的脑海中思考一个功能,也会将任务分解为更容易实现的小部件。