Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python program to create dynamically named variables from user input

  • Last Updated : 19 May, 2021

Given a string input, the task is to write a Python program to create a variable from that input (as a variable name) and to assign it some value. Below are the methods to create dynamically named variables from user input: 

Method 1: Using globals() method.

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

Method 2: Using locals() method.

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

Method 3: Using exec() method.

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

Method 4: Using vars() method

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!