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

8

8

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
Abagail answered 23/7, 2015 at 16:34 Comment(5)
*args and **kwargs pythontips.com/2013/08/04/args-and-kwargs-in-python-explainedAphesis
couldn't you just ask after every input, if there is more input the user wants to give?Basenji
Normally, in these cases you either ask the user after every input if there are more inputs, or you define a special input that marks the end of the list.Behemoth
@JulianBerger For many inputs, this might get tedious; I'd recommend quitting the loop on a special char or none input.Statutory
It is usually best to specify these arguments on the command line rather than asking the user for new ones on every iteration. For example, python myprog.py 1 2 3 4 5 6 7 much cleaner than questions embedded in the output. Then you can use the other sys.argv comments here.Gerontocracy
R
8

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])
Rabah answered 23/7, 2015 at 16:49 Comment(4)
@hannes-karppila : It works really well, but you are missing something on first block of code ===> where it reads "inputs.append(int())" it should be inputs.append(int(inp))Brachy
How to do this in python3?Laborsaving
@Tojrah replace raw_input with inputRabah
I did the same thing but I got RunTime ErrorVoodoo
S
3
from sys import stdin 
lines = stdin.read().splitlines()
print(lines)

INPUT

0
1
5
12
22
1424
..
...

OUTPUT

['0', '1', '5', '12', '22', '1424' .. ...]
Starveling answered 7/10, 2018 at 17:58 Comment(1)
Please explain your answer to help others, now and in the future, to understand how and why your code works.Glassworks
S
2

In most cases, the error thrown is "EOFError : EOF while reading a line"

If we handle this error, our job is done!

while True:
    try:
        var = input()
        # do your task 

    except EOF as e:
        pass
Stewardess answered 26/10, 2021 at 7:41 Comment(1)
It's a bad practice to pass an exceptionHeadword
W
0

I am guessing that n is a list passed as command line arguments, if so then you can try doing

import sys

noOfArgs = len(sys.argv)
n = sys.argv

Here is a link that shows how to parse command line arguments.

Whall answered 23/7, 2015 at 16:47 Comment(0)
M
0
l=[]
while(True):
        try:
            a=input()
        except Exception as e:
            break
        l.append(int(a))
print(*l)
Megavolt answered 10/12, 2019 at 18:19 Comment(0)
R
0

I am guessing this is what you were looking for

inputs = []
while True:
    sval = input("Enter a number: ")
    if sval == 'done' :
        break
    try:
        fval = float(sval)
    except:
        print('Invalid input')
        continue
    try:
        inputs.append(int(sval))
    except:
        inputs.append(float(sval))
print(inputs)
Resee answered 21/7, 2020 at 13:51 Comment(0)
D
0

argv is a list of inputs passed to the script. the first argument argv[1] is the name of your script. what comes after that can be considered as passed arguments to the script. you can simply use the script below to get the inputs and store them in a list.

import sys
inputs = []
for item in sys.argv[1:]:
    inputs.append(item)
print(inputs)

Disseise answered 9/8, 2021 at 2:19 Comment(0)
L
0

I think the best way to handle this problem is by using error handling i.e try and except block please refer to the code below.

while True:
try:
    n = input()
    
    # Your Logic or code
    
except:
    break
Lukas answered 31/12, 2021 at 14:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.