Learn EV3 Python‎ > ‎

Math & Time

You shouldn't be looking at this page! Math and time functions are part of standard Python, and you should have a good knowledge of standard Python before you use this site. There are many sites that can help you learn standard Python - this isn't one of them (though you will of course get lots of practice with standard Python functions as you use EV3 Python). This site is intended to help you step up from standard Python to EV3 Python.

However, in case you need a refresher, HERE is the official documentation for the math library and HERE is the official documentation for the time library.

Abs() and Round()
Unlike the other math functions mentioned further down the page, these two are built into the Python interpreter and are therefore always available, so you don't have to import the math library in order to be able to use these two functions. (You do need to import the math library before you use the other math functions described on this page.)

abs(x) returns the absolute value of a number. The argument may be an integer or a floating point number. Example:  print (abs(-34.6)) will print 34.6.

round(number) returns (as an integer) the integer nearest its input. 

round(number, ndigits) returns the floating point value number rounded to ndigits digits after the decimal point. Example:  print (round(2.78, 1)) will print 2.8. The return value is of the same type as number.

Division and Modulo
In addition to 'normal' division with '/', Python can do integer division with '//'. Integer division rounds the result down to the nearest integer. By rounding down, I mean rounding in the negative direction, which is not always the same as truncating the result. Rounding down is also called 'flooring'. See the script below.

Python also has a modulo operator '%' which, for positive numbers, gives the remainder. For example 15 % 4 = 3. Note that Python calculates modulo in a different way to C.

#!/usr/bin/env python3
from time import sleep

print(11/3)      # 3.6666666666666665
print(11//3)     # 3
print(-11//3)    # -4
print(11//-3)    # -4
print(11%3)      # 2
sleep(6) # give enough time for result to be read

Trigonometric functions
It's important to remember that Python trigonometric functions use radians, not degrees. One revolution = 2*pi radians. One radian = 57.3° approx. You can convert degrees to radians with math.radians(x) and radians to degrees with math.degrees(x). For example this will print the cosine of 45°:

#!/usr/bin/env python3

from time import sleep
import math

print (math.cos(math.radians(45)))
sleep(6) # give enough time for result to be read

Random Numbers
The random library must be imported before the random number functions can be used. In Python, random integers between a and inclusive can be generated with randint(a, b). For example, to generate a random integer between 0 and 6 inclusive, use randint(0,6)See an example of a script using randint() on this page.

A random float between 0 and 1 (greater than or equal to zero but always less than 1) can be generated with random().

This script will print a random integer between -100 and +100 and a random float between 0 and 1.

#!/usr/bin/env python3

from time import sleep
import random

print (random.randint(-100,100)
print (random.random())
sleep(6) # give enough time for result to be read in Brickman

For more help with Python random functions, click HERE or HERE.

If you want to measure how long it takes for some action to complete you may find the function time.time() to be useful. It returns the time as a floating point number expressed in seconds since the 'epoch'. The 'epoch' is some time in history which doesn't interest us because we would only be interested in changes in time. Don't forget to import the time library if you want to use this function.

The following example times how long it takes the user to add two random integers, and also indicates whether the answer was right or wrong. We must be careful not to write code that will 'crash' if a user enters an answer that is not an integer. The script below demonstrates a very good technique (using try: ... except ValueError: ... else: ... ) to validate user input, in this case checking that the user entered an integer. To learn more about validating user input click HERE. The script below probably can't be run from Brickman since it needs keyboard input, so the first and last lines are probably superfluous.

#!/usr/bin/env python3
from time import sleep, time
import random

# Get user input
while True:
        ans = int(input('What is '+str(int1)+ ' + ' + str(int2) + ' ? '))
    except ValueError:
        print("Sorry, I didn't understand that.")
        #better try again... Return to the start of the loop
        #input was successfully parsed so we can exit the loop
verdict=['wrong.', 'correct.'][ans==sum]
print('You took '+str(timetaken)+'s and your answer is '+verdict)
if verdict=='wrong.':
    print('The correct answer is '+str(sum)+'.')

sleep(5) # give enough time for result to be read in Brickman

The most interesting line may be the line highlighted in yellow. In that line a list is defined containing two text strings 'wrong.' and  'correct.'. One of these text strings will be copied into the variable verdict according to the index value [ans==sum]. If ans is equal to sum then this gives True which is considered equivalent to 1, so the text string with index 1 ('correct.') will be placed in verdict. If ans is not equal to sum then we have False which is equivalent to zero, so the text string with index 0 ('wrong.') will be placed in verdict

The time() function is also used in exercise 10 on this page.

Here again is the LINK to the official documentation for the time library.