为什么这个循环在它完成之前就停止了?

时间:2017-03-24 22:52:05

标签: python-3.x loops random continue

这个滚动两个骰子的小程序存在一些问题。

为什么程序在完成循环之前就会停止,而是要求循环次数"你想再玩一次吗?"

感谢您的帮助!

#Program which simulates the rolling of two dice

import random

def rolling_dices(repetitions):
    a = repetitions
    b = 1
    while b <= a:
        i = (random.randrange(1,7))
        y = (random.randrange(1,7))
        b +=1
        print(i, y, "\t =>", int(i+y))

        answer = input("do you want to play again? (Y/N)")
        if answer.lower() == "y":
            continue
        else:
            break


rolling_dices(5)

2 个答案:

答案 0 :(得分:2)

好像你想从骰子滚动循环中删除问题,而是将骰子滚动循环放入一个带有问题提示的循环中。

import random

def rolling_dices(repetitions):
    a = repetitions
    b = 1

    while b <= a:
        i = (random.randrange(1,7))
        y = (random.randrange(1,7))
        b +=1
        print(i, y, "\t =>", int(i+y))

rolling_dices(5)

while input("do you want to play again? (Y/N)").lower() == "y":
    rolling_dices(5)

print("done.")

答案 1 :(得分:0)

确保正确缩进while循环:

#Program which simulates the rolling of two dice

import random

def rolling_dices(repetitions):
    a = repetitions
    b = 1

    while b <= a:
        i = (random.randrange(1,7))
        y = (random.randrange(1,7))
        b +=1
        print(i, y, "\t =>", int(i+y))

        answer = input("do you want to play again? (Y/N)")
        if answer.lower() == "y":
            continue
        else:
            break


rolling_dices(5)

有关python中缩进的更多信息:http://www.diveintopython.net/getting_to_know_python/indenting_code.html