我被赋予此算法以转换为伪代码:
Name[1] = 'Ben'
Name[2] = 'Thor'
Name[3] = 'Zoe'
Name[4] = 'Kate'
Max <- 4
Current <- 1
Found <- False
OUTPUT 'What player are you looking for?'
INPUT PlayerName
WHILE (Found = False) AND (Current <= Max)
IF Names[Current] = PlayerName
THEN Found <- True
ELSE Current <- Current + 1
ENDIF
ENDWHILE
IF Found = True
THEN OUTPUT 'Yes, they have a top score'
ELSE OUTPUT 'No, they do not have a top score'
ENDIF
所以我把它转换成Python就像这样:
def Names():
list = ['Ben', 'Thor', 'Zoe', 'Kate']
Max = 4
Current = 1
Found = False
PlayerName = str(input("What Player are you looking for? "))
while (Found == False) and (Current <= Max):
if Names(Current) == PlayerName:
Found = True
else:
Current = Current + 1
if Found == True:
print("Yes, they have a top score.")
else:
print("No, they do not have a top score.")
但是出现了一个错误:
'TypeError: Names() takes 0 positional arguments but 1 was given'
我哪里出错了?
答案 0 :(得分:4)
让我们分析你得到的错误:
'TypeError: Names() takes 0 positional arguments but 1 was given'
它说,你所做的函数,名为Names()
,取零参数,但你给它一个参数。
在您的代码中,当您在函数Names(Current)
中使用Names()
时,可以看到这一点。实际上,这是再次调用函数,因此您无意中编写了一个您不想要的递归函数。
您要做的是检查名称列表,以查看是否有任何名称与用户输入的名称相匹配。
要执行此操作,请使用for循环而不是while循环。这样,您就不必专门说明列表的起点和终点,如果您愿意,可以添加其他名称。
这就是转化的样子:
def Names():
names_list= ['Ben', 'Thor', 'Zoe', 'Kate']
Found = False
PlayerName = str(raw_input("What Player are you looking for? "))
for name in names_list:
if name == PlayerName:
Found = True
if Found == True: #place this if-else outside your for-loop
print("Yes, they have a top score.")
else:
print("No, they do not have a top score.")
Names()
这将输出:
>>>
What Player are you looking for? Thor
Yes, they have a top score.
>>>
What Player are you looking for? Bob
No, they do not have a top score.
答案 1 :(得分:1)
您收到type
错误,因为您试图将参数传递给Names
函数。 Names
不接受任何参数,因为那里没有列出任何参数。您需要在不使用参数的情况下调用函数,或在声明Names
函数时向括号中添加参数。此外,除非返回函数,否则无法从外部访问函数本地变量。所以不要这样做:
Names["Something"] == Another_Thing
但是,相反传递你需要你的函数吐出作为参数。如果您需要全局访问其中的所有内容,请不要在函数内部定义所有内容,而是在其外部定义,并将您尝试执行的所有内容作为参数传递给函数。
def Names(A_Parameter, Another_Parameter, A_Default_Parameter = Some_Default):
# do something
答案 2 :(得分:1)
@logic有一个解决方案,但它可以简化。无需str
,for
循环或Found
变量。
def Names():
names_list = ['Ben', 'Thor', 'Zoe', 'Kate']
PlayerName = raw_input("What Player are you looking for? ")
if PlayerName in names_list:
print "Yes, they have a top score."
else:
print "No, they do not have a top score."
Names()
Python 2.x中的 print
也不应该有括号。在上述情况下,这并不重要,但会有以下几点:
PlayerName = "Ben"
print("Name:",PlayerName)
print "Name:",PlayerName
输出:
('Name:', 'Ben')
Name: Ben