很抱歉在我最近问过一个问题后又问了一个问题。我已经尝试了解决这个问题的一切,我无法解决它。如果你问我我尝试了什么,我的答案将是“我不知道”,因为在我尝试修复此错误的所有工作之后,我的脑袋正在旋转。
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中测试我计划的算法,直到我的键盘出现。
答案 0 :(得分:1)
尝试在代码下运行,我已修复了代码中的问题,
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()
答案 1 :(得分:0)
错误消息的措辞表明解释器在执行第5行时正在尝试查找名为averageFinish
的全局变量,并且不存在此类变量。你是对的averageFinish
不是全局变量。但是翻译是正确的,因为它没有为&#34; if&#34; function1
中的语句评估为false。它错误的原因是您在用户输入season
时将int
转换为season
,但在if语句中您将season == "2000"
与字符串进行比较。你写了season == 2000
而不是if
,这可能就是你想要的。
作为一个好的做法,您应该编写带参数的函数,而不是尝试通过全局变量传递信息。但这不是该计划失败的原因。