Creating Dynamically Named Variables from User Input

How can you dynamically create variables?

Unless there is an overwhelming need to create a mess of variable names, I would just use a dictionary, where you can dynamically create the key names and associate a value to each.

a = {}
k = 0
while k < 10:
# dynamically create key
key = ...
# calculate value
value = ...
a[key] = value
k += 1

There are also some interesting data structures in the collections module that might be applicable.

How to create variables with their name taken as input from user?

It's very much possible, but I don't recommend trying to do it. If you really need what your asking for, something like this would work:

>>> exec(input("Enter name: ") + ' = {}')
Enter name: myDict
>>> myDict
{}
>>> locals()['myDict']
{}
>>>

However it is generally A bad idea to use exec() especially with a combination of input(). There is usually a better way to do something without it. In fact, there is a better way of doing it.

Instead of trying to create variables based upon user input, use a dictionary instead. This way, you have good control over your "variables". You could easily extend this to add more than one "variable" from user input to your variable dictionary:

>>> varDict = {}
>>> name = input("Enter name: ")
Enter name: myDict
>>> varDict[name] = {}
>>> varDict[name]
{}

You can dynamically create variables using a while loop, and input(). Create a dictionary to hold all your user inputted variables. Create a while loop, then ask the user for a variable name and value:

>>> varDict = {}
>>> while True:
name = input("Enter a variable name: ")
value = input("Enter a variable value: ")
varDict[name] = value

Enter a variable name: var1
Enter a variable value: a
Enter a variable name: var2
Enter a variable value: b
Enter a variable name: var3
Enter a variable value: c
Enter a variable name:
Traceback (most recent call last):
File "<pyshell#12>", line 2, in <module>
name = input("Enter a variable name: ")
KeyboardInterrupt
>>> varDict
{'var1': 'a', 'var2': 'b', 'var3': 'c'}
>>>

setting user input to variable name

You can use the dictionary returned by a call to globals():

input_name = raw_input("Enter variable name:") # User enters "orange"
globals()[input_name] = 4
print(orange)

If you don't want it defined as a global variable, you can use locals():

input_name = raw_input("Enter variable name:") # User enters "orange"
locals()[input_name] = 4
print(orange)

How to make a variable name dependant on input in python?

Instead of using multiple variables, you can use a dictionary. Using multiple variables is less Pythonic than using a dictionary and can prove cumbersome with large data. In your example, you could use a dictionary to store each worker and their number of points.
Documentation for dictionaries can be found here

For example:

#recieve a valid input for the number of workers
while True:
num = input("How many workers would you like to create?\n") # accepts an int
try:
num = int(num)
except ValueError:
print("Must input an integer")
else:
break

#create a dictionary with the workers and their scores (0 by default)
workers = {'worker'+str(i+1) : 0 for i in range(num)}

# get the user to choose a worker, and add 1 to their score
while True:
worker = input("Which worker would you like to add a point to?\n") #accepts worker e.g worker1 or worker5
if worker in workers:
workers[worker] += 1
print(f"Added one point to {worker}")
break
else:
print("That is not a worker")

print(workers)

This code gets a user input to create a certain number of workers. It then gets user input to add a point to one of the workers. You can change this to add multiple points to different workers, but this is just a basic example, and it depends on what you want to do with it.



Related Topics



Leave a reply



Submit