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:(

Recommended Answers

All 4 Replies

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

Thank you Sneekula. It was helpful.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.