首页 > 解决方案 > Python重启程序1

问题描述

如果用户从掷骰子中选择两个数字所获得的信息已经从整个列表中消失,我正在尝试重新启动该程序。它会要求他们再次滚动,刚刚发生的一切都会像他们从未点击过“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)

标签: python

解决方案


如果您想重复代码直到满足某些条件,您可以使用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.


推荐阅读