i am new python and need to know how to print one of theis list by typing a or b or c, i tried useing if condtions and it's working but what if i have 100 of theis lists is there a better way thanks.
letters = input("Select a letter ")
a = ["aaaa","aaaa","aaaa","aaaa",]
b = ["bbbb","bbbb","bbbb","bbbb",]
c = ["CCCC","CCCC","CCCC","CCCC",]
if letters == "a":
print(a)
elif letters == "b":
print(b)
elif letters == "c":
print(c)
else:
print("wrong input")
CodePudding user response:
The easiest way is to call eval.
print(eval("a"))
print(eval(letters)) # beware
However, one must never directly evaluate any raw input obtained from a user since they can then enter a command that would make the program do something arbitrary, like bypass restrictions, steal data or wipe your files. User input must always be processed or vetted fully:
if letters in ["a", "b", "c"]:
print(eval(letters)) # safe
else:
print("wrong input")
Another way to do it is to use the built-in function locals(). It returns a dictionary of all variables and values accessible within the local scope.
if letters in ["a", "b", "c"]:
print(locals()[letters])
