简体   繁体   中英

Counting function calls python

What would be the best way to count how many times the function is called so that if it is called five times, the program will stop?

from random import randint
from functools import wraps
randNum = randint(1,100)



userGuess = int(input('Please guess a number between 0 and 100: '))
yesNo = 'y'
while yesNo == 'y':
    while randNum != userGuess:
        def numCheck(userGuess):
            if userGuess == randNum:
               return('Well done!')
            elif userGuess > randNum:
                return('Too high!')
            else:
                return('Too low!')

        def tryAgain(numCheck):
            if numCheck == 'Well done!':
                return(numCheck(userGuess))
            else:
                return('Try again')

        print(numCheck(userGuess))
        print(tryAgain(numCheck))

        userGuess = int(input('Please guess a number between 0 and 100: '))

    yesNo = str(input('Continue? Y/N: ')).lower()

You should avoid the functions inside your loop, just loop until the user has had five guesses or break in the loop if they guess correct.:

def main():
    randNum = randint(1,100)
    count = 0
    while count < 5:
        userGuess = int(input('Please guess a number between 0 and 100: '))
        if userGuess == randNum:
           print('Well done!')
           break
        elif userGuess > randNum:
            print('Too high!')
        else:
            print('Too low!')
        count += 1
    yesNo = input('Continue? Y/N: ').lower() # ask user to play again
    if yesNo == "y": 
        main() # restart the function if the user enters y 
    else: 
        return "Game Over" 

Or just use range in range of the number of guesses allowed:

    for guess in range(5):
            userGuess = int(input('Please guess a number between 0 and 100: '))
            if userGuess == randNum:
               print('Well done!')
               break
            elif userGuess > randNum:
                print('Too high!')
            else:
                print('Too low!')
    yesNo = input('Continue? Y/N: ').lower()
    if yesNo == "y":
        main()
    else:
        return "Game Over"

not quite a full answer, but you probably want to check out sys.settrace if you want to monitor functions. This might be a little more advanced

>>> import sys
# start by defining a method which we will track later
>>> def blah():
...   print('blah')
... 
# we make a set of functions, such to avoid the "under the hood" functions
>>> functions = set(['blah'])
# define what we want to do on the function call
>>> def tracefunc(frame, event, args):
      # if the event is a function being called, and the function name is on our set of functions
...   if event == 'call' and frame.f_code.co_name in functions:
...     print('function called! <function {}>'.format(frame.f_code.co_name))
... 
# set our trace to the function we described above
>>> sys.settrace(tracefunc)
>>> blah()
function called! <function blah>
blah

How about as a decorator that maintains a global (eww) dict? Each function is a key (fully qualified name) and the value is the maximum number of calls to that function. Each time it executes the enclosed function, it checks that the value != 0, executes the function and decrements the count.

If you need it for just one function, a less generic decorator could use a global var instead of a dict, and check-execute-decrement that value as above.

我认为您可以指望一定数量,然后提出Catch例外。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM