Python中的Dice统计信息

2024-09-26 17:48:13 发布

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

:反复询问用户掷骰子的次数,只有当用户输入的数字小于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.')
*

Tags: of用户numberifrandomnumtotalprint
1条回答
网友
1楼 · 发布于 2024-09-26 17:48:13

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

相关问题 更多 >

    热门问题