Professional Documents
Culture Documents
Lab#3
Lab#3
We can do many interesting things with variables. If we want to use mathematical functions, we
need to import them first (as done below):
We will import functions from modules as we need them. Here is a list of other commonly used
function which have to be imported from the math module
Function returns
A function needs to be imported only once in a session or in a program. If one wants to import
all functions in the math module, write from math import *
Start a new interpreter session to see what happens if one forgets to import a function used:
>>> sqrt(44)
>>> x = 3.14
>>>y = sin ( x )
>>> print ( y )
>>> x = 3.14
>>> y = sin ( x )
>>>print ( y )
>>> y = cos ( x )
>>> print ( y )
I
>>>import math
>>> x = 3.14
>>> y = math . sin ( x )
>>>print ( y )
>>> math.sqrt(5)
>>> math.trunc(4.5)
>>> math.ceil(4.5)
>>> math.log(1024,2)
>>> math.pi
>>>import math as mt
>>>x = 3.14
>>>y = mt . sin ( x )
>>> print ( y )
We can get an explanation of what functions and variables are provided in a module using
the help function
>>>import math
>>>help(math)
>>> a = 2
>>> b = 5
>>> x = 3
>>> y = a*x + b
>>> print ( y )
The following program reads radius and height of a cylinder and outputs its area and volume.
Code:
import math
Exercise:
Write a Python program that computes the area of a circle. Your program should use
the math module. Also, take the value of radius(r) from user. Remember, the formula is
area = πr2
import math
area = math.pi*radius**2
In addition to arithmetic expressions, the programs we write will use Boolean expressions. These
are expressions with only two possible values, True or False. Below are some examples.
Note that in Python equal (=) is written as == and not equal (≠) is written as !=.
>>> 10<100
True
>>> 100<100
False
>>> 100<=100
True
>>> 100==100
True
>>> 100!=100
False
We can also join two Boolean expressions together using and, or operations.
>>> a = 10
>>> b = 6
>>> a>0 and b<100
True
>>> a>0 and b<5
False
>>> (a==0) or (a==10)
True
>>> (b==0) or (b==10)
False
Exercises
In the interpreter window, set myage = 17, driving = 16, drinking = 21.
What do the following statements produce?
1.>>> myage < 17