Ritz Ganguly
Ritz Ganguly

Reputation: 361

Wrong comparison result for equal values in python

def fib_gen(fib=-1):
 print(f"initial fib={fib}")
 a = 1
 b = 0
 yield b
 i = 1
 print(f"initial i={i}")
 while(i!=fib):#infinite sequence by default, since default value of fib is -1
  c = a
  a = a+b
  b = c
  i = i+1
  print(f"i={i}")
  print(f"fib={fib}")
  print("is fib==i: ",fib==i)
  input("Continue? ")
  yield a

x = input("First how many fibonacci numbers do you want? ")
fibs = fib_gen(x)
print(f"x={x}")
try:
 while(True):
  print(next(fibs))
except:
 print(f"That's the first {x} fibonacci numbers")

Even when fib and i become equal, the result shows False. Why?

And if I pass a concrete value in the generator function instead of a variable, then the result comes as expected. Why???

Upvotes: 0

Views: 43

Answers (1)

user15888618
user15888618

Reputation:

input() returns a string by default, to get a number do int(input())

x = int(input("First how many fibonacci numbers do you want? "))

Upvotes: 1

Related Questions