Python 3.6:我的变量在每次猜测后都不会添加数字

时间:2017-09-26 00:35:06

标签: python python-3.x

我的代码有效,一切运行正常,但计数器在每次猜测后都没有添加数字。无论用户有多少猜测,它总是输出“guess = 1”。

import random

number = random.randint(1,100)
counter = 1

while True:
    pick = input("Choose a number between 1 and 100. ")
    pick = int(pick)
    if pick == number:
        print("You are correct, great job! ")
        print("\n")
        print("How many guesses you had: ", counter)
        print("\n")
        continue

    while True:
        if pick > number:
            print("That was too high of a guess. Try again. ")
            counter + 1
            print("How many guesses you have had: ", counter)
            print("\n")
            break       
        elif pick < number:
            print("That was too low of a guess. Try again. ")
            counter + 1          
            print("How many guesses you have had: ", counter)
            print("\n")
            break

1 个答案:

答案 0 :(得分:2)

设置计数器

import random

number = random.randint(1,100)
counter = 1

while True:
    pick = input("Choose a number between 1 and 100. ")
    pick = int(pick)
    if pick == number:
        print("You are correct, great job! ")
        print("\n")
        print("How many guesses you had: ", counter)
        print("\n")
        continue

    while True:
        if pick > number:
            print("That was too high of a guess. Try again. ")
            counter = counter + 1
            # counter +=1  # alternate form
            print("How many guesses you have had: ", counter)
            print("\n")
            break       
        elif pick < number:
            print("That was too low of a guess. Try again. ")
            counter = counter + 1          
            # counter += 1  # alternate form
            print("How many guesses you have had: ", counter)
            print("\n")
            break