Home > Back-end >  How to set only n number of inputs for input().split() in python?
How to set only n number of inputs for input().split() in python?

Time:07-23

Problem : 1.The first line contains an integer n, denoting the number of elements in the tuple. 2.The second line contains n space-separated integers describing the elements in tuple.

Sample Input(correct):

2 
3 6 

sample input(wrong):

2
3 6 8  

Example:

n=int(input())  #denotes number of elements should be in a tuple 
integer_list = tuple(map(int, input().split()))  # how to modify this line to take only n space separated inputs

#suppose if n=2 in first line then 
#In second line I need only 2 space-separated inputs(since n=2) i.e 3 9(or any two),
 but not more than or less than n numbers. 
  **For Example**:5 7 3(which is >n) or 5(which is <n))

CodePudding user response:

The following code works, but I do not think it's possible to create the tuple in one line:

def main():
    n = 0
    while True:
        try:
            n = int(input())
        except ValueError:
            print("Wrong type entered (must enter integer number). Enter again: ")
            continue
        else:
            break
    if n == 0:
        return -1
    integer_list = []
    string_input = input()
    count = 0
    for i in string_input.split():
        if count == n:
            break
        x = 0
        try:
            x = int(i)
        except ValueError:
            return -1
        else:
            integer_list.append(x)
            count  = 1
    if count != n:
        return -1
    integer_tuple = tuple(integer_list)
    print(f"The tuple: {integer_tuple}")
    return 0


if __name__ == "__main__":
    main()

It will ask the user again and again for an integer if they have not entered one (as the first input), and then only creates a tuple if n subsequent space-separated integer numbers are entered (not less than n or more than n, and not if there is an invalid input).

Hope this helps.

CodePudding user response:

Instead of input(), define your own function that checks for the condition, and raise exception if condition failed.

Example:

def get_input(n):
    string_splits=input().split(' ')
    if len(string_splits)!=n:
        raise Exception("Invalid input")
    return string_splits

n=int(input()) 
integer_list = tuple(map(int, get_input(n))

  • Related