How to get multiple inputs Python

送分小仙女□ 提交于 2019-12-01 13:07:23

问题


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 the number 'N' I assign to this input, I would to then get N lines asking for new input. For example, if I give as input the number 3, I would like the program to ask for 3 new inputs and assign them to certain letters:

x = int(input())
3

Then

a = input()
b = input()
c = input()

Any idea on how to do this?


回答1:


Assigning them to certain variables with an unknown amount of inputs is not something you want. What you can do is make a list with the inputs:

x = int(input()) # the amount of numbers
input_list = []
for i in range(x):
    input_list.append(input())
print input_list

Now you can index the input_list to get the n-th input:

print input_list[0]

This will return the first input as the indexing in Python starts from 0




回答2:


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.



来源:https://stackoverflow.com/questions/37456391/how-to-get-multiple-inputs-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!