[Tutor] Count for loops

Rafael Knuth rafael.knuth at gmail.com
Mon Apr 3 08:22:29 EDT 2017


I wrote a program which checks if PI (first one million digits)
contains a person's birth year.

file_path = "C:/Users/Rafael/PythonCode/PiDigits.txt"

with open (file_path) as a:
    b = a.read()

get_year = input("What year were you born? ")

for year in b:
    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. Can anyone help? Thanks!

file_path = "C:/Users/Rafael/PythonCode/PiDigits.txt"
with open(file_path) as a:
    b = a.read()

get_year = input("What year were you born? ")

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)
    print("Your birth date occurs %s times in PI!" % (sum_count))


More information about the Tutor mailing list