首页 > 解决方案 > 无法记录我的 while 循环运行了多少次 - Python3

问题描述

我正在为 python3 开发一个数字猜谜游戏,其最终目标是向用户展示他们是否玩了多个游戏,他们将收到平均数量的猜测。但是,我无法记录游戏实际运行了多少次。任何帮助都可以。

from random import randint
import sys

def guessinggame():
    STOP = '='
    a = '>'
    b = '<'
    guess_count = 0
    lowest_number = 1
    gamecount = 0
    highest_number = 100
    while True: 
        guess = (lowest_number+highest_number)//2
        print("My guess is :", guess)
        user_guess = input("Is your number greater than,less than, or equal to: ")
        guess_count += 1
        if user_guess == STOP:
            break
        if user_guess == a:
            lowest_number = guess + 1            
        elif user_guess == b:
            highest_number = guess - 1
    print("Congrats on BEATING THE GAME! I did it in ", guess_count, "guesses")
    PLAY_AGAIN = input("Would you like to play again? y or n: ")
    yes = 'y'
    gamecount = 0
    no = 'n'
    if PLAY_AGAIN == yes:
        guessinggame()
        gamecount = gamecount + 1
    else:
        gamecount += 1
        print("thank you for playing!")
        print("You played", gamecount , "games")
        sys.exit(0)
    return guess_count, gamecount

print('Hello! What is your name?')
myname = input()

print('Well', myname, ', I want you to think of number in your head and I will guess it.')
print("---------------------------------------------------------------------------------")
print("RULES:                 if the number is correct simply input '='")
print("---------------------------------------------------------------------------------")
print("                  if YOUR number is GREATER then the output, input '>'")
print("---------------------------------------------------------------------------------")
print("                  if YOUR number is LESS then the output, input '<'")
print("---------------------------------------------------------------------------------")
print("                                ALRIGHT LETS PLAY")
print("---------------------------------------------------------------------------------")



guessinggame()
guess_count = guessinggame()
print(" it took me this many number of guesses: ", guess_count)


## each game the user plays is added one to it
## when the user wants to the game to stop they finish it and
## prints number of games they played as well as the average of guess it took
## it would need to take the number of games and add all the guesses together and divide it.

标签: python-3.xif-statementwhile-loopbinarynumbers

解决方案


这是因为您要么在每次用户想再次玩游戏时调用guessinggame(),要么正在退出程序。此外,每次调用 guessinggame() 时,您都将 gamecount 设置为 0。您应该将 gamecount 声明和初始化移出您的函数。在调用 guessinggame() 之前还要增加 gamecount。


推荐阅读