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


this question has answer here:

i want take input string user in python3 . example : abc input string . want create dictionary insider program "abc" name.is possible?

it's possible, don't recommend trying it. if need asking for, work:

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

however a bad idea use exec() combination of input(). there better way without it. in fact, there better way of doing it.

instead of trying create variables based upon user input, use dictionary instead. way, have control on "variables". extend add more 1 "variable" user input variable dictionary:

>>> vardict = {} >>> name = input("enter name: ") enter name: mydict >>> vardict[name] = {} >>> vardict[name] {} 

you can dynamically create variables using while loop, , input(). create dictionary hold user inputted variables. create while loop, ask user variable name , value:

>>> vardict = {} >>> while true:         name = input("enter variable name: ")         value = input("enter variable value: ")         vardict[name] = value   enter variable name: var1 enter variable value: enter variable name: var2 enter variable value: b enter variable name: var3 enter variable value: c enter variable name:  traceback (most recent call last):   file "<pyshell#12>", line 2, in <module>     name = input("enter variable name: ") keyboardinterrupt >>> vardict {'var1': 'a', 'var2': 'b', 'var3': 'c'} >>>  

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -