您可以在定义的函数中执行执行时评估全局值吗?

问题描述 投票:-2回答:1

这是我的代码:

import time

def guessit():
    print('i have a number from 0 to 10 and you must guess it!')
    guess = input("what's the number?")
    if guess == a: # this is the global variable specified in the function "randomnumber"#
        print('you cheater! how did you know? fine, you win!')
    else:
        print('you failed! i win! would you like to play again?')
        randomnumber()

def randomnumber():
    global a
    a = random.randint(0, 10)
    guessit()

randomnumber()

这里是一些上下文:

这是游戏,用户猜出一个从十到十的数字。

问题:

打印值a没问题,这是评估它的问题。每当我尝试这样做时,甚至通过打印a值进行复制粘贴,仍然会给我else评估结果。

我尝试输入local(相反,global是python中的关键字),但是没有像其他任何关键字一样突出显示。

执行时是否有任何方法可以使全局变量a成为函数内部的局部变量?

python variables global local python-3.8
1个回答
0
投票

欢迎来到网站!否。该变量需要在全局范围内定义:

a = 7 # 7 for example

import time

def guessit():
    global a
    print('i have a number from 0 to 10 and you must guess it!')
    guess = input("what's the number?")
    if guess == a: # this is the global variable specified in the function "randomnumber"#
        print('you cheater! how did you know? fine, you win!')
    else:
        print('you failed! i win! would you like to play again?')
        randomnumber()

def randomnumber():
    global a
    a = random.randint(0, 10)
    guessit()

randomnumber()

您未正确使用global关键字。它没有定义新变量,仅声明该函数将使用预定义的全局变量。

希望这会有所帮助!如果您有任何问题,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.