gpt4 book ai didi

python - 猜数字游戏-全局变量

转载 作者:太空宇宙 更新时间:2023-11-03 14:22:50 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,它可以简单地生成一个随机数,然后让您猜测该数字。该程序的大部分工作正常,但我遇到了一个问题,我认为该问题与局部和全局变量有关,但无法找出解决方案。一旦一切顺利,我打算让一切变得更简单、更简洁。

当玩家进行新的猜测时,游戏应该在开始时说明这是哪个数字。为此,我在开头分配了一个变量 guess_num ,并创建了 guess_count 函数来计数并重新定义每个后面的 guess_num 全局变量猜测。

当运行guess_input函数时,它会连接并打印“Guess Number”,后跟guess_num变量。然而,程序似乎使用了 guess_num - 1,而不是使用新的全局 guess_num 变量。

在游戏结束时,它会总结猜测的数量,这会正确显示猜测的数量,这与 guess_input 函数不同。

希望有人能够通过一个简单的解决方案来阐明我确信是一个愚蠢的错误。

猜数字游戏

import random

guess_num = 1

def guess_count():
global guess_num
guess_num = guess_num + 1

def guess_input():
global guess
print("Guess Number "+ str(guess_num))
guess = int(input("Guess a number between " + str(low) + " and " + str(high) + ":"))
exceed()
guess_output()

def user_entry():
global low
global high
global rand_num
low = int(input("Type the lowest whole number the PC will generate: "))
high = int(input("Type the highest whole number the PC will generate: "))
print ("")
if low > high:
print ("ERROR: The lowest number cannont be greater than the highest")
print ("")
user_entry()
rand_num = random.randint(low, high)

def exceed():
if guess < low:
print("")
print("Your guess of " + str(guess) + " is less than " + str(low) + " which is the lowest possible value - try again")
print("")
guess_input()
if guess > high:
print("")
print("Your guess of " + str(guess) + " is more than " + str(high) + " which is the highest possible value - try again")
print("")
guess_input()

def guess_output():
global low
global high
if guess > rand_num:
print(str(guess) + " is too high!")
print("")
high = guess
guess_input()
guess_count()
elif guess < rand_num:
print(str(guess) +" is too low!")
print("")
low = guess
guess_input()
guess_count()
elif guess == rand_num:
print ("Correct!")

def count_sum():
print("")
if guess_num == 1:
print(str(guess_num) + " guess was made")
elif guess_num > 1:
print(str(guess_num) + " guesses were made")

user_entry()
# print(rand_num) #used for Debugging
guess_input()
count_sum()

最佳答案

你交换了顺序

guess_input()
guess_count()

在你的guess_output函数中。在报告该数字之前,您需要增加猜测的数量。

存在许多架构困难,但一个建议可能是将成功条件移至第一个,然后是 return,这样您就不必在两个地方进行相同的更改:

  global low
global high

if guess == rand_num:
print ("Correct!")
return

if guess > rand_num:
print(str(guess) + " is too high!")
print("")
high = guess

elif guess < rand_num:
print(str(guess) +" is too low!")
print("")
low = guess

guess_count()
guess_input()

关于python - 猜数字游戏-全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47833057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com