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

后端 未结 3 1367
轻奢々
轻奢々 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-14 23:50

    I think you can take advantage of python's global() or locals() feature.

    here's an example:

    from random import choice as rc
    
    
    
    def your_function(variable):
        if variable in local_keys:
            print(variable, " = ", local_variables[variable])
        else:
            print("Your input is not a defined variable")
        return
    
    #randomly populate the variables
    item1 = rc(range(20))
    item2 = rc(range(20))
    item3 = rc(range(20))
    item4 = rc(range(20)) 
    item5 = rc(range(20))
    item5 = rc(range(20))
    
    user_variable = input("Input the variable name: ")
    
    local_variables = locals() # you may have to use globals instead
    local_keys = list(local_variables.keys())
    
    your_function(user_variable)
    

提交回复
热议问题