You are on page 1of 35

INTRODUCTION TO

COMPUTING SCIENCE AND PROGRAMMING


Lecture 4.1: Modules & Functions

CMPT 120, Spring 2023, Mohammad Tayebi


Class Agenda

• Today
• Last Time • Functions
• In-class Exercises • Flow of Execution With Functions
• Multiple Functions
• Calling Functions Inside Functions
• Function Parameters
• Main Function

• Reading
• cspy ch. 5 & 6

CMPT 120, Spring 2023, Mohammad Tayebi 2


Functions
• Function is a sequence of statements that performs a specific task.
• Divide and conquer
• Breaking up the program to smaller and manageable pieces
• Making software development process more manageable
• Reusability
• Avoid code duplication by calling a function in the program as many times as needed
• Adding functions to a library (module) to be used by any program
• How to define a function:
• def : A function begins with the word def
• name : def is followed by the function’s name
parenthesis : the name is followed by a pair of def sayhi():
parenthesis and a colon print('Hi!')
• body : Indented lines of code
CMPT 120, Spring 2023, Mohammad Tayebi 3
Flow of Execution With Functions
def sayhi(): 4
print('Hi!') 5
print('What’s up?') Function definitions do not alter the
6
flow of execution of the program.

print('This is a test program!') 1 Functions are not executed until they


print('The last line before calling sayhi!') 2 are called.
sayhi() 3

When a function is called the flow jumps to


the first line of the called function.
This is a test program!
The last line before calling sayhi
Hi!
What’s up?

CMPT 120, Spring 2023, Mohammad Tayebi 4


In-class Exercise 1
• Which option shows the correct syntax for a function in
Python that multiplies two numbers?

1 3 4
2
def addition(): addition(): def addition
def addition:
a = 3 a = 3 a = 3
a = 3
b = 4 b = 4 b = 4
b = 4
c = a * b c = a + b c = a + b
c = a + b

CMPT 120, Spring 2023, Mohammad Tayebi 5


In-class Exercise 2
def addition():
• What is the a = 3
output of the b = 4
following c = a + b
program? addition()
addition()
addition() 4
3
1 2
7 7 7 7
7
7
7

CMPT 120, Spring 2023, Mohammad Tayebi 6


In-class Exercise 3
def addition():
• What is the last line of a = 3
the code to be b = 4
executed by Python in c = a + b
the following program? addition()
addition()
addition()
3 4
1 2

def addition(): addition() c = a + b a = 3

CMPT 120, Spring 2023, Mohammad Tayebi 7


Multiple Functions
def sayhi():
This is a test program!
print('Hi!')
print('What’s up?') The last line before calling sayhi!
Hi!
What’s up?
The last line before calling saybye!
def saybye(): I need to go!
print('I need to go!') See you later!
print('See you later!')

You can define multiple functions to break


print('This is a test program!') your program to meaningful pieces.
print('The last line before calling sayhi!')
sayhi()
print('The last line before calling saybye!')
saybye()

CMPT 120, Spring 2023, Mohammad Tayebi 8


In-class Exercise 4
def hi():

• What is the print('Hi')


print('How are you?')
output of the def bye():
following print('Bye')
program?
bye()
print('I am leaving!')
hi()

Bye I am leaving! Syntax error


Hi
I am leaving! Bye How are you?
Hi Hi Bye
How are you? How are you?
I am leaving!
1 2 4
3
CMPT 120, Spring 2023, Mohammad Tayebi 9
Calling Functions Inside Functions
def sayhi():
print('Hi!')
print('What’s up?') This is a test program!
Hi!
saybye() What’s up?
I need to go!
See you later!

def saybye():
print('I need to go!') A function can be called inside
print('See you later!') another function. Python keep
track of execution flow.

print('This is a test program!') To understand what a program does, you


should not read from top to bottom, instead,
sayhi() you should follow the flow of execution.
CMPT 120, Spring 2023, Mohammad Tayebi 10
In-class Exercise 5
def hi():

• What is the print('Hi')


def bye():
output of the hi()
following print('Bye')
program?
bye()
print('I am leaving!')
hi()

Hi I am leaving! Syntax error


