【问题标题】:Why this loop stops before it finishes?为什么这个循环在完成之前就停止了?
【发布时间】:2017-03-24 22:52:04
【问题描述】:

这个掷两个骰子的小程序有点问题。

为什么程序在完成循环之前就停止了,而是询问循环次数“你想再玩一次吗?”

感谢您的帮助!

#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)

【问题讨论】:

  • 缩进有问题,可能与问题无关
  • 嗨!我修了吗?
  • 嗨,是的,您修复了缩进,但我不确定这是否解决了问题。你是什​​么意思它“在完成循环之前停止”?它循环5次。它应该怎么做?
  • 它询问我五次是否要重复该程序;而不是打印 5 次结果然后让我重复该程序
  • 好吧,你期待什么?你把问题放在循环里面

标签: python-3.x loops random continue


【解决方案1】:

您似乎想从掷骰子循环中删除问题,而是将掷骰子循环放入带有问题提示的循环中。

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.")

【讨论】:

  • 很好的解决方案,我没想到要再放一个while循环来回答!
【解决方案2】:

确保正确缩进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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-10
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多