[Tutor] Python Help (shits killing me)

Alan Gauld alan.gauld at yahoo.co.uk
Fri Oct 26 06:21:31 EDT 2018


Plain text is preferred for code since otherwise the mail
system removes all indentation making the code hard to understand.

On 25/10/2018 23:13, Ben Placella wrote:
> So I have to make a fibonacci sequence, and I'm not sure what is wrong with
> my code
> #This program illustrates the fibonacci sequence
> nterms=int(input("Please enter how many terms you would like to know: "))
> n1 = 1
> n2 = 1
> count = 0
> if nterms <= 0:
> print("Please enter a positive integer")
> elif nterms == 1:
> print("Fibonacci sequence upto",nterms,":")
> print(n1)
> else:
> print("Fibonacci sequence upto",nterms,":")
> while count < nterms:
> print(n1,end=' , ')
> nth = n1 + n

I suspect that n should be n2?

> n1 = n2
> n2 = nth

BTW in Python you can do that set of assignments more
concisely as

n1,n2 = n2, n1+n2

with no temporary variable required.

> count += 1

And rather than using a while loop and manually
maintaining a count you could just use a for loop:

for count in range(nterms):

It's slightly more reliable and a lot more "pythonic".

> attached is a photo of what the output SHOULD look like

This is a text only list so images or other binary files
are stripped off by the server. Please, in future,
cut n' paste any output into the mail body.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list