Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take any number of inputs in python without defining any limit?

Now, the thing is that I am supposed to take an unknown amount of input from the user like on one run he can enter 10 terms on another run he can enter 40. And I cannot ask user initially to enter the value of n so that I can run a range loop and start storing the input in list. If somehow I can do this then for that I have created the loop but that is not the case. So, the question is how to define the endpoint for user? or how to pass unknown number of arguments to the function?

def fibi(n):
    while n<0 or n>=50:
        print "Enter value of n greater than 0 but less than 50"
        n = int(raw_input())
    if n==0:
        return n
    else:
        a, b = 0, 1
        for i in range(n):
            a, b = b, a + b
    return a

main calling function starts

n =[]
????
//This loop is for calling fibi function and printing its output on each diff line
for i in n:
    print (fibi(n[i]))

Sample Input:each entry should be on a new line

1
2
3
4
5
.
.
.
n

Sample Output

1
1
2
3
5
like image 320
Arpit Agarwal Avatar asked Jul 23 '15 16:07

Arpit Agarwal


People also ask

How do you take many inputs from a user in Python?

Using split() Method The split() method is useful for getting multiple inputs from users. The syntax is given below. The separator parameter breaks the input by the specified separator. By default, whitespace is the specified separator.

How do you collect multiple inputs in Python?

Using Split () Function With the help of the split () function, developers can easily collect multiple inputs in Python from the user and assign all the inputs to the respective variables. Developers can specify a character that will be used as a separator to break the input provided by the user.


2 Answers

This is how to read many integer inputs from user:

inputs = []
while True:
    inp = raw_input()
    if inp == "":
        break
    inputs.append(int(inp))

If you want to pass unknow number of arguments to function, you can use *args:

def function(*args):
    print args
function(1, 2, 3)

This would print (1, 2, 3).

Or you can just use list for that purpose:

def function(numbers):
    ...
function([1, 2, 3])
like image 109
Hannes Karppila Avatar answered Sep 22 '22 12:09

Hannes Karppila


from sys import stdin 
lines = stdin.read().splitlines()
print(lines)

INPUT

0
1
5
12
22
1424
..
...

OUTPUT

['0', '1', '5', '12', '22', '1424' .. ...]
like image 29
Arpitt Desai Avatar answered Sep 24 '22 12:09

Arpitt Desai