Python : Basic countdown timer & function() > int()

前端 未结 3 720
温柔的废话
温柔的废话 2021-01-26 03:04

I\'m trying to ucreate a timer function that runs in the background of my code and make it so I can use/check the time. What I mean by use/check, I\'m trying to make it so I can

相关标签:
3条回答
  • 2021-01-26 03:19
    import time
    
    def timer(tim):
        time.sleep(1)
        print tim
    
    def hall():
        tim = 15
        while (tim > 0):
            print 'do something'
            timer(tim)
            tim-=1
    

    Not the cleanest solution, but it will do what you need.

    0 讨论(0)
  • 2021-01-26 03:24

    The way you do it, you'll going to have to use multithread.

    Here is another, simpler approach : On your script beginning, set a time_start variable with the number of seconds since the epoch using time.time() Then when you need the number of elapsed seconds, use time.time() - time_start :

    t_start = time.time()
    # do whatever you'd like
    t_current = int(time.time()-t_start) # this way you get the number of seconds elapsed since start.
    

    You can put that in a function as well, defining t_start as a global variable.

    import time
    t_start = time.time()
    
    def timer():
        global t_start
        print(str(int(time.time()-t_start)))
    
    
    print('start')
    time.sleep(2)
    timer()
    time.sleep(3)
    timer()
    
    0 讨论(0)
  • 2021-01-26 03:42

    The problem with your code is that when you run hall(), Python first executes the whole of timer() (i.e. the whole for loop), and then moves on with the rest of the code (it can only do one thing at a time). Thus, by the time it reaches the while loop in hall(), timer is already 0.

    So, you're going to have to do something about that timer so that it counts down once, and then it moves on to the do something part.

    Something that you can do is this:

    def hall():
        for a in range(0, 15):
            print(15 - a)
            # do something
            time.sleep(1)
    

    This should work just fine (if you're only executing hall 15 times), and condenses your code to just one function.

    0 讨论(0)
提交回复
热议问题