How to get multiple inputs Python

前端 未结 2 360
忘掉有多难
忘掉有多难 2021-01-16 21:43

I\'m writing a program in Python where I would like to do the following: I ask for a certain input by writing

x = int(input())

Now, given t

2条回答
  •  生来不讨喜
    2021-01-16 22:01

    I'd recommend to follow previous answer, but if you care about giving meaningful names to the user's inputs you can do the following:

    import sys
    current_module = sys.modules[__name__] # you will have an access to module instance
    print("Define number of further inputs:")
    no = input()
    for x in range(int(no)):
        print("Input value: ")
        _var = input()
        setattr(this_module, 'var_%s' % _var, _var)
    

    After that, you can access those variables through the next code:

    globals()[name_of_the_variable]
    

    where name_of_the_variable is 'var_' plus user's input value, for example

    Define number of further inputs: 5
    
    var_5 = globals()['var_5']
    

    Hope that would help you.

提交回复
热议问题