Skip to content Skip to sidebar Skip to footer

Use Loop To Name Variables

So I essentially want to know how to do this in python: X = int(input('How many students do you want to add? ')) for X: studentX = str(input('Student Name: ')) Any ideas?

Solution 1:

You don't. You'd use a list instead:

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

Generally speaking, you keep data out of your variable names.

Solution 2:

I upvoted Martijn's answer, but if you need something similar to a variable name, that you can call with student1 to studentX, you can use an object:

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

I'm not gonna suggest the exec solution...

Post a Comment for "Use Loop To Name Variables"