计数函数调用python

时间:2014-09-30 11:17:43

标签: python function random count numbers

计算函数调用次数的最佳方法是什么,如果调用它五次,程序将停止?

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

4 个答案:

答案 0 :(得分:1)

你应该避免你的循环中的函数,只是循环,直到用户有五个guesses或在循环中断,如果他们猜测正确。:

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" 

或者只在允许的猜测范围内使用range

    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"

答案 1 :(得分:1)

不是一个完整的答案,但如果你想监控功能,你可能想查看sys.settrace。这可能会更高级

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

答案 2 :(得分:0)

作为维护全局(eww)字典的装饰器怎么样?每个函数都是一个键(完全限定名称),该值是该函数的最大调用次数。每次执行封闭的函数时,它都会检查值!= 0,执行函数并减少计数。

如果你只需要一个函数,那么一个不那么通用的装饰器可以使用全局var而不是dict,并且check-execute-decrement这个值如上所述。

答案 3 :(得分:0)

我认为你可以数到一定的数字,然后向Catch提出一个例外。