Skip to main content
 首页 » 编程设计

Python:未定义全局名称(但它不是全局变量)

2025年02月15日8Leo_wl

很抱歉在我最近问了一个问题之后又问了另一个问题。我已经尝试了所有尝试解决此问题的方法,但我无法解决。如果您问我尝试过什么,我的回答会是“我不知道”,因为在我为修复此错误所做的所有工作之后,我的头都在旋转。

def function1( ): 
    if driver == "Steve Park" and season == "2000" 
        averageFinish = 10.0 
    return averageFinish  
 
def function2( ): 
    momentum = int ( input ( "Enter the momentum for the driver: " ) ) 
    global driver, season 
    if driver == "Steve Park" and season == "2000" and momentum == "5" 
        newAverageFinish == function1( ) - 2.0 
    print( newAverageFinish ) 
    return newAverageFinish 
 
def main( ): 
    global driver 
    driver = input ( "Enter a driver: " ) 
    global season 
    season = int ( input ( "Enter a season: " ) ) 
    function1( ) 
    function2( ) 
    # Output should be 8.0 

输出是:

Enter a driver: Steve Park 
Enter a season: 2000 
Traceback (most recent call last): 
File "<stdin>", line1, in <module> 
File "<stdin>", line6, in main 
File "<stdin>", line5, in function1 
Name Error: global name 'averageFinish' is not defined 

我不知道为什么它认为平均完成度是全局的。此外,我在笔记本电脑上使用的键盘无法正常工作,所以我在平板电脑上输入了代码。我正在使用 android 应用程序 QPython3。与计算机 python 解释器相比,我不知道它是否会产生不同的错误消息。我之所以没有等到拿到键盘,是因为我真的很急于完成我个人程序的算法。在我的键盘出现之前,我正在 QPython3 中测试我计划的算法。

请您参考如下方法:

尝试运行下面的代码,我已经修复了你在代码中遇到的问题,

def function1( ): 
    if driver == "Steve Park" and season == 2000: 
        averageFinish = 10.0 
    return averageFinish  
 
def function2( ): 
    momentum = int ( input ( "Enter the momentum for the driver: " ) ) 
    #momentum = 5 
    global driver, season 
    if driver == "Steve Park" and season == 2000 and momentum == 5: 
        newAverageFinish = function1( ) - 2.0 
    print( newAverageFinish ) 
    return newAverageFinish 
 
def main( ): 
    global driver 
    driver = input ( "Enter a driver: " ) 
    #driver = "Steve Park" 
 
    global season 
    season = int ( input ( "Enter a season: " ) ) 
    #season = 2000 
 
    function1( ) 
    function2( ) 
    # Output should be 8.0 
 
main()