-3

Is there a way to make variables with a for statement using the variable from the for statement in order to add a number to the end of the variable name?

Here is an example of what I'm trying to achieve:

for i in range(1,9):
    grade+i = round(float(input(firstprompt)))
    type+i = input(secondprompt)
3
  • 3
    See the link from @VanPeer for two reasons: First, it tells you a much better way to handle arbitrary numbers of values with dynamic names (in Python, use a list or a dictionary, depending on whether an integer index is sufficient or a static name per value is required). Second, it gives good reasons never do what you're asking how to do, in any language, whether it's well-supported or not. Commented Nov 1, 2018 at 3:19
  • So... what's wrong with a list? Commented Nov 1, 2018 at 3:22
  • Also see How can you dynamically create variables via a while loop? (even though it's marked as a "dup'). In addition, there's Python - Dynamic variables. Get the hint? Commented Nov 1, 2018 at 3:29

2 Answers 2

0

I think it is better for you to use list or dict object for that instead

For list

grade = []
type = []
for i in range(1,9):
    grade.append(round(float(input(firstprompt))))
    type.append(input(secondprompt))


For dict

grade = {}
type = {}
for i in range(1,9):
    grade["grade"+str(i)] = round(float(input(firstprompt)))
    type["type"+str(i)] = input(secondprompt)
Sign up to request clarification or add additional context in comments.

3 Comments

The grade+i and type+i for a dictionary aren't going to work...you can't add an integer to a dictionary.
I edited the code for that
Unfortunately your edit doesn't make it work—you can't add (or concatenate) the integer value of the variable i to the strings "grade" and "type" like that (it raises a TypeError).
0

I thought i wouldn't really be possible, but I realized you could use exec in a for loop to achieve that effect:

prompt1 = 'Enter a number:\n'; prompt2 = 'Enter a string:\n' for i in range(1, 9): exec('grade{} = int(input(prompt1))'.format(i)) exec('type{} = input(prompt2)'.format(i))

Although as Andreas suggested, a list would probably be better.

2 Comments

If one were hell-bent on doing this, I would not recommend exec. There's cheaper and safer ways such as modifying the namespace dicts stackoverflow.com/a/1373201/365102.
Yeah, I get that exec is rarely used and not that great. The question did ask for this solution, and from the link above it does say that even locals() can't edit variables even if globals could. I also mentioned it wasn't the best solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.