[Tutor] Count for loops

Alan Gauld alan.gauld at yahoo.co.uk
Mon Apr 3 10:52:20 EDT 2017


On 03/04/17 13:22, Rafael Knuth wrote:

> with open (file_path) as a:
>     b = a.read()
> 
> get_year = input("What year were you born? ")
> 
> for year in b:

Can you explain what you think this loop line is doing?
I'm pretty sure it's not doing what you expect.

>     if get_year in b:
>         print("Your year of birth occurs in PI!")
>         break
>     else:
>         print("Your year of birth does not occur in PI.")
>         break
> 
> As a next challenge, I wanted to check how often a person's birth year
> occurs in PI. Unfortunately, I wasn't able to figure out how to use
> the loop count properly. 

What loop count?
There is none, its a for loop, no counter needed.
(OK I just spotted your code below...)

But there is a count() method on a string object that should help.


> count = 0
> for year in b:
>     if get_year in b:
>         count += 1
>     else:
>         print("Your birth date does not occur in PI.")
>         break

>     sum_count = sum(count)

sum() sums a sequence, but count is an integer. You have been
incrementing it as you go, the final value is already there.

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