首页 > 解决方案 > 我怎样才能把它放在一个循环中,在开始时尝试使用一个while循环,但我会得到错误的输出

问题描述

提前致谢。

import random

user_input= int(input("How many times would you like to roll the dice?"))

Dice_1 = [random.randint(1,6) for x in range(user_input)]
Dice_2 = [random.randint(1,6) for x in range(user_input)]

count = 0
for a,b in zip(Dice_1,Dice_2):
    if((a)) == ((b)):
        print("double")
        count += 1
    else:
        print((a,b))

print(f'\nYou have scored {count} doubles! out of {user_input}')

标签: pythonloops

解决方案


所以我不确定你的第一次尝试,但我想说即使失败了,看看你尝试了什么也会很棒:)

使用 while 循环是最简单、最方便的方法。例如

import random

while user_input := int(input("How many times would you like to roll the dice?")) :
    Dice_1 = ...
    ... # roll dice, blah blah

会做你想做的。输入 0 将中断 while 循环(因为0在 python 中被认为是假的,即while 0->while False并且任何其他整数都被认为是真)。请注意,它使用海象运算符:=而不是=

没有海象运算符,上面与下面类似:

user_input = int(input("How many times would you like to roll the dice?"))

while user_input != 0:
  ... # roll dice, blah blah
  
  #then ask again if they want to roll again
  user_input = int(input("How many times would you like to roll the dice?")

:=海象运算符只是使其更具可读性的一种方法(它计算结果值并将:= int(input("How many times would you like to roll the dice?"))其分配给user_input)。


推荐阅读