• Python Mystery Powers Apr 4, 2005

    Posted by Mike Naberezny in Python

    Beginning Python programmers can be easily confused by the numeric operator for exponents. In many languages, the statement:

    print(2^2)
    

    Will return 4, or 2 raised to the power of 2. However, the ^ operator in Python has a completely different meaning. It actually returns the bitwise exclusive OR of the two numbers. For the example of 2^2, the number 0 will be returned instead of the expected 4.

    To express exponents in Python, use either:

    x = pow(a,b)
    x = a**b
    
  • Python Module “time” Apr 4, 2005

    Posted by Mike Naberezny in Python

    Python’s time module provides some very useful functions for working with time and dates.

    One useful function is sleep(), which pauses the program for a given number of seconds. I use this when I need to wait a fixed time period for physical events, such as a thermal soaking.

    The function time() returns the local time in the ever-useful number of seconds since the UNIX epoch. An interesting quirk is that accuracy of smaller than a second is available on some operating systems and this function will actually return with a floating-point number. Use Python’s int() if this is not desirable.

    The functions gmtime() and localtime() return the time in a 9-tuple which is somewhat unusual, however it can be handy for quickly extracting parts of the time. For example, time.localtime()[0] will return the four-digit year.