为什么我的计数变量不显示用户输入的数字?蟒蛇

时间:2014-07-02 19:19:44

标签: python variables

我的python程序要求用户输入任意随机数,将它们存储在适当的变量中,然后在最终语句中显示它们。我不知道为什么实际变量不显示计数输入。我感到困惑和困惑。

countOne = 0
countTwo = 0
countThree = 0
countFour = 0
countFive = 0
countSix = 0    


print("Welcome")
print("This program is determines how often a certain number appears after the dice have been tossed")
print("You will toss your dice then input the number rolled. After you have entered in the information, the program will tell you how many times the number appears")
userInput=int(input("Please enter the number shown(1-6) or enter 0 to quit: "))



for i in range(1, 6):
    if userInput == 1:
        countOne = countOne + 1
    elif userInput == 2:
        countTwo = countTwo + 1
    elif userInput == 3:
        countThree = countThree + 1
    elif userInput == 4:
        countFour = countFour + 1
    elif userInput == 5:
        countFive = countFive + 1
    elif userInput == 6:
        countSix = countSix + 1

while userInput != 0:
    if userInput >= 0 and userInput <= 6:
        userInput=int(input("Please enter the number shown(1-6) or enter 0 to quit: "))
    else:
        userInput=int(input("ERROR, NUMBER OUTSIDE RANGE!! Please enter the number shown(1-6) or enter 0 to quit: "))
print("Number 1 appeared: ",countOne," time.")
print("Number 2 appeared: ",countTwo," time.")
print("Number 3 appeared: ",countThree," time.")
print("Number 4 appeared: ",countFour," time.")
print("Number 5 appeared: ",countFive," time.")
print("Number 6 appeared: ",countSix," time.")
print("Thank you! Good Bye!")

它运行时没有语法错误,但会回复错误的数字。

1 个答案:

答案 0 :(得分:2)

你的循环毫无意义:

userInput=int(input("Please enter the number shown(1-6) or enter 0 to quit: "))
for i in range(1, 6):
    ...
while userInput != 0:
    ...

您输入一次,然后计算相同的输入五次,然后获取更多输入(不计算它)。此外,不需要六个单独的变量;只需使用六个整数的列表。

尝试将输入验证分成单独的函数(请参阅例如this community wiki),然后执行以下操作:

counts = [0 for _ in range(6)]
while True:
    ui = get_input() # input function validates 0 to 6
    if ui == 0:
        break
    else:
        counts[ui-1] += 1 # note -1 - list is zero-based

请注意,使用列表会删除大量重复:

print("Number 1 appeared: ",countOne," time.")
print("Number 2 appeared: ",countTwo," time.")
print("Number 3 appeared: ",countThree," time.")
print("Number 4 appeared: ",countFour," time.")
print("Number 5 appeared: ",countFive," time.")
print("Number 6 appeared: ",countSix," time.")

变为:

for num, count in enumerate(counts, 1):
    print("Number {0} appeared: {1} time.".format(num, count))