How to Create a Python Variable At Runtime Based on a User String Input?

5/5 - (1 vote)

πŸ’¬ 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 dir() function.

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!')
    name = input('your variable name: ')
    value = input('your variable value: ')
    create_var(name, value)


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 Vladimir:

You can learn more about the user input processing in the following tutorial.

🌍 Recommended Tutorial: Python input() Function

Python input() Function [6-Minute Primer]