Bye
Bye Bye Hi
I am leaving! Hi Bye
Hi How are you?
I am leaving!
1 2 4
3
CMPT 120, Spring 2023, Mohammad Tayebi 11
Function Parameter
def sayhi(name):
print('Hi!', name + '!')
print('What’s up?')
Function parameters is information
that function receive from the caller.
print('This is a test program!’)
name = 'Anna' Parameter numbers can be any,
sayhi(name) zero or many.

This is a test program!


Hi Anna!
What’s up?

CMPT 120, Spring 2023, Mohammad Tayebi 12


In-class Exercise 6
• What does the def somefunction(a):
following c = a * a
function do? c = a / a
print(a)

Print the Print the given Syntax error


Do nothing
square of a number
given number

1 2 4
3
CMPT 120, Spring 2023, Mohammad Tayebi 13
Multiple Parameters
def sayhi(pname, pcountry, pcity):
print('Hi', pname + '!') No limitation in the number of
print('What’s up?') parameters you pass to a function.
print('Are you from', pcountry +
'?') Parameters should be separated by
commas.
print('which city?', pcity + '?')

print('This is a test program!')


name = 'Anna' This is a test program!
country = 'Canada' Hi Anna!
city = 'Vancouver' What’s up?
sayhi(name, country, city) Are you from Canada?
which city? Vancouver?
CMPT 120, Spring 2023, Mohammad Tayebi 14
Functions that Return Values
def sayhi(pname):
print('Hi', pname + '!')
user_age = int(input('May I ask
how old are you? '))
return user_age If needed, a function can return a piece of
information to help the program to complete
the assigned task.

name = 'Anna'
age = sayhi(name)
print(name, 'is', str(age) + '
years old.') Hi Anna!
May I ask how old are you? 12
Anna is 12 years old.
CMPT 120, Spring 2023, Mohammad Tayebi 15
In-class Exercise 7
• What does the
following def somefunction(a,b):
function do? c = a * a + b
c = a / a
d = c + a

Print the Sum up two Multiply two


Increase the
multiplication numbers numbers
first
of two numbers parameter by
one

1 2 4
3
CMPT 120, Spring 2023, Mohammad Tayebi 16
Using a Main Function
In some programming languages such as C,
def sayhi(pname): C++ and Java, the program can not start
print('Hi', pname + '!') executions from statements sitting alone
outside of a function, and a special function,
called main, is needed to be automatically
invoked for program execution.
def main():
name = 'Anna' In python a main function is not needed but to
have a more structured and readable program it
sayhi(name) is recommended to use such function. Note that,
print('Goodbye!') there is nothing special about the name main.

main() Hi Anna!
Goodbye!
CMPT 120, Spring 2023, Mohammad Tayebi 17
Example - A Function to Compute the
Volume of a Cylinder
def volume_cylinder(radius, height):
pi = 3.14159
volume = pi * radius ** 2 * height
return volume

print(volume_cylinder(2, 3))

37.699079999999995

CMPT 120, Spring 2023, Mohammad Tayebi 18


Example - A Function to Compute the
Area of a Circle
def area_circle(radius):
pi = 3.14159
area = pi * radius ** 2
return area

print(area_circle(2))

12.56636

CMPT 120, Spring 2023, Mohammad Tayebi 19


Functions That Do Not Return Values

def area_circle(radius):
pi = 3.14159
area = pi * radius ** 2
print(area)

area_circle(2)
12.56636

CMPT 120, Spring 2023, Mohammad Tayebi 20


Local and Global Variables
def main(): Local variable
• Variables that are created inside a name = 'Anna'
function called local. print('Hi!', name)
• Local variables only exist inside the
function.
• Variables that are created outside Global variable
age = 18
of a function are known as global
variables. main()
• Global variables can be used by print('Anna is ', str(age) +
everyone, both inside of functions ' years old.')
and outside.

CMPT 120, Spring 2023, Mohammad Tayebi 21


Defining Global Variable Inside a Function

def area_circle(radius):
We can define a global variable inside a
global pi function using the global keyword.
pi = 3.14159
area = pi * radius ** 2
Functions can access global variables and
pi = pi + 1 The area_circle modify them. Modifying global variable
print(area) function has some side inside a functions is considered poor
effect on whole program programming practice.
by changing the value of
the variable pi.
area_circle(2) Based on modular programming principles
print(pi) the best practice is to think of a function
as black-box with input and outputs.
12.56636
4.14159
CMPT 120, Spring 2023, Mohammad Tayebi 22
In-class Exercise 8
def somefunction(a,b):
global k
• What is the final k = 10
value of x? c = a + b + k
return c

x = somefunction(1,2)
k = 3
x = somefunction(1,2)
x = x + k

12 18 11
23

1 2 4
3
CMPT 120, Spring 2023, Mohammad Tayebi 23
Modules

• A module is a file containing Python definitions and statements


intended for reusing in other Python programs.
• Grouping related code as per their functionality
• Making your code organized and easier to maintain
• Built-in modules
• There are many modules that come with Python as part of the standard library.
• User-defined modules
• Creating your own functions and put them in a module

CMPT 120, Spring 2023, Mohammad Tayebi 24


The math Built-in Module

• Contains mathematical functions

To import a module, we We can import a specific


use the keyword import
function of a module

>>> import math >>> from math import pi


>>> from math import sqrt
>>> print(math.pi)
>>> print(pi)
3.141592653589793
3.141592653589793
>>> print(math.sqrt(4))
>>> print(sqrt(4))
2.0 2.0

CMPT 120, Spring 2023, Mohammad Tayebi 25


The random Built-in Module

• To generate random number You can give s shorter


• Giving computer game the chance of flipping a coin name to a module in
your program
• Random shuffling of card games
• Data encryption
• Data simulation

>>> import random >>> import random as r


>>> p = random.random() >>> p = r.random()
>>> print(p) >>> print(p)
0.7451468522749828 0.659954142217758
>>> q = random.randrange(4, 12) >>> q = r.randrange(4, 12)
5 8

CMPT 120, Spring 2023, Mohammad Tayebi 26


User-defined Modules Save functions in a file
named greetings.py

# greetings module
• You can store your functions in a def greeting_morning(pname):
print('Good morning,', pname + "!")
module and import it to your code
when needed. def greeting_afternoon(pname):
print('Good afternoon,', pname + "!")

To use the functions defined in a


import greetings module first we need to import
greetings.greeting_morning('Anna') the respective module.

Good morning, Anna!


The syntax to call a function
stored in a modules is
module.function()
CMPT 120, Spring 2023, Mohammad Tayebi 27
In-class Exercise 9
• Write a program to generate the following structure.

@@@@@@@1
@@@@@@12
@@@@@123
@@@@1234 for i in range(7):
@@@12345 print('@' * (7 - i), end='')
@@123456
@1234567
for j in range(1, i + 2):
print(j, end='')
print()

CMPT 120, Spring 2023, Mohammad Tayebi 28


In-class Exercise 10
• Write a program to generate the following structure.

@
for i in range(7):
@@
print(' ' * (7 - i), end='')
@@@
for j in range(0, i + 1):
@@@@
print('@ ', end='')
@@@@@
print()
@@@@@@
@@@@@@@

CMPT 120, Spring 2023, Mohammad Tayebi 29


In-class Exercise 11
• Write a program to test whether a given number by
user is perfect square.
A perfect square is an integer
that is the square of an integer.
# this program tests if a number is perfect
square.

n = int(input('Enter a number: '))


root = int(n ** 0.5)
if n == root * root:
print(n, 'is a perfect square.')
else:
print(n, 'is not a perfect square.')
CMPT 120, Spring 2023, Mohammad Tayebi 30
In-class Exercise 12
# this program detects if
three numbers provided by
user are equal or not.
flag = 0
• Write a program using for x = 0
loop that takes three numbers for i in range(3):
y = x
from user and writes 'equal' if
x = int(input())
all three are equal, and 'not if i > 0 and y == x:
equal' otherwise. flag = 1
else:
flag = 0
if flag == 1:
print('equal')
else:
print('not equal')
CMPT 120, Spring 2023, Mohammad Tayebi 31
Piazza Challenges

CMPT 120, Spring 2023, Mohammad Tayebi 32


Challenge 1
• Write a python program to take a cylinder radius (r) and height (h)
from the user and compute the cylinder area. The formula to
compute the cylinder area is 2πrh + 2πr2. And π is equal to 3.14.

# this program computes the area of a cylinder given its radius and height.
radius = float(input('Insert the radius of the cylinder: '))
height = float(input('Insert the height of the cylinder: '))
pi = 3.14
area = 2 * pi * radius * height + 2 * pi * radius * height
print('The cylinder are is:', area)

CMPT 120, Spring 2023, Mohammad Tayebi 33


Challenge 2
• Write a Python program to print out the cube of all
numbers from a number provided by the user to 1.

# this program produce the cube of all


numbers in the range of a given number to 1.
range(n, 0, -1)
n = int(input('Enter a number: '))
for i in range(n, 0, -1): is equal to

cube = i ** 3 reversed(range(1, n+1)


print(cube)

CMPT 120, Spring 2023, Mohammad Tayebi 34


Next Lecture

Modules & Functions


Pre-reading: N/A

CMPT 120, Spring 2023, Mohammad Tayebi


35

You might also like