[Tutor] Counting iterations of a function

Steven D'Aprano steve at pearwood.info
Fri Dec 1 18:18:12 EST 2017

On Thu, Nov 30, 2017 at 10:26:20AM -0600, Michael Dowell wrote:

> Hello, I'm trying to code a magic 8-ball program and it needs to include a
> counter for the number of questions asked. I'm having a hard time
> implementing a count, and need a little help. I had tried to implement it
> in the main() function, but that (naturally) led it to only counting '1'
> for each question, for each question asked. Is there a way to count how
> many times a give line of code is executed? For instance, every time the
> oracle() function is run, a counter goes up. Thanks for any help.

I haven't even looked at your code, but the obvious way to count the 
number of times a specific function is called is to have a separate 
counter for that function and have the function increment it. FOr 

oracle_count = 0

def oracle():
    global oracle_count
    oracle_count += 1

Will that solve your problem?


More information about the Tutor mailing list