Dynamic variables using python

In this article we shall see how to create dynamic variables in python. This will be helpful in scenarios where the user’s input has to be stored in a variable and access in later part of the program. Dynamic variables can be created using the following two ways.

  1. exec()
  2. dictionary

Let us look at the above two methods one by one with an example for each.


The first method is using the built-in method called exec(). exec() function is used for the dynamic execution of Python program which can either be a string or object code. If it is a string, the string is parsed as a suite of Python statements which is then executed unless a syntax error occurs and if it is an object code, it is simply executed.

Let me show you an example where the user provides a string and we convert it into a variable using the exec() method.

exec() method

As we can see I have provided a string with a key and a value. The exec() method interpreted it and converted it into variable.

Using dictionary

The next method is using the dictionary. It will be easier to explain this with an example.

variables = {}
for i in range(0, 3):
    key = input()
    value = input()
    variables[key] = value


In this example I am getting the key=value pairs for three times. The user will enter them one by one which will be added to the dictionary as a key-value pair.

The output of the above code is,


{'name': 'Adam', 'age': '35', 'country': 'Brazil'}

As you can see I have entered the key value pairs one by one. Finally they are updated in a dictionary which can be used later.

Note: The only problem with this method is all the values are considered as string. If you are sure when or where the integer input will occur, then you can get the input from the user and convert it into integer before saving it to the dictioanry.


Hope this article is helpful. If you have any queries leave them in the comments below.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *