【问题标题】:Dice statistics in PythonPython中的骰子统计
【发布时间】:2015-07-18 19:42:27
【问题描述】:

:反复询问用户掷骰子的次数,仅当用户输入的数字小于 1 时才退出。提示:使用 while 循环,只要 num_rolls 大于等于1.

我这样做了,但不知道如何使用 while 循环。

import random

num_sixes = 0
num_sevens = 0
num_rolls = int(input('Enter number of rolls:\n'))

if num_rolls >= 1:
for i in range(num_rolls):
    die1 = random.randint(1,6)
    die2 = random.randint(1,6)
    roll_total = die1 + die2

    #Count number of sixes and sevens
    if roll_total == 6:
        num_sixes = num_sixes + 1
    if roll_total == 7:
        num_sevens = num_sevens + 1
    print('Roll %d is %d (%d + %d)' % (i, roll_total, die1, die2))

print('\nDice roll statistics:')
print('6s:', num_sixes)
print('7s:', num_sevens)
else:
print('Invalid number of rolls. Try again.')
*

【问题讨论】:

    标签: python statistics dice


    【解决方案1】:

    使用while 循环是解决C 等编程语言中某些问题的一种非常常见的方法。在Python 中您也可以这样做,但是Python 有自己的方法来做一些事情。在您的情况下,您一直在使用 for 循环和 range() 函数。这比使用while 倒计时更“pythonic”,后者更“C-ish”。

    有趣的是,range 函数很聪明,您无需进行额外检查。任何整数参数< 1 将导致一个空列表,for 循环将不会被执行。而for 有一个else

    for i in range(num_rolls):
        # your dicing code
    else:
        print('Invalid number of rolls. Exiting.')
        sys.exit(1) # might be good to signal an error with a return code > 0
    
    # your result printing code
    

    TL;DR:你的代码即使不是更好也很好。仅当老师 (?) 需要 while 时才更改它。

    【讨论】:

    • 总的来说,这都是很好的建议……但这个问题是错误的。 “反复询问用户掷骰子的次数,只有当用户输入的数字小于1时才退出。”这需要一个外循环,围绕他的内循环。
    • (当然使用while num_rolls >= 1: 并在循环结束时重复input,这是我怀疑他的老师想要的,不是 Pythonic……但是这并不像用while 循环替换他的for 循环那样糟糕。)
    猜你喜欢
    • 2021-12-26
    • 2014-08-25
    • 2021-03-23
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 2019-03-04
    相关资源
    最近更新 更多