Python - User input for name of a variable to pass as an argument to a function

后端 未结 3 1368
轻奢々
轻奢々 2021-01-14 23:06

I have a question here which is based around user input to scripts and passing this user-input to functions.

I have a script, within which I have defined a function.

3条回答
  •  无人及你
    2021-01-15 00:02

    with raw_input the input is just a string

    table2 = range(3)
    variable_name = raw_input('Enter Variable Name: ')
    def function(list_object):
        print list_object
    
    function(globals()[variable_name])
    

    with input() the input data given by the user is evaluated, be sure that the all the possible input lists are declared before asking for user input, other wise you end up getting an NameError

    table2 = range(3)
    variable_name = input('Enter Variable Name: ')
    def function(list_object):
        print list_object
    
    function(variable_name)
    

    globals() function returns a dictionary of all the objects defined in the module. you can get the respective object by passing the variable name as a key.

提交回复
热议问题