如何让用户在Python中输入任意数量的输入值?

时间:2018-03-22 06:38:26

标签: python python-3.x

例如,如果你想接受2个输入值,那就像是,

x = 0
y = 0
line = input()
x, y = line.split(" ")
x = int(x)
y = int(y)
print(x+y) 

然而,这样做意味着我必须始终有2个输入,用空格分隔。

我如何制作它以便用户可以选择输入任意数量的输入,例如什么都没有(例如,这会导致某些消息,要求他们再试一次),或者输入1个输入值并对其执行操作(例如,简单地打印它),或2(例如,将2个值加在一起)或更多。

3 个答案:

答案 0 :(得分:1)

您可以设置一个参数将有多少个值并循环输入并将它们放入地图中 - 或者您将其简化为2个衬垫:

numbers = input("Input values (space separator): ")
xValueMap = list(map(int, numbers.split()))

这将创建一个INT值的地图 - 以空格分隔。

答案 1 :(得分:0)

您可能希望使用for循环重复获取用户的输入,如下所示:

num_times = int(input("How many numbers do you want to enter? "))
numbers = list() #Store all the numbers (just in case you want to use them later)
for i in range(num_times):
  temp_num = int(input("Enter number " + str(i) + ": "))
  numbers.append(temp_num)

然后,稍后,您可以使用if/elif/else链根据列表的长度(使用len()函数找到)对数字执行不同的操作。

例如:

if len(numbers) == 0:
  print("Try again") #Or whatever you want
elif len(numbers) == 1:
  print(numbers[0])
else:
  print(sum(numbers))

答案 2 :(得分:0)

尝试这样的事情。您将提供要让用户输入这么多数字的数字。

def get_input_count():
  count_of_inputs = input("What is the number you want to count? ")
  if int(count_of_inputs.strip()) == 0:
      print('You cannot have 0 as input. Please provide a non zero input.')
      get_input_count()
  else:
      get_input_and_count(int(count_of_inputs.strip()))

def get_input_and_count(count):
  total_sum = 0
  for i in range(1,count+1):
      input_number = input("Enter number - %s :"%i)
      total_sum += int(input_number.strip())

  print('Final Sum is : %s'%total_sum)

get_input_count()
相关问题