簡體   English   中英

名稱“x”未定義/全局變量?

[英]Name 'x' is not defined / Global variable?

我正在學習使用 python 進行編程,我遇到了這個問題:我正在嘗試制作一個猜謎游戲,並且在嘗試檢查獲勝條件時,function 無法識別輸入變量,我確保我返回之前的 function。 所以我得到 'name << 'first_input' is not defined' >> 錯誤。 我認為這與變量不是全局的或類似的東西有關。

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

我沒有粘貼整個代碼,因為在測試它時它在這個階段返回了錯誤,所以我認為 rest 對這個特定問題並不重要。 我嘗試將 var 輸入設為全局和類似的東西,但我認為我做得不對。

您的方法調用不正確。 你應該這樣調用你的函數

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)

出現錯誤是因為您試圖在某處使用first_input (即在check_win_1()內部)。

一個可能但不推薦的解決方案是將您的變量限定為global ,應該非常謹慎地使用它。

相反,建議使用 function 參數,以便將您的代碼封裝在自包含的塊中,例如:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM