因此,我试图创建一个代码,它接受用户对num_rolls
的输入,然后多次掷两个骰子。你知道吗
它记录了有多少个6和7出现。然后打印出每一卷和数字。我让代码一直要求输入转鼓,直到他选择1退出循环,然后打印统计数据。你知道吗
我遇到的问题是,在我的第二个输入请求被请求之后,它只是继续往下写代码。你知道吗
如何让它返回并从while
循环开始?我的第二个输入是在错误的位置还是我需要创建一个额外的循环?你知道吗
代码如下:
import random
num_sixes = 0
num_sevens = 0
num_rolls = int(input('Enter number of rolls:\n'))
while num_rolls >= 1:
for i in range(1,num_rolls + 1):
die1 = random.randint(1,6)
die2 = random.randint(1,6)
roll_total = die1 + die2
#Count number of 6 and 7 rolled
if roll_total == 6:
num_sixes = num_sixes + 1
if roll_total == 7:
num_sevens = num_sevens + 1
if i in range(1,num_rolls+1):
print('Roll %d is %d (%d + %d)' % (i, roll_total, die1, die2))
num_rolls = int(input('Enter number of rolls:\n'))
print('\nDice roll statistics:')
print('6s:', num_sixes)
print('7s:', num_sevens)
else:
print('Invalid number of r2olls. Try again.')
如果要在
num_rolls
等于1
时退出循环,则需要测试while num_rolls > 1
,而不是while num_rolls >= 1
。如果您只想在程序结束时打印骰子滚动的结果,那么您应该删除
从
while
循环,并将其放在程序的末尾。你明白你的
while
循环末尾的else
子句是做什么的吗?我很确定你的行为不是你想要的。如果要验证用户的输入是否有效,则需要与主while
循环分开进行。你知道吗因为您没有指定如何验证用户的输入,所以我将把这个任务留给您。其实很简单。详见Asking the user for input until they give a valid response。最重要的一点是,您需要一个单独的循环。
这是您的代码,上面做了修改:
当测试上述代码时,它将生成输出:
如果要验证用户输入是否为正整数,可以使用下面的代码1:
然后,您可以在需要获取用户输入的任何地方调用上述函数:
1上述解决方案利用
str.isdigit
为负数返回false这一事实,确实有点作弊,但它仍然适用于您的情况。相关问题 更多 >
编程相关推荐