TypeError:'int'对象不支持项目赋值,我不明白我的错误在哪里

时间:2013-12-05 04:46:04

标签: python python-3.x

name=0
gender=0
gpa=0
k=1

num= float(input("how many student's would you like to process?  "))

while k<num:
    name[k]= (input("enter student's first and last name: "))
    print (name[k])
    gender[k]=(input("enter student's gender: "))
    gpa[k]=(input("enter student's grade point average: "))
    print (name[k]," is a ",gender[k]," with a G.P.A of ",gpa[k])
    k=k+1

另外,如果您在输入“未知”的性别时可以帮我指出如何终止循环的方向,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

我建议您将一个人的数据放入一个对象中,不要为此任务使用索引。 Python字典是存储此类数据的一个很好的容器。这是一个简单的代码:

# Why to ask an extra input? Spare this for the user!
# num = float(input("how many student's would you like to process?  "))

students = []
while True:
    name = input("enter student's first and last name (or Enter if done): ")
    if not name: # I could have used 'if name == "":' here too.
        break
    gender = input("enter student's gender: ")
    # I don't know why you want this but here is it:
    if gender.lower() == "unknown":
        break
    gpa = input("enter student's grade point average: ")
    students.append({"name": name, "gender": gender, "gpa": gpa})
    print ("{} is a {} with a G.P.A of {}".format(name, gender, gpa))

试运行(python -i gpa.py):

enter student's first and last name (or Enter if done): John Smith
enter student's gender: male
enter student's grade point average: 4
John Smith is a male with a G.P.A of 4
enter student's first and last name (or Enter if done): Scarlet Clark
enter student's gender: female
enter student's grade point average: 3
Scarlet Clark is a female with a G.P.A of 3
enter student's first and last name (or Enter if done):
>>> students
[{'name': 'John Smith', 'gpa': '4', 'gender': 'male'},
 {'name': 'Scarlet Clark', 'gpa': '3', 'gender': 'female'}]
>>> students[1]
{'name': 'Scarlet Clark', 'gpa': '3', 'gender': 'female'}
>>> students[1]["gpa"]
'3'