python-3.x - 无法记录我的 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.
解决方案
这是因为您要么在每次用户想再次玩游戏时调用guessinggame(),要么正在退出程序。此外,每次调用 guessinggame() 时,您都将 gamecount 设置为 0。您应该将 gamecount 声明和初始化移出您的函数。在调用 guessinggame() 之前还要增加 gamecount。
推荐阅读
- python - 嵌套列表中字典的数据框 - Python
- python - 尝试使用 PyOpengl 的索引和顶点绘制简单的正方形
- javascript - 使用 Javascript 向表中添加另一行时出现选项卡索引问题
- angular - NgxBootstrapIconsModule 已经加载。仅在 AppModule 中导入
- json - 用 yq 版本 4 更新 yaml 文件
- python - 有没有办法使用 python 获取谷歌云存储桶中的对象数量?
- python - 如何填充不连续的线
- python - 在第一个“linspace”排除某个点之后第二次“numpy.linspace”
- r - 如何向量化这个 ifelse 语句?
- python - 如何在 python 中将条码扫描器与 tkinter GUI 应用程序集成?