I want to create varibales as a1,a2,a3,...a10.
For that i used a for loop.As the variable in loop increments..i need var gettng created as above .

Can anyone give me an idea?

At the same time of creation i need to be able to assign to them

There i m gettng syntax error:(

9 Years
Discussion Span
Last Post by paddy3118

One way to do this:

# creates variables qq1 - qq4 and initializes to 77
for i in range(1, 4):
    exec "%s = %d" % ('qq' + str(i), 77)

print qq1  # 77

However why do you need to create these variables ? In such cases, it's usually better to create a list of 10 elements a[0], ..., a[9] like this

a = [None] * 10
for i in range(len(a)):
    a[i] = 77 - i * i

Listen to the guy who told you to use a list.

If you don't know about exec, your probably going about solving your problem in the wrong way by using it. Try thinking of how you might solve things using a list or a dictionary. exec is something to use if those approaches fail you.

- Paddy.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.