名称“ x”未定义/全局变量?

时间:2019-09-27 17:47:10

标签: python

我正在学习使用python编程,遇到了这个问题:我正在尝试做一个Guessing游戏,并且在尝试检查获胜条件时,该函数无法识别输入变量,确保我返回了以前的功能。所以我得到'名称<<'未定义first_input'>>错误。我认为这与变量不是全局或类似的东西有关。

import random
ran_int = random.randint(1,100)
guesses = 0

# here you input the number and it keeps asking unless you do so with 1 to 100

def ask():
    first_input = 0
    while first_input < 1 or first_input > 100:
        first_input = int(input('Enter a number between 1 and 100: '))
    return first_input

# this is just to increment the number of guesses stored for showing at the end # of the game

def guesses_inc():
    global guesses
    guesses += 1
    return guesses

# here is where i get the error, as if my ask() function didn't return 
# the value properly or as if I assigned it wrongly

def check_win_1():
    if first_input == ran_int:
        guesses_inc()
        print(f'BINGO!\nYou guessed correctly after {guesses} times.')
    elif (abs(ran_int - first_input) <= 10):
        guesses_inc()
        print('WARM!')
        ask2()
    elif first_input < 1 or first_input > 100:
        print('Out of bounds!')
        ask2()
    else:
        guesses_inc()
        print('COLD!')
        ask2()

ask()
check_win_1()

这是错误

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-11-bfd5497995df> in <module>
----> 1 check_win_1()

NameError: name 'first_input' is not defined

我没有粘贴整个代码,因为在测试它时,它在此阶段返回了错误,因此我认为其余的代码对这个特定问题没有影响。我尝试使var输入成为全局变量,但我认为我做得不好。

2 个答案:

答案 0 :(得分:0)

您的方法调用不正确。您应该这样调用函数

def check_win_1(first_input):
    if first_input == ran_int:
        guesses_inc()
        print(f'BINGO!\nYou guessed correctly after {guesses} times.')
    elif (abs(ran_int - first_input) <= 10):
        guesses_inc()
        print('WARM!')
        ask2()
    elif first_input < 1 or first_input > 100:
        print('Out of bounds!')
        ask2()
    else:
        guesses_inc()
        print('COLD!')
        ask2()
first_input = ask()
check_win_1(first_input)

答案 1 :(得分:0)

存在错误是因为您试图在某个地方(即first_input内)使用check_win_1()

一种可能(不建议使用)的解决方案是将变量限定为global,应谨慎使用非常

相反,建议使用函数参数,以便将代码封装在独立的块中,例如:

def func(a, b):
    return a + b


x = func(10, 5)

而不是:

def func():
    global a, b
    return a + b

a = 10
b = 5

x = func()

对于您而言,这可能意味着您需要执行以下操作:

def check_win_1(first_input, ran_int):
    ...

并相应地使用它们,例如:

first_input = ask()
check_win_1(first_input, ran_int)


编辑

按照上述原则,您的代码可能看起来像这样:

import random

MIN_VAL = 1
MAX_VAL = 100
WARM_LIMIT = 10


def ask_number(
        min_val=MIN_VAL,
        max_val=MAX_VAL):
    guess = None
    while guess is None:
        guess = int(input(f'Enter a number between {min_val} and {max_val}: '))
        if guess < min_val or guess > max_val:
            print('Out of bounds!')
            guess = None
    return guess


def check_guess(
        guess,
        target,
        num_guesses,
        warm_limit=WARM_LIMIT):
    if guess == target:
        print(f'BINGO!\nYou guessed correctly after {num_guesses} times.')
        return True
    else:
        if (abs(guess - target) <= warm_limit):
            print('WARM!')
        else:
            print('COLD!')
        return False


# : main
target = random.randint(MIN_VAL, MAX_VAL)
num_guesses = 0
won = False
while not won:
    guess = ask_number()
    num_guesses += 1
    won = check_guess(guess, target, num_guesses)