55284A - Introduction to Python _ Chapter3
55284A - Introduction to Python _ Chapter3
Topics Covered
The math
Th module.
is
do
cu
The random module. me
nt
be
lon
No ja gta gs to
un p NI
au nilka L
tho nt@ KAN
I had been to school rmost ize all
rethe time
T and could spell and read and write just a little, and could say the
dif ESH
multiplication table up todsix co times
pie .coseven
f WAis thirty-five, and I don't reckon I could ever get any further than
s a take m R
that if I was to live forever. I don't llo no stock
JA in mathematics, anyway.
w G
– Adventures of Huckleberry Finn, Mark ed Twain TAP
! .
Introduction
Th some built-in math functions and some additional built-in libraries that provide extended math (and
Python includes is
do
cu In this lesson, we’ll cover the built-in functions and the math and random libraries.
related) functionality. me
nt
be
lon
Arithmetic Operators No agta gs to
j
un p NI
au nilka L
tho nt@ KAN
riz red TES
ed HW
c iff.
op operators
The following table lists the arithmetic ies com in Python. Most will be familiar. We’ll explain the others.
A R
all JA
ow GT
ed AP
Arithmetic Operators ! .
Operator Description
+ Addition
Th
is
do
cu 5 + 2 returns 7
men
tb
elo
n
No jagta gs to
- pn
un Subtraction NI
au il LK
tho kant
riz @ ANT
ed re ES
co d3iff.c
5 - 2 returns
HW
pie o AR
sa m JA
llo GT
we AP
d! .
* Multiplication
5 * 2 returns 10
Th
/ is Division
do
cu
men
tb
elo
jag ng
N s
Operator Description
% Modulus
Th
is
do 5 % 2 returns 1
cu
men
tb
elo
n
** gta gs to
No jaPower
un p NI
au nilka L
tho nt@ KAN
riz TE
ed 5 torethe SH of 2. It returns
co diff.c
5**2 is power 25
pie o WA
sa m R
JA
llo GT
we AP
// Floor Division
d! .
5 // 2 returns 2
Th
is
Here are the examples in Python:
do
cu
me
nt
be
lon
>>> 5+2 No agta gs to
j
un p NI
au nilka L
7 tho nt@ KAN
riz re TE
ed SH
>>> 5-2 co diff.c
pie om WAR
3 sa JA
llo GT
we AP
>>> 5*2 d! .
10
>>> 5/2
2.5
>>> 5%2
1 Th
is
do
>>> 5**2 cu
men
25 tb
elo
n
>>> 5//2 No agta gs to
j
un pn NI
au il LK
2 tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d!
Modulus and Floor Division .
Th
is
do
cu
men
tb
elo
jag ng
N s
Th of 5 divided by 2 is 1.
The remainderis
do
cu
me
The modulus operator (%) nt is used to find the remainder after division:
be
lon
No ja gta gs to
un p NI
au nilka L
tho nt@ KAN
r ize T
d c rediff ESH
>>> 5 % 2
op . WA
1 ies com R
all JA
>>> 11 % 3 o we GT
d! AP
.
2
>>> 22 % 4
2
>>> 22 % 3
1
Th
i
>>> 10934 % s324
do
cu
men
242 tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
Modulus and Negative Numbers riz @ ANT
ed re ES
co diff.c HW
pie numbers
o AR surprising, and are different in different programming languages. Python uses
The results of modulus operations with negative s a m can be JA
the following formula: x - y*(x//y), which will always llo return GT number. This is mostly academic. You will likely never have to deal with
a positive
we AP
this, so we will not dig further into it. d ! .
The floor division operator (//) is the same as regular division, but rounded down:
Th
>>> 5 // 2
is
do
2 cu
me
>>> 11 // 3 nt
be
lon
3 No jagta gs to
un p NI
>>> 22 // 4 au nilka L
tho nt@ KAN
riz r e TE
5 ed SH
co diff.c
>>> 22 // 3 pie om WAR
sa JA
llo GT
7 we AP
d! .
>>> 10934 // 324
33
>>> -5 // 2 # rounded down, meaning towards negative infinity
-3
Th
is
do
cu
men
tb
on el
ExerciseN 8:jagFloorgs and Modulus
5 to 10 minutes
In this exercise, you will write a small function called divide() that takes a numerator and denominator and prints
out a response that a fifth grader would understand (e.g., “5 divided by 2 equals 2 with a remainder of 1”).
1. Th
Open math/Exercises/floor_modulus.py in your editor.
is
do
cu
2. Write the divide() me
nt function.
be
lon
3. Run the module.
ja gta gsoutput
No It should to the following:
un p NI
au nilka LK
tho n A
riz t@re NTE
ed
5 divided by 2 equals c2opwith
d iff. a Sremainder
HW of 1
ies com AR
6 divided by 3 equals 2 with J
all a remainder AG of 0
ow TA
ed Pof
12 divided by 5 equals 2 with a remainder ! . 2
1 divided by 2 equals 0 with a remainder of 1
Th
Exercise Code:
is math/Exercises/floor_modulus.py
do
cu
me
nt
be
1. # write the divide() lon function
No agta gs to
j
un p NI
au nilka
2.
LK
tho n A
3. def main(): riz t@re NTE
ed d SH
co if
4. divide(5, 2) pie f.com WAR
sa JA
5. divide(6, 3) llo GT
we AP
6. divide(12, 5) d ! .
7. divide(1, 2)
8.
9. main()
Th
is
do
cu
me
nt
Solution: math/Solutions/floor_modulus.py
be
lon
No jagta gs to
un pn NI
au den): il LK
1. def divide(num, tho kant
riz @ ANT
remainder = numed% den re ES
co diff.c
2. H
3. floor = num // den ies
p om WAR
all JA
o GT
4. print(num, "divided by",wden, ed AP
"equals",
! .
5. floor, "with a remainder of", remainder)
6.
7. def main():
8. divide(5, 2)
9. divide(6,
T 3)
his
10. do
divide(12, 5)
c um
11. divide(1,ent2)
b elo
jag ng
N s
12.
13. main()
Assignment Operators
The following table lists the assignment operators in Python.
Th
is
do
cu
Assignment Operators me
nt
be
lon
No ja gta gs to
p
un Description NI
Operator au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
Basic assignment
= pie om WAR
sa JA
llo GT
a = 2 wed AP
! .
a += 2 same as a = a + 2
Th
is
do
cu
men
tOne
be step subtraction and assignment
-= lon
No agta gs to
j
un a -= p N
au ni2lkasame ILasK a = a - 2
tho nt@ AN
riz re TE
ed SH
co diff.c
pie om WAR
s a and assignment
One step multiplication JA
llo GT
*= we AP
d! .
a *= 2 same as a = a * 2
1. **
2. *, /, //, %
Th
is
3. +, - do
cu
men
tb
elo
n
No agta gs to
j
un topchange
You can use parentheses NI the order of operations and give an operation higher precedence. For example:
au nilka L
tho nt@ KAN
riz red TES
ed HW
c
6 + 3 / 3 is equal to 6 + o1piand iff. will yield
es om
c AR7.
all JA
o G
But (6 + 3) / 3 is equal to 9 / 3wand ed will yieldTA3.
! P.
Operations of equal precedence are evaluated from left to right, so 6 / 2 * 3 and (6 / 2) * 3 are the same.
Built-in Math
Th
is Functions
do
cu
me
Python’s built-in functions 12 include several math functions.
nt
be
lon
No jagta gs to
int(x) un p NI
au nilka L
tho nt@ KAN
riz r e TE
ed SH
co diff.c WA
p
int(x) returns x converted to esan integer. i o m R
all JA
ow GT
ed AP
! .
When converting floats, int(x) strips everything after the decimal point, essentially rounding down for positive
numbers and rounding up for negative numbers.
When converting strings, the string object must be an accurate representation of an integer (e.g., '5', but not
'5.0'). Th
is
do
cu
me
nt
be
lon
N ja g gs
>>> int(5)
5
>>> int('5')
5
>>> int(5.4)
5
>>> int(5.9)
T his
5 do
cu
m en
>>> int(-5.9) tb
elo
n
-5 No jagta gs to
un p NI
>>> int('5.4') au nilka L
tho nt@ KAN
r
Traceback (most recent icallze T
d c rediff ESH
last):
op . WA
File "<stdin>", line 1, in <module> ies com R
all JA
ValueError: invalid literal for int() ow GT
with base
ed AP 10: '5.4'
! .
float(x)
Th
is
do
float(x) returns x converted to a float.
cu
m en
tb
>>> float(5)
elo
n
No agta gs to
j
un pn
ilka NILK
5.0
au
>>> float('5') t h ori nt@ ANT
ze
d c rediff ESH
5.0 op . WA
ies com R
>>> float(5.4) a llo JA
we GT
d! AP
5.4 .
>>> float('5.4')
5.4
>>> float('-5.99')
-5.99
hisT
>>> float(-5.99)
do
cu
-5.99 m en
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
r i @ ANT
abs(x) z ed re ES
co diff.c H
pie om WAR
abs(x) returns the absolute value of xaas s JAor a float.
llo an integer GT
we AP
d! .
>>> abs(-5)
5
>>> abs(5)
5 Th
is
d
>>> abs(-5.5) ocu
me
nt
5.5 be
lo
N jag ngs
>>> abs(5.5)
5.5
pow(base, exp)
Th
is
do
is the same as cu
m en
tb
elo
n
No agta gs to
j
un pn NI
au il LK
base**exp
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
For example: llo GT
we AP
d! .
>>> pow(4, 2)
16
>>> 4**2
Th
16 is
do
cu
men
tb
elo
pow() can take a third ja
argument:ng mod. pow(base, exp, mod) is functionally equivalent to base**exp% mod:
N g s
>>> pow(4, 2, 3)
1
>>> 4**2 % 3
1
Square Brackets
Th in Code Notation
is
do
c notation indicate that the contained portion is optional. Consider the pow() function signature:
Square brackets in codeum
en
tb
elo
n
No agta gs to
pow(base, exp[, mod]) j
un p NI
au nilka L
tho nt@ KAN
This means that the mod parameterriis optional.
ze T
d c rediff ESH
op . WA
ies com R
all JA
round(number[, ndigits]) ow GT
ed AP
! .
round(number[, ndigits]) returns number as a number rounded to ndigits digits after the decimal. If
ndigits is 0 or omitted then the function rounds to the nearest integer. If ndigits is -1 then it rounds to the
nearest 10 (e.g., round(55, -1) returns 60).
Th
i
s d -1)
>>> round(55, o cu
men
60 tb
elo
>>> round(3.14) n
No agta gs to
j
3 un pn NI
au il LK
tho kant
>>> round(-3.14) riz @ ANT
ed re ES
-3 co diff.c HW
pie o AR
sa m JA
>>> round(3.14, 1) llo GT
we AP
d! .
3.1
>>> round(3.95, 1)
4.0
>>> round(1111, 0)
1111
Th
is
do
cu
men
tb
elo
n
No agta gs to
sum(iter[, start]) j
un pn
au ilka NILK
The sum() function takes ant h nt
ori iterable AN a list) and adds up all of its elements. We will cover this in the Iterables
(e.g.,
ze @red TES
dc
lesson (see page 131). op iff.co HWA
ies m R
all JA
ow GT
ed AP
The math Module ! .
The math module is built in to Python and provides many useful methods. We cover some of them here. 14
Th
is
do
u c
>>> import math men
tb
elo
jag ng
N s
Common Methods of the math Module
math.ceil(x)
>>> math.ceil(5.4)
T his
6 do
cu
en m
>>> math.ceil(-5.4) t be
lon
j gta gs to
-5 a
No
un p NI
>>> au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
math.floor(x) we AP
d! .
x rounded down to the nearest whole number as an integer.
>>> math.floor(5.6)
5 Th
is
do
cu
m
>>> math.floor(-5.6)
en
tb
-6 elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
math.trunc(x) co diff.c HW
pie o AR
sa m JA
llo GT
x with the fractional truncated, effectively roundingwe AP 0 to the nearest whole number as an integer.
towards
d! .
>>> math.trunc(5.6)
5
>>> math.trunc(-5.6)
Th
is
-5 do
cu
men
tb
elo
n
No agta gs to
j
un pn NI
au il LK
math.fabs(x) tho kant
riz @ ANT
ed red E
The absolute value of float x. This iff. S
cois similar toHthe built-in abs(x) function except that math.fabs(x) always
pie c om WAR
s
returns a float whereas abs(x) returnsaall number ofJAthe
ow GT same data type as x.
ed AP
! .
>>> math.fabs(-5)
5.0
>>> abs(-5)
5 Th
is
do
cu
men
tb
elo
jag ng
N s
math.factorial(x)
The factorial of x. This is often written as x!, but not in Python!
>>> math.factorial(3)
6
>>> math.factorial(5)
120
Th
is
do
cu
men
tb
elo
n
math.pow(x, y) No jagta gs to
un p NI
au nilka LK
x raised to the power y as thaofloat.nt
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
>>> math.pow(5, 2) wed AP
! .
25.0
math.sqrt(x)
Th
is
The square root dofocx as a float.
um
en
tb
elo
n
No agta gs to
j
>>> math.sqrt(25)un pn
au ilka NILK
5.0 t h ori nt@ ANT
ze
d c rediff ESH
op . WA
ies com R
all JA
ow GT
The math module also contains two constants: ed math.pi AP
! . math.e, for Pi and e as used in the natural
and
logarithm. 15
Th
To access any isofdothese methods, you must first import random:
cu
me
nt
be
lon
N ja g gs
>>> import random
Common Methods of the random Module 16
random.random()
Th
is
do
cu 0 and 1.
Random float between me
nt
be
lon
No ja gta gs to
un p NI
au nilka L
nt@ KAN
>>> random.random()
tho
r ize T
0.5715141345521301 d c rediff ESH
op . WA
ies com R
all JA
ow GT
ed AP
! .
random.randint(a, b)
hisT
>>> random.randint(1,
d 10)
oc
um
7 # integer between
e 1 and 10
nt
be
lon
No agta gs to
j
un p NI
au nilka L
tho nt@ KAN
random.randrange(b) r ize T
d c rediff ESH
op .co WA
Random integer between 0 and b-1.ies a m R
JA
llo GT
we AP
d! .
>>> random.randrange(10)
3 # integer between 0 and 9
Th
is
do
cu
random.randrange(a, me b)
nt
be
Random integer between a loand
n b-1.
No jagta gs to
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
>>> random.randrange(1, 10) co diff.c HW
pie o AR
sa m JA
5 # integer between 1 and 9 llo GT
we AP
d! .
random.randrange(a, b, step)
>>> random.uniform(1,
T 10)
his
do
8.028088082797572 # a float between 1 and 10
c um
en
tb
elo
n
No jagta gs to
un p NI
au nilka LK
random.choice(seq) and thrandom.shuffle(seq)
ori nt@ ANT
ze red ES
d if elementHW
random.choice(seq) returns acorandom
pie f.com AR in the sequence seq.
sa JA
llo GT
we AP
d! .
random.shuffle(seq) shuffles the sequence seq in place.
Seeding
Th
is
do
random.seed(a) cuis used to initialize the random number generator. The value of a will determine how random
m
numbers are selected.eThent following code illustrates this:
be
lon
No agta gs to
j
un p NI
au nilka L
tho nt@ KAN
>>> import random r ize T
d c rediff ESH
op . WA
>>> random.seed(1) ies com R
a llo JA
>>> random.randint(1, 100) we GT
d! AP
18 .
Notice that the random numbers generated depend on the seed. If you run this same code locally, you should get
the same random integers. This can be useful for testing.
Th
is
do
By default, random.seed() uses the current system time to ensure that seed() is seeded with a different
cu
me
number every time it runs, nt so that the random numbers generated will be different each time.
be
lon
N ja g gs
Exercise 9: How Many Pizzas Do We Need?
15 to 25 minutes
Th
is you will write a program from scratch. Your program should prompt the user to input the information
In this exercise, do
cu
required: me
nt
be
lon
N ja g gs
The number ofopeople. t t
un apni o NI
au l LK
tho kant AN
The number of slices each r @
ize person T eat.
will
d c rediff ESH
op . WA
ies com R
The number of slices in each pizzaallpie. JA
ow GT
ed AP
! .
Using that information, your program must calculate how many pizzas are needed to feed everyone. It should work
like this:
Th
is
do are eating? 5
How many peoplecu
me
How many slices per nt person? 2.5
b elo
ng 8
How many slicesN perjagpie?
o s ta to
u pn
You need 2 pizzas nto
au feed il 5 Npeople.
ILK
tho kant AN
r @
There will be 3.5 leftover
d red TES
ize slices.
if H co
pie f.com WAR
sa JA
How many people are eating? 25 llowe GT
AP
d! .
How many slices per person? 2
How many slices per pie? 8
You need 7 pizzas to feed 25 people.
There will be 6.0 leftover slices.
Th
is
do
cu
en m
tb
Solution: math/Solutions/pizza_slices.py
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
1. import math
riz @ ANT
ed re ES
2. co diff.c H
pie om WAR
3. def main(): s all JA
ow GT
e AP eating? "))
d! people are
4. people = int(input("How many .
5. slices_per_person = float(input("How many slices per person? "))
6. slices = slices_per_person * people
7.
8. slices_per_pie = int(input("How many slices per pie? "))
9. Th
pizzas = math.ceil(slices / slices_per_pie)
is
do
10. cu
m en
11. print("Yout bneed",
el pizzas, "pizzas to feed", people, "people.")
on
N jag gs
12.
13. total_slices = slices_per_pie * pizzas
14. slices_left = total_slices - slices
15. print("There will be", slices_left, "leftover slices.")
16.
17. main()
Th
is
do
cu
m
Exercise 10:
en Dice Rolling
tb
e lon
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
15 to 25 minutes ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .
In this exercise, you will write a dice-rolling program from scratch. The program should include two functions:
main() and roll_die(). The roll_die() function should take one parameter: sides, and return a random
roll between 1 and sides
The main() function should call the roll_die() function three times and keep a tally of the total. After each roll,
Thout the value of the roll, the number of rolls, and the total. At the end, it should output the average of
it should print is
do
the three rolls. The cuoutput will be similar to the following:
me
nt
be
lon
No agta gs to
j
un p NI
You rolled a 3 au nilka L
tho nt@ KAN
Total after first roll:iz3 r re TE
ed SH
co diff.c
You rolled a 5 pie om WAR
sa JA
llo GT
Total after 2 rolls: 8 we AP
d! .
You rolled a 3
Total after 3 rolls: 11
Your average roll was 3.67
Thanks for playing.
Th
is
do
cu
en m
tb
Solution: math/Solutions/dice.py
elo
n
No agta gs to
j
un pn
a ilka NILK
1. import random utho n A
riz t@re NTE
ed d SH
2. co if
pie f.com WAR
3. def roll_die(sides=6): sa JA
llo GT
we AP
4. num_rolled = random.randint(1, d! sides) .
5. return num_rolled
6.
7. def main():
8. sides = 6
9. Th
total = 0
is
do
10. cu
me
n
11. num_rolls t=be1
lon
12. jag gs
roll =N roll_die(sides)
13. print("You rolled a", roll)
14. total += roll
15. print("Total after first roll:", total)
16.
17. num_rolls += 1
18. roll = roll_die(sides)
19. print("You rolled a", roll)
Th
is
20. totaldo += roll
cu
21. me
print("Total after", num_rolls, "rolls:", total)
n tb
22.
elo
n
No jagta gs to
23. un += p1ni
num_rolls NI
au lka LK
t
24. h o
roll = roll_die(sides)
riz
n t @ ANT
ed red E
25. print("You rolled ca", ff.c SHW
op iroll)
ies om AR
26. total += roll all JA
ow GT
ed AP
27. print("Total after", num_rolls, ! .
"rolls:", total)
28.
29. average = round(total / num_rolls, 2)
30. print("Your average roll was", average)
31.
T
his
32. print("Thanks for playing.")
do
cu
33. m en
tb
34. main() elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
Conclusion pie
sa m
o AR
llo JA
w GT
In this lesson, you have learned to do basic emath d! AP and to use the math and random modules for
in Python.
extended math functionality.
12. https://docs.python.org/3/library/functions.html
Th
is
do
cu
me
nt
be
lo
13. The min() and jag nfunctions
No max() g can also compare strings.
tap s to
un N
au nilka IL
tho nt@ KAN
riz red TES
ed HW
c if
14. To get a full list of the math module’so pie f.comethods, AR import math and then type help(math) in the Python shell or
sa m JA
visit llo GT
we AP
d! .
https://docs.python.org/3/library/math.html.
15. https://en.wikipedia.org/wiki/Natural_logarithm
Th
is
do
cu
me
16. To get a full list of nthe
t b random module’s methods, import random and then type help(random) in the
elo
Python shell or j
visita ng
N g s
https://docs.python.org/3/library/random.html.
Th
is
do
cu
men
tb
elo
n
No jagta gs to
un p NI
au nilka L
tho nt@ KAN
riz re TE
ed SH
co diff.c
pie om WAR
sa JA
llo GT
we AP
d! .
Th
is
do
cu
men
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .
Th
is
do
cu
men
tb
elo
n
No agta gs to
j
un pn NI
au il LK
tho kant
riz @ ANT
ed re ES
co diff.c HW
pie o AR
sa m JA
llo GT
we AP
d! .
Th
is
do
cu
men
tb
elo
jag ng
N s