我有这个代码,当它不在函数形式时有效,但在它不是函数时却不行。
我可以致电grade()
,但在添加award()
时会收到错误。
这是我到目前为止所拥有的
def award(firstplace, secondplace):
print("")#return
print("The Player of the Year is: " + firstplace)
print("The Runner Up is: " + secondplace)
def grade():
count = 0
playeroftheyear = 0
runnerup = 0
firstplace = (" ")
secondplace = (" ")
for results in range (0,5):
name = input("Player Name: ")
fieldgoal = input("FG%: ")
fieldgoal = int(fieldgoal)
if fieldgoal > playeroftheyear:
runnerup = playeroftheyear
secondplace = firstplace
playeroftheyear = fieldgoal
firstplace = name
elif fieldgoal > runnerup:
runnerup = fieldgoal
secondplace = name
award(firstplace, secondplace)
return
grade()
答案 0 :(得分:0)
函数设置新的命名空间。您定义 in 函数的名称不能在外部函数中使用,除非您明确说明它们可以使用global
关键字。
在这种情况下,您要在grade
(firstplace
,secondplace
等)中定义名称,但award
无法使用这些名称,因为它们仅存在于grade
函数内。要让他们出来,你可以添加:
global firstplace
global secondplace
位于grade
功能的顶部。但是,绝对不是最好的方法。最好的方法是将它们作为参数传递:
def award(firstplace, secondplace):
...
然后你这样打电话给award
:
award(firstplace, secondplace)
答案 1 :(得分:0)
在您的代码中,firstplace
与secondplace
一样,仅存在于grade
,但不存在于award
。因此,当您尝试从award
访问它时,您会收到错误。
您需要将secondplace
和firstplace
作为参数传递:
def award(firstplace, secondplace):
print("")
print("The Player of the Year is: " + firstplace)
print("The Runner Up is: " + secondplace)
def grade():
...
award(firstplace, secondplace)
return
grade()