[Tutor] Counting iterations of a function
Neil Cerutti
neilc at norwich.edu
Thu Nov 30 14:42:01 EST 2017
On 2017-11-30, Michael Dowell <michael.dowell297 at gmail.com> 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.
>
> Program:
> #import modules
> import random
> import turtle
>
>
> #Give welcome message
> def print1():
>
> print("Hello!")
> print("Thank you for using this Magic 8-Ball Simulator.")
> print("We understand that you have a choice in magic 8-ball
> experiences,\n and that you have no choice in viewing mine.")
> print("Thank you")
>
> #Define main function
>
> def main():
> #Set local variables
> count=0 #Tried to intergrate count into main() function
> query=''
>
> #Get question
> query=str(input("Please type in your question(press 'Enter' to exit):"))
>
> while query!='':
> oracle()
> main()
> break
You are combining a while loop and a recursive call to main in a
redundant way. A while loop without the complication of the
function calling itself makes things easier. By the way, input
returns a string, so you don't need to call "str" on it.
query = input("Please type in your question(press 'Enter' to exit):")
while query!='':
oracle()
count += 1
query = input("Please type in your question(press 'Enter' to exit):"))
When the while loop is finally complete, count will be the number
of times oracle has run. In current Python, pushing the query
into a separate function is a good way to eliminate the verbatim
repetition of code.
def get_query():
return input("Please type in your question(press 'Enter' to exit):")
In main:
query = get_query()
while query!='':
oracle()
count += 1
query = get_query()
You can generalize function-call counting by writing a function
decorator that counts the number of times its function has run,
and then decorate oracle with it, but that pie is higher in the
sky than needed here.
--
Neil Cerutti
More information about the Tutor
mailing list