Advertisement

time in loop

Started by July 04, 2018 10:31 AM
4 comments, last by WinterDragon 6 years, 5 months ago

I'm trying to find/figure out where in a loop, before the loop, after the loop, the computer understands time.

As I have created a loop and I need to put a time-limit on an input.

lost my program, so I'll adapt the following to a guessing game from a coin flip. Then I need to insert a time counter, just need to understand where to put it?

 

import random
def variables ():
    heads = 0
    tails = 0
    coinCount = 0
    againPlay = "y"
   
def game():
    heads = 0
    tails = 0
    againPlay = "y"
    coinCount = 1
    while coinCount > 0:
        if againPlay != "y":
            print ("you had ", heads, "heads.")
            print (" and ", tails, "tails.")
            end = input ("You're all done now!")
        nmCoin = random.randrange(2)
        if coinCount > 100: againPlay = "n"
        if nmCoin == 1:
           heads = heads + 1
           coinCount = coinCount + 1
        elif nmCoin == 0:
           tails = tails + 1
           coinCount = coinCount + 1
        else:
            print ("you had ", heads, "heads.")
            print (" and ", tails, "tails.")
            end = input ("You're all done now!")
    
variables ()
game ()
 

http://polydina.com

To use time, you have to import it


import time

print(time.time())  # Time in seconds since epoch (January 1st, 1970), so it's a huuuge number
print(time.localtime(time.time()))  # Print the number as somewhat readable timestamp

#Measuring time:
before_time = time.time() # Save the time at this point

# Do something, eg input
input("give a value!")

after_time = time.time() # Save the time again (should be later now)

# Compute the difference, which is the amount of time between both saves.
print("You took {} seconds to answer".format(after_time - before_time))

The 'time' module has more functionality, read the documentation on the module. (It's always useful what Python can do for you.)

 

While you cannot abort the 'input' statement when time runs out (the user must always give an answer), you can afterwards conclude if the user was fast enough.

Advertisement

thanks that's hugely helpful! :) the book hasn't covered the time module yet so I didn't know there was one but the assignment kind of requires it. Which is a bit strange, but it's the last assignment for this section so it may be a curve ball. Is there documentation on all the modules in python, if so, I'm assuming it's pretty massive? Could I combine time with a while statement, to keep the game going until time reaches required time state?

http://polydina.com

There is loads of documentation written for Python, I use it every day. A short summary:

Main entry point is https://docs.python.org/3/, bookmark it :)  It always points to the newest version that exist, but you can select the version that you actually have. Also, in the documentation it is usually mentioned that some function or so "was added in Python 3.x" if it was added later.

The 'Tutorial' is a tutorial, but one for people that can already program. Also, it treats most if not all features of the language (haven't read it for a long time, so ymmv), including the more advanced ones. Very useful to read once you have the basics done, as you will find new wonderful features that come in handy sometimes.

The 'Library reference' is exactly that, it lists all modules that come with Python, that you can just import, such as time. It lists all functionality that a module has, often with a load of examples, but there are also more densely documented modules, that you may not immediately understand. The table of contents is organized on topic, so you can find easily all related modules in some area that you are looking for.

The 'Language Reference' is about the Python language itself. It's the precise description of the language, including all details how it works. It's useful if you need to know precisely how it works. Likely you will find it difficult to read, as it's dense material.

The 'Python setup and usage', I have no clue whatsoever.

The 'Python Howtos' is more of a guide on some areas, describing what is available, and how to do things in practice. Don't look there often, but can be useful at times.

The 'Installing Python Modules' is about installing (non-standard) Python modules. There are a few zillion Python modules out there at the Internet. If you think "he, this looks useful enough to make a module for", it's a safe bet that someone has already done that and put it at the Internet.

The 'Distributing Python Modules' is the other side, you wrote a module, how to publish it?

The 'Extending and embedding' is about connecting Python to C and vice versa. Only useful if you also know C/C++ and want to call C from Python code or Python from C code. The 'Python/C' API is like the library reference for it.

The 'FAQ' has questions with answers obviously, no idea what, though.

 

With 'Indices and tables':

The 'Module Index' is the #1 goto page for accessing the module documentation. You can also find a link at the top-right of the page.

The 'Index' basically contains all Python words, I sometimes look there, but I use the search box at the top much more often.

 

So there you have it, enough for a few holidays reading material :)

 

Quote

Could I combine time with a while statement, to keep the game going until time reaches required time state?

Not with input, as it blocks until you hit 'enter'. You can do it in the console terminal if you really insist, but it's not that simple in Python, as it's close to the operating system.

It becomes much easier if you switch to eg pygame, where you get events when the keyboard is used automatically, so I think the simpler solution is to accept now that you cannot abort until 'enter' is pressed, and revisit this problem when you're in the event based world of many graphical programming systems.

Thanks, that is immensely helpful, lots to read, yay. But seriously, thanks a lot, :).

http://polydina.com

This topic is closed to new replies.

Advertisement