Python重新启动程序1

2024-04-20 04:11:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图重新启动这个程序,如果用户从掷骰子的两个数字中得到的东西已经从整个列表中消失了。它会要求他们再次滚动,刚刚发生的一切都会像他们从未点击过“e”一样返回

roll = input("Player turn, enter 'e' to roll : ")

    dice_lst = []
    if roll == "e":
        for e in range(num_dice):
            d_lst = random.randint(1,6)
            dice_lst.append(d_lst)
    else:
        print("Invalid ----- Please enter 'e' to roll the dice")
        # Add in the invalid input error



    print("")
    print("You rolled", dice_lst)
    dice_choose = int(input("Choose a dice : "))
    dice_lst.remove(dice_choose)
    print("")
    print("You are left with", dice_lst)
    dice_choose1 = int(input("Choose a dice : "))
    dice_lst.remove(dice_choose1)
    print("")


    while True:
        sum1 = dice_choose + dice_choose1
        if sum1 in lst_player:
            break
        else:

            print("You have made an invalid choice")


    sum1 = dice_choose + dice_choose1
    print(dice_choose, "+", dice_choose1, "sums to", sum1)
    print(sum1, "will be removed")
    print("")

    lst_player.remove(sum1)

Tags: toinyouinputifdiceelseremove
1条回答
网友
1楼 · 发布于 2024-04-20 04:11:55

如果要重复代码直到满足某些条件,可以使用while True循环或while <condition>循环,在达到某个无效情况时使用continue(继续到下一次迭代)来“重置”:

while True:
    roll = input("Player turn, enter 'e' to roll : ")

    dice_lst = []
    if roll == "e":
        for e in range(num_dice):
            d_lst = random.randint(1,6)
            dice_lst.append(d_lst)
    else:
        print("Invalid input")
        continue # Go back to asking the player to roll

    print("")
    print("You rolled", dice_lst)
    dice_choose = int(input("Choose a dice : "))
    dice_lst.remove(dice_choose)
    print("")
    print("You are left with", dice_lst)
    dice_choose1 = int(input("Choose a dice : "))
    dice_lst.remove(dice_choose1)
    print("")

    sum1 = dice_choose + dice_choose1
    if sum1 not in lst_player:
        print("You have made an invalid choice")
        continue # Go back to asking the player to roll

    print(dice_choose, "+", dice_choose1, "sums to", sum1)
    print(sum1, "will be removed")
    print("")

    lst_player.remove(sum1)
    break # Break out of the loop

我不完全确定这段代码是如何工作的,但您可能需要在continue之前移动块和/或重置骰子

相关问题 更多 >