-1
Ai=([int(x) for x in input().split()])   

Using the above-mentioned statement I want to take make a list from the string input by the user.

I want to limit the number of entries the user makes. Suppose the use gives an entry with 5 numbers separated by blank space. After splitting I get 5 different numbers but I wanted to restrict the input to just 4 numbers. How do I achieve this using the above-mentioned statement? If not then how do I take different numeral inputs (suppose 4) in a single line in python?

  • 2
    Please provide the output expected and also some code snippet which you have already worked on. – Stan11 Dec 16 '20 at 11:39
  • If you want to limit input, a comprehension is likely the wrong way to do it. You're better off with traditional control structures like a while loop with an if statement. – mikebabcock Dec 16 '20 at 16:28

1 Answers1

0

You have multiple options to do it. If you do it like this: Ai = ([int(x) for x in input().split()[:4]]) you will only take the first 4 numbers of your input, even if the user types in more numbers. However, this will give you an error if the user types in less than 4 numbers. Also, if the user types in something else than numbers, the int conversion will give you an error.

A better way to do this would be to validate the input before your list comprehension using regex and only accept it if it's compliant with your desired format. This pattern matches any string that contains between 1 and 4 numbers seperated by spaces, but will not match stings with more than 4 numbers or with letters.

This code will ask you for user input in an infinite loop and check if the user input matches the format that you want. If not, it asks again for input. If a match is found, the loop ends and you list comprehension gets executed.

import re

pattern = re.compile(r'^(?: ?\d+ ?){1,4}$')

while True:
    user_input = input('Please enter up to four numbers seperated by spaces: ')
    if pattern.search(user_input):
        break
    else:
        print('Invalid input, try again!')

Ai = ([int(x) for x in user_input.split()])
sunnytown
  • 1,844
  • 1
  • 6
  • 13