[Tutor] Count for loops

Alan Gauld alan.gauld at yahoo.co.uk
Tue Apr 4 20:14:02 EDT 2017


On 04/04/17 12:04, Rafael Knuth wrote:
> Sarma: thank you so much, I checked your code, it works. However, can
> you enlighten me what it exactly does?

It just iterates over the PI string manually and compares
the birth date with the first 4 PI string characters.

It would probably be more pythonic and easier to read
to use startswith() instead

> count = 0
> b = "3"+b[2:]

I think this is to eliminate the period after the 3 of PI

> n = len(b)
> for i in range(n-3):
>     if b[i:i+4] == get_year:
>         count += 1

This is the core of it.
It starts with i = 0 and goes up to i = n-4
If b[i] to b[i+3] equals the birthdate you count
a match

You could rewrite it as

for i in range(n-3):
    if b.startswith(get_year, i):
       count += 1

HTH
-- 
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