:反复询问用户掷骰子的次数,只有当用户输入的数字小于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.')
*
使用
while
循环是解决C等编程语言中某些问题的一种非常常见的方法。在Python中,您也可以这样做,但是Python有它自己的方法来做一些事情。在您的例子中,您一直在使用for
循环和range()
函数。这比用while
倒计时更“python”,后者更“C-ish”。在有趣的是,
range
函数很聪明,不需要做额外的检查。任何整型参数< 1
都将导致空列表,并且不会执行for
循环。并且for
有一个else
:TL;DR:如果不是更好的话,您的代码也可以。只有当老师(?)需要
while
。在相关问题 更多 >
编程相关推荐