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 = "geek"
globals ()[Dynamic_Variable_Name] = 2020
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 = "geek"
locals ()[Dynamic_Variable_Name] = 2020
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 = "geek"
exec ( "%s = %d" % (Dynamic_Variable_Name, 2020 ))
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 = "geek"
vars ()[Dynamic_Variable_Name] = 2020
print (geek)
|
Output:
2020
Last Updated :
13 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...