正如我的名字所暗示的那样,我对此非常陌生,并在我的大学上进行了低级编码课程。我应该写一个程序,接受20个名字然后按字母顺序排序。
我一直在讨论这里的问题,他们帮助所有人直到这个项目。我找到了建议的代码
strs = ["" for x in range(20)]
所以我像这样修改了
def main():
names = ["" for x in range (20)]
names = getNames(names)
displayInfo(names)
def getNames(names)
counter = 0
while counter < 20:
names[counter] = input("Enter a name: ")
return names
但是如果我输入一个名字(比如说“Amber”),我一直都会收到这样的错误信息。
NameError: name 'Amber' is not defined
我该如何纠正这个?我的书只用伪代码说话,我的老师不太擅长教学。由于这个网站,我的大部分作业已经完成。
答案 0 :(得分:2)
你有几个问题:
raw_input
; SyntaxError
(缺少:
);和counter
。 此外,使用while
for
会做def main():
names = getNames(20)
displayInfo(names)
def getNames(n):
names = []
for _ in range(n):
names.append(raw_input("Enter a name: "))
return names
是不好的做法,并且不需要像这样初始化列表。相反,我建议:
{{1}}
答案 1 :(得分:0)
当你在Python-2.x中输入时,你应该使用raw_input()
而不是input()
。 input()
从字面上理解输入,因此它只需要在shell中调用的东西:
>>> import sys
>>> print sys.version_info[0:3]
(2, 7, 6)
>>> Amelia
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Amelia' is not defined
>>> name = input('Enter your name: ')
Enter your name: Amelia
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'Amelia' is not defined
>>> name = raw_input('Enter your name: ')
Enter your name: Amelia
>>>
而是将代码更改为以下内容:
def main():
names = sorted([raw_input("Enter a name: ") for i in range(20)]) #You can change the 20 to however many names you want
for i in names: print i
运行如下:
>>> main()
Enter a name: Bob
Enter a name: Joe
Enter a name: Sally
Enter a name: Jimmy
Enter a name: Cole
Enter a name: Brian
Enter a name: Ronald
Enter a name: Harry
Enter a name: Henry
Enter a name: Dylan
Enter a name: Coby
Enter a name: Jodie
Enter a name: Billy
Enter a name: Walter
Enter a name: Sue
Enter a name: Leon
Enter a name: Francis
Enter a name: Angela
Enter a name: George
Enter a name: Amelia
Amelia
Angela
Billy
Bob
Brian
Coby
Cole
Dylan
Francis
George
Harry
Henry
Jimmy
Jodie
Joe
Leon
Ronald
Sally
Sue
Walter
>>>
这使用列表理解来获取输入一定次数:
>>> names = [raw_input("Enter a name for person number %d: " %(i)) for i in range(1, 6)]
Enter a name for person number 1: Angela
Enter a name for person number 2: Amelia
Enter a name for person number 3: Joe
Enter a name for person number 4: John
Enter a name for person number 5: Sam
>>> names
['Angela', 'Amelia', 'Joe', 'John', 'Sam']
>>>