Reputation: 527
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
n =[]
????
//This loop is for calling fibi function and printing its output on each diff line
for i in n:
print (fibi(n[i]))
1
2
3
4
5
.
.
.
n
1
1
2
3
5
Upvotes: 8
Views: 57506
Reputation: 178
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
Upvotes: 0
Reputation: 61
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
Upvotes: 2
Reputation: 49
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)
Upvotes: 0
Reputation: 1
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)
Upvotes: 0
Reputation: 11
l=[]
while(True):
try:
a=input()
except Exception as e:
break
l.append(int(a))
print(*l)
Upvotes: 0
Reputation: 988
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])
Upvotes: 8
Reputation: 131
from sys import stdin
lines = stdin.read().splitlines()
print(lines)
INPUT
0
1
5
12
22
1424
..
...
OUTPUT
['0', '1', '5', '12', '22', '1424' .. ...]
Upvotes: 3
Reputation: 236
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.
Upvotes: 0