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.
# 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.
# 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.
# 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
# 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
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.