0

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?

3
  • 1
    Short answer : you can't do that easily, but you can use a dictionary. Commented Apr 7, 2014 at 21:30
  • 2
    If you really wanted to do this, you could start hacking globals(), but that's a very bad idea Commented Apr 7, 2014 at 21:31
  • 1
    @C.B.: well, you can, with globals at least, but you really don't want to do that. Because next thing you know you want to address those variables and you'd have to generate those names again. And again, and again. While with a list or dictionary, you just don't have to worry about that. Commented Apr 7, 2014 at 21:31

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If I can use myself as an example, one of my first professional projects in Python involved getting file size information from a couple hundred machines. We were concerned that a purge process wasn't running correctly. I used globals() hacking to pipe them all into dictionaries named after each file, with the key as the machine I was polling. This means I have NO idea now how to maintain that script, and God Help Me if I ever have to repair it for any reason
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 in range(how_many):
    students["student{}".format(i+1)] = input("Student Name: ")

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

3 Comments

Note that i starts at 0, not 1, so you get student0 through to student<X-1>.
Surely you meant i + 1, not -.
Sure, embarrassing. I also accepted a suggested edit by @s16h

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.