使用循环命名变量

时间:2014-04-07 21:29:29

标签: python

所以我基本上想知道如何在python中执行此操作:

X = int(input("How many students do you want to add? "))
for X:
    studentX = str(input("Student Name: "))

有什么想法吗?

2 个答案:

答案 0 :(得分:6)

你不是。您改为使用列表:

how_many = int(input("How many students do you want to add? "))
students = []
for i in range(how_many):
    students.append(input("Student Name: "))

一般来说,你是keep data out of your variable names

答案 1 :(得分:2)

我赞成了Martijn的答案,但是如果你需要类似于变量名的东西,你可以用student1调用studentX,你可以使用一个对象:

how_many = int(input("How many students do you want to add? "))
students = {}
for i in range(how_many):
    students["student{}".format(i+1)] = input("Student Name: ")

我不建议exec解决方案......