当错误达到5时,此代码继续运行,而错误停滞在5时,为什么呢?

时间:2019-02-19 20:17:35

标签: python

import random
number = random.randint(1,100)
mistakes = 0

功能从这里开始

def numberguesser(number,mistakes):
    guess = int(input("Guess?"))
    if guess < number:
        mistakes += 1
        print("Guess is too low, Mistakes:", mistakes)
    if guess > number:
        mistakes += 1
        print("Guess is too high, Mistakes:", mistakes)
    if guess == number:
        print ("Correct!")

这是我认为错误正在发生的地方,因为错误在达到五个错误后仍会继续猜测

    while guess != number and mistakes < 5:
        numberguesser(number, mistakes)
numberguesser(number, mistakes)

1 个答案:

答案 0 :(得分:0)

问题在于您的错误变量是全局变量,您需要在函数内部说。而且您不需要通过参数传递数字和错误,您可以仅传递您的猜测,想要的大小写,甚至可以将猜测放入函数中:) 尝试以下代码,这不是最佳解决方案,但应该可以正常工作:

import random
number = random.randint(1, 100)
mistakes = guess = 0

def numberguesser(guess):
  global mistakes, number # explicit says the global var

  if guess < number:
    mistakes += 1
    print("Guess is too low, Mistakes:", mistakes)
  elif guess > number:
    mistakes += 1
    print("Guess is too high, Mistakes:", mistakes)
  elif guess == number:
      print ("Correct!")

while guess != number and mistakes < 5:
  guess = int(input("Guess?"))
  numberguesser(guess)