Python program to create dynamically named variables from user input
Given a string input, our task is to write a Python program to create a variable from that input (as a variable name) and assign it to some value. Below are the methods to create dynamically named variables from user input.
Using globals() method to create dynamically named variables
Here we are using the globals() method for creating a dynamically named variable and later assigning it some value, then finally printing its value.
Python3
# Dynamic_Variable_Name can be # anything the user wants Dynamic_Variable_Name = "geek" # The value 2020 is assigned # to "geek" variable globals ()[Dynamic_Variable_Name] = 2020 # Display variable print (geek) |
Output:
2020
Using locals() method to create dynamically named variables
Here we are using the locals() method for creating dynamically named variable and later assigning it some value, then finally printing its value.
Python3
# Dynamic_Variable_Name can be # anything the user wants. Dynamic_Variable_Name = "geek" # The value 2020 is assigned # to "geek" variable locals ()[Dynamic_Variable_Name] = 2020 # Display variable print (geek) |
Output:
2020
Using exec() method to create dynamically named variables
Here we are using the exec() method for creating dynamically named variable and later assigning it some value, then finally printing its value.
Python3
# Dynamic_Variable_Name can be # anything the user wants. Dynamic_Variable_Name = "geek" # The value 2020 is assigned # to "geek" variable exec ( "%s = %d" % (Dynamic_Variable_Name, 2020 )) # Display variable print (geek) |
Output:
2020
Using vars() method to create dynamically named variables
Here we are using the vars() method for creating dynamically named variable and later assigning it some value, then finally printing its value.
Python3
# Dynamic_Variable_Name can be # anything the user wants. Dynamic_Variable_Name = "geek" # The value 2020 is assigned # to "geek" variable vars ()[Dynamic_Variable_Name] = 2020 # Display variable print (geek) |
Output:
2020