数字猜测游戏 - 全局变量

时间:2017-12-15 13:08:10

标签: python python-3.x

我正在尝试编写一个只生成随机数的程序,然后允许您猜测该数字。该计划的大部分工作,但我有一个问题,我认为与本地和全球变量有关,但无法找出解决方案。一旦一切正常,我打算让一切变得更简单,更简洁。

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

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

在游戏结束时,它总结了猜测的数量,这正确地显示了猜测的数量,与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()

1 个答案:

答案 0 :(得分:1)

您已交换了

的顺序
width:100px;

guess_input() guess_count() 函数中。在报告该数字之前,您需要增加猜测次数。

存在许多架构上的困难,但有一条建议可能是将成功条件移至首先跟随guess_output,这样您就不必在两个地方进行相同的更改:< / p>

return