Skip to content

[Python] Use exec() Function To Batch Variable Assignment

When we developing a program, sometimes we need to assign many variable with one time. It may be when many interface components are made in one go, or when many numerical settings are made in one go.

This demand definitely exists, how can it be realized in Python?

It's actually very simple, just use the exec() function. Let's look at a simple example.


Use exec() function to declare 100 variables

Suppose we have a need to name 100 variables today, it's a somewhat exaggerated example, but in theory we can definitely do it.

# coding: utf-8


# Example
for i in range(100):
    exec('item_{} = {}'.format(i, i*10))


print('item_5:', item_5)
print('item_50:', item_50)



Output:

item_5: 50
item_50: 500

From the example, we can see that we have indeed assigned values to the variables through the exec() function. Regarding more ways to use the exec() function, I once recorded it in another blog post, you can refer to the link at the end of my article.


References


Read More

Tags:

Leave a Reply