0

For example, if you wanted to accept say 2 input values it would be something like,

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

Doing it this way however, would mean that I must have 2 inputs at all times, that is separated by a white space.

How do I make it so that a user could choose to enter any number of inputs, such as nothing (e.g. which leads to some message,asking them to try again), or 1 input value and have an action performed on it (e.g. simply printing it), or 2 (e.g. adding the 2 values together) or more.

Kyle
  • 69
  • 6

3 Answers3

1

You can set a parameter how many values there will be and loop the input and put them into a map - or you make it simple 2 liner:

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

this will create a map of INT values - separated by space.

LenglBoy
  • 1,451
  • 1
  • 10
  • 24
0

You may want to use a for loop to repeatedly get input from the user like so:

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)

Then, later on, you can use an if/elif/else chain to do different actions to the numbers based on the length of the list (found using the len() function).

For example:

if len(numbers) == 0:
  print("Try again") #Or whatever you want
elif len(numbers) == 1:
  print(numbers[0])
else:
  print(sum(numbers))
lyxαl
  • 1,108
  • 1
  • 16
  • 26
0

Try something like this. You will provide how many numbers you want to ask the user to input those many numbers.

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()
lyxαl
  • 1,108
  • 1
  • 16
  • 26
Subhrajyoti Das
  • 2,685
  • 3
  • 21
  • 36