0% found this document useful (0 votes)
130 views5 pages

SEE1002 Introduction To Computing For Energy and Environment

This document introduces useful Python modules including math, random, time, and ipywidgets. It provides examples of importing and using functions from these modules. It also assigns exercises for readers to practice using the modules, such as verifying trigonometric identities using math, testing the random number generator, playing rock-paper-scissors with random, creating an infinite loop that prints integers with delays using time, and building interactive widgets using ipywidgets. Finally, it demonstrates how to create your own module with defined functions that can be imported and used in other programs.

Uploaded by

Ming Lim Chan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
130 views5 pages

SEE1002 Introduction To Computing For Energy and Environment

This document introduces useful Python modules including math, random, time, and ipywidgets. It provides examples of importing and using functions from these modules. It also assigns exercises for readers to practice using the modules, such as verifying trigonometric identities using math, testing the random number generator, playing rock-paper-scissors with random, creating an infinite loop that prints integers with delays using time, and building interactive widgets using ipywidgets. Finally, it demonstrates how to create your own module with defined functions that can be imported and used in other programs.

Uploaded by

Ming Lim Chan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

SEE1002 Introduction to Computing for Energy and

Environment

Lab 3.1a: Useful Python modules

Modules are extremely useful. They add extra functionality and capability to our programs, saving us from
writing the code ourselves. Here we introduce several of the most useful Python modules.

1 math

The math module contains many useful functions. We have already used it on several occasions.
Functions from math can be called using qualified or unqualified references.

In [3]:

# example 1a: qualified references


import math

a = math.cos(math.pi)
print(a)

-1.0

In [1]:

# example 1b: unqualified references


from math import sqrt,log

a = sqrt(2)
print(a)
print(log(1))

1.4142135623730951
0.0

Exercise 1 Verifying trigonometric identities

Verify the following trigonometric identities:

1. 2
cos(2𝑥) = cos (𝑥) − sin (𝑥)
2

2. arccos(cos(𝑥)) = 𝑥

for 𝑥 ∈ [0, 𝜋] . Discretise the interval using 10 evenly spaced points and print the residuals (i.e. left-
hand side minus right-hand side) for each value of 𝑥. Do so using qualified and unqualified references.
The output should look like this for the first identity:

i = 1, x=0.000000, residual=0.000000
i = 2, x=0.031733, residual=0.000000
i = 3, x=0.063467, residual=0.000000
i = 4, x=0.095200, residual=0.000000
[...]

In [ ]:

# Answer to Exercise 2.1

In [ ]:

# Answer to Exercise 2.2

2 random

The random module generates random numbers. It can be used for many different applications. Here’s a
brief summary:

In [7]:

import random

N=10
a=1.0
b=2.0
mylist=['rock', 'paper', 'scissors']

print(random.random()) # random float 0<= x <=1


print(random.uniform(0,N)) # random float 0<= x <=N
print(random.randint(a,b)) # random integer a <= x <=b
print(random.choice(mylist)) # picks random element from a list

0.9145152366659649
7.7943991526349
2
scissors

Exercise 2: testing the random number generator

Let's check to see whether the random numbers generated look reasonable. Write a program that prints 𝑁
random numbers and calculates their average.

In [ ]:

# Answer to Exercise 2
Exercise 3: rock, paper and scissors

Random number generators are useful for writing games. Use random.choice to play a game of rock,
paper, scissors.

Your program should do the following:

1. Create a list containing the three elements, e.g. elements = [ ‘rock’,‘paper’,‘scissors’].


2. Use random.choice to get the computer to make a choice.
3. Write a function that prompts the user to enter r/R, s/S, p/P. Continue prompting so long as the input is
invalid.
4. Determine whether the user has won, lost or drew by writing separate functions, analyse_UserRock ,
analyse_UserPaper , analyse_UserScissors , for each of the three valid choices. The element
chosen by the computer (e.g. computer_choice) should be passed as an argument to the functions.
5. Use an explicit main .

The output should look like:\ Please choose rock (r/R), paper (p/P), or scissors (s/S): w \ Please
choose rock (r/R), paper (p/P), or scissors (s/S): R \ You chose rock \ The computer chose scissors.
You win!

In [12]:

# Answer to Exercise 3

3 time

Occasionally it’s useful to have access to date and time functions.

In [10]:

import time
N=5
print(time.ctime()) #gets currect date and time
time.sleep(N) #delays execution for N seconds
print(time.ctime())

Fri Mar 26 13:52:42 2021


Fri Mar 26 13:52:47 2021

Exercise 4: a sleepy infinite loop

Create an infinite loop that prints the integers starting at 0. To ensure that the numbers don’t scroll by too
quickly add a delay (in seconds) equal to the current value of the integer. Verify that the delay is correct by
printing the current time before and after the call to time.sleep . The output should look like this:

Tue Mar 23 22:18:37 2021 \ i= 0 \ Tue Mar 23 22:18:37 2021 \ \ Tue Mar 23 22:18:37 2021 \ i= 1 \ Tue Mar
23 22:18:38 2021 \ \ Tue Mar 23 22:18:38 2021 \ i= 2 \ Tue Mar 23 22:18:40 2021
In [ ]:

# Answer to Exercise 4

4. Widgets

The programs we’ve written so far aren’t very pretty. There are lots of modules for user interfaces. One very
useful module is ipywidgets . It creates widgets, which are graphical user interface elements. In
particular, it allows us to introduce sliders for modifying variables. There are also widgets for progress bars
and user input.
Unfortunately ipywidgets may not work inside Spyder. However, it works inside Jupyter notebook or
Google Colab. The following program creates a slider:

In [8]:

import ipywidgets

def square_root(x):
print('The square root of %f = %f' %(x, x**0.5))
return

ipywidgets.interact(square_root,x=(0,25,1));

The interact function creates a slider based on the values of 𝑥. What happens as 𝑥 is varied?

Exercise 5: nth root

Use ipywidgets to write a simple program that allows a user to calculate the 𝑛 th root of a number, 𝑥1/𝑛 ,
where 𝑛 > 0. Use sliders to specify 𝑛 and 𝑥. The output should be of the form “The n[suffix] root of [𝑥]=[
𝑥
1/𝑛
]" where suffix is ‘st’ for 𝑛 = 1, 'nd' for 𝑛 = 2, 'rd' for 𝑛 = 3 and 'th' otherwise.

The output should look like this:

The 5th root of 12.000000 = 1.643752 \ The 4th root of 12.000000 = 1.861210 \ The 2nd root of
12.000000 = 3.464102 \ The 1st root of 12.000000 = 12.000000

In [13]:

# Answer to Exercise 5

5. Creating a module of your own


Modules aren't needed to use functions defined with a Jupyter notebook. For example, the function

In [15]:

def add(x,y):
return(x+y)

can be used within the same notebook (after the function has been defined):
In [19]:

print(add(2,3))
add(1,2)

Out[19]:

Nevertheless, we can still import a function from a module. You can download the module mylib.py from
Canvas. It looks like this:

def perimeterareaRectangle(L,W):
return (L*W,2*(L+W))

def perimeterRectangle(L,W):
return (2*L + 2*W)

def areaRectangle(L,W):
area=L*W
return (area)

Now let's test it using a program

In [12]:

# from mylib import *

L=float(input('Enter length: '))


W=float(input('Enter width: '))

print( 'The area of the rectangle=',areaRectangle(L,W) )


print('The perimeter of the rectangle=',perimeterRectangle(L,W) )

area,perimeter=perimeterareaRectangle(L,W)
print('The area of the rectangle=',area )
print('The perimeter of the rectangle=',perimeter)

Enter length: 1.0


Enter width: 2.0
The area of the rectangle= 2.0
The perimeter of the rectangle= 6.0
The area of the rectangle= 2.0
The perimeter of the rectangle= 6.0

In [ ]:

You might also like