💬 Question: Say, you want to dynamically create a variable in your Python script that is named like a string. For example, you want to name the variable after a string value
'Vladimir' and assign a value to it so you can access the results using only the variable name
Vladimir without the string quotes around
'Vladimir'. How to accomplish this in Python?
You can dynamically create a global variable based on a given string in
var_name by using the expression
globals()[var_name] = var_value to modify the dictionary of the global variables.
This code snippet is used to create a global variable. It takes user input for the variable name and value, then calls the
create_var() function which creates a new global variable with the given name and value. Finally, it prints out a list of all global variables that have been defined using the built-in
def create_var(var_name, var_value): globals()[var_name] = var_value q = input('Do you want to create a new variable? ') if q!='y': print('okay, bye!') else: name = input('your variable name: ') value = input('your variable value: ') create_var(name, value) print(dir())
Here’s an example run where the user types in the string
'Vladimir' and the code creates a new variable that can be accessed without the quotes, i.e., as variable
You can learn more about the user input processing in the following tutorial.
🌍 Recommended Tutorial: Python
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.