Aidan H
Aidan H

Reputation: 21

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?

Upvotes: 0

Views: 89

Answers (2)

Mathias
Mathias

Reputation: 1500

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 in range(how_many):
    students["student{}".format(i+1)] = input("Student Name: ")

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

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121514

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

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

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

Upvotes: 6

Related Questions