-2

I am writing a program in Python 2.7.6 that calculates the Fibonacci Sequence(1,1,2,3,5,8,etc.). This is the code(so far):

x = int(input("Enter a number: "))
y = int(input("Enter the number that comes before it:"))
z = x + y
a = z + x
b = a + z
c = b + a
d = c + b
e = d + c
f = e + d
g = f + e
print x, z, a, b, c, d, e, f, g

Is there a way I can loop the process so that I don't have to keep typing f=e+d and others?

Braden Parks
  • 51
  • 1
  • 10

2 Answers2

1

Sure, just use some form of loop. For example, if you want to make a list of the first 11 Fibonacci numbers after x:

fiblist = [x]
for _ in range(10):
    z = x + y
    fiblist.append(z)
    x, y = z, x
print(fiblist)

(or use a loop instead of the single print to vary the output's cosmetics -- not relevant to your core Q).

For different purposes (e.g "list all numbers in the sequence until the first one above 100") you could easily tweak the loop (e.g in lieu of the for use while x <= 100:).

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 1
    I think you should not encourage help vampiring, but whatever. – Stefano Sanfilippo Feb 27 '15 at 23:45
  • @StefanoSanfilippo, since clearly the OP doesn't understand how to use a loop in this example, what's wrong with teaching by example? The Q seems to respect all criteria listed in SO's FAQ -- it does show what code the OP's using, and what the problem is ("have to keep typing"). – Alex Martelli Feb 27 '15 at 23:49
  • How would I make to where I could make the input value the range value? @aruisdante – Braden Parks Feb 28 '15 at 00:01
  • @BradenParks, sorry but I'm not sure I can make head or tails of this comment/question. Of course you can use the same `int(input(...))` idiom to assign a third variable `numfibs` and then use `for _ in range(numfibs):` -- is **that** what you're asking about? – Alex Martelli Feb 28 '15 at 05:05
1

You can write a loop or just use the built-in reduce function in Python.

    fib = lambda n: reduce(lambda x, y: x+[x[-1]+x[-2]],range(n-2), [0, 1])
Amrita Sawant
  • 10,403
  • 4
  • 22
  • 26