-2

am trying to take input from user forcefully and execute it in Fibonacci elements program, having problem near input i want to make sure that he doesn't enter character nor -ve number, when i take my input as int(input()) my while loop wont execute i want it to keep executing until user provides input.

in below program when i entered 5 as input it taking it as string object

n=input("enter no of fibonnaci elements: ")
while not n:
    n=input("enter no of fibonnac elements: ")
print(type(n))
if(n!=int()):
    print("enter integer only")
else:
    t1=0
    t2=1
    print("series is:",end=" ")
    for i in range(n):
        print(t1,end=" ")
        t1,t2=t2,(t1+t2)
print()
GOku San
  • 3
  • 3
  • Input takes *everything* as string object – jonrsharpe Dec 29 '18 at 09:47
  • i tried int(input()) but my while loop won't execute for integers, i want to repeat that loop until user give some input when i tried int(input()) it throws me error.. – GOku San Dec 29 '18 at 09:51

1 Answers1

1

You can use isinstance(n,int)to check if it is an int. But if you use int(input("enter no of fibonnaci elements:"))then it will throw a ValueError before it.

n=int(input("enter no of fibonnaci elements: ")) #convert to int here
while not n: #will not enter this loop - why is it even here?
    n=input("enter no of fibonnac elements: ")
if(not isinstance(n,int)): #Note: won't Reach this line - Will throw an error before this
    print("enter integer only")
else:
    t1=0
    t2=1
    print("series is:",end=" ")
    for i in range(n):
        print(t1,end=" ")
        t1,t2=t2,(t1+t2)
print()

A better way to do this

while True:
    try:
        n=int(input("enter no of fibonnaci elements: "))#convert to int here
        break
    except ValueError:
        print("enter integer only")
t1=0
t2=1
print("series is:",end=" ")
for i in range(n):
    print(t1,end=" ")
    t1,t2=t2,(t1+t2)
print()

Output

enter no of fibonnaci elements: str
enter integer only
enter no of fibonnaci elements: 6
series is: 0 1 1 2 3 5
Bitto
  • 7,937
  • 1
  • 16
  • 38