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

2024-10-04 11:31:00 发布

您现在位置:Python中文网/ 问答频道 /正文

很抱歉在我最近问了一个问题之后又问了一个问题。我想尽一切办法来解决这个问题,但我解决不了。如果你问我做了什么,我的回答会是“我不知道”,因为在我努力纠正这个错误之后,我的脑子都在转。在

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

输出为:

^{pr2}$

我不知道为什么它认为平均完成是一个全球性的。另外,我笔记本电脑上的键盘坏了,所以我在平板电脑上输入了代码。我使用的是android应用程序QPython3。我不知道它是否会产生与计算机python解释器不同的错误消息。我之所以不等到拿到我的键盘,是因为我真的很想为我的个人程序完成算法。我在QPython3中测试我计划的算法,直到我的键盘来。在


Tags: andparkinputifdefdriver错误键盘
2条回答

错误消息的措辞表明,解释器在执行第5行时试图查找名为averageFinish的全局变量,并且不存在此类变量。你说得对,averageFinish不是全局变量。但是解释器是正确的,它没有为function1中的“if”语句计算结果为false的情况下定义它。错误的原因是,一旦用户输入season就将其转换为int,但在if语句中,将season与字符串进行比较。您写的是season == "2000",而不是{},这可能是您想要的。在

作为一个好的实践,您应该编写带参数的函数,而不是试图通过全局变量传递信息。但这并不是这个项目失败的原因。在

试着运行下面的代码,我已经修复了你代码中的问题

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()

相关问题 更多 >