Programming Foundation
with Python
Lesson 5 Functions
Coding ညေကျာင်း By CodeChamps
We call these reusable pieces of code “functions”
Program:
Output:
def thing():
print('Hello') Hello
print('Fun')
Fun
thing() Zip
print('Zip') Hello
thing()
Fun
There are two kinds of functions in Python.
Built-in functions
- that are provided as part of Python
- print(), input(), type(), float(), int() ...
User defined function
- Functions that we define ourselves and then use
We treat function names as new reserved words
(i.e., we avoid them as variable names)
A function is some stored code that we use.
A function takes some input and produces an output.
What are the functions defined in modules?
Python Module
Python has a math module that provides most of the familiar mathematical functions.
The random module provides functions that generate pseudorandom numbers.
Before we can use the module, we have to import it.
The module object contains the functions and variables defined in the module.
To access one of the functions, you have to specify the name of the module and the
name of the function, separated by a dot (also known as a period).
This format is called dot notation.
How to use Random module?
To see a sample, run this loop:
import random
number_list = [1,4,8,3,9]
mychoice = random.choice(number_list)
x = random.random()
y = random.randint(10,20) Run the program on your system and
see what numbers you get.
print(x) Run the program more than once and
see what numbers you get.
print(y)
print(mychoice)
How to use Math module?
import math
import random
number = random.randint(2,20)
print(number)
print(math.sqrt(number))
print(math.factorial(number))
Class Activity: To display who is the winner.
import random
print("Computer:: ",random.randint(1,6))
ans = input("Do you want to play?(y/n):: ")
if(ans == "y"):
print("Player:: ",random.randint(1,6))
Function Definition
● In Python a function is some reusable code that takes arguments(s) as input,
does some computation, and then returns a result or results
● We define a function using the def reserved word
● We call/invoke the function by using the function name, parentheses, and
arguments in an expression
Building our Own Functions
● We create a new function using the def keyword followed by optional
parameters in parentheses
● We indent the body of the function
● This defines the function but does not execute the body of the function
def printGreeting():
print(“Welcome to my program…”)
print(“*” * 40)
Example: just define the function
number = 89
print(number,“* 4 =”,number * 4)
def printGreeting():
print(“*” * 40)
print(“Welcome to my program…”)
print(“*” * 40)
print(“Hello”)
print(number,“/ 3 =”,number/3)
Definitions and Uses
● Once we have defined a function, we can call (or invoke) it
as many times as we like
● This is the store and reuse pattern
Example: Function Calling
number = 89
print(number,“* 4 =”,number * 4)
def printGreeting():
print(“*” * 40)
print(“Welcome to my program…”)
print(“*” * 40)
print(“Hello”)
printGreeting()
print(number,“/ 3 =”,number/3)
Parameters and Return Value
A parameter is a variable which we use in the function definition. It is a “handle”
that allows the code in the function to access the arguments for a particular
function invocation.
Often a function will take its arguments, do some computation, and return a value
to be used as the value of the function call in the calling expression. The return
keyword is used for this.
def addto5(x): ‘x’ is parameter
y = x + 5
return y ‘y’ is return value
Arguments
● An argument is a value we pass into the function as its input when we call the
function
● We use arguments so we can direct the function to do different kinds of work
when we call it at different times
● We put the arguments in parentheses after the name of the function
print(“Hello”)
result = addto5(number)
print(result)
Function Definition and Function Invoking(Calling)
def greet(lang):
Function Calling
if lang == 'es':
>>> greet('en')
print('Hola') Hello
elif lang == 'fr':
>>> greet('es')
Hola
print('Bonjour')
else: >>> greet('fr')
Bonjour
print('Hello')
Check the random import random
number is even or odd def iseven(num):
using function. if(num % 2 == 0):
return True
else:
return False
a = random.randint(10,100)
print(“Your number is”+str(a),end=” “)
if iseven(a):
print(“and it is even”)
else:
print(“and it is odd”)
Multiple Parameters / Arguments
● We can define more than one
parameter in the function definition
def addtwo(a, b):
● We simply add more arguments added = a + b
return added
when we call the function
x = addtwo(3, 5)
● We match the number and order of print(x)
arguments and parameters
Exercise
1. Rewrite the grade program from the previous chapter using a function called
computegrade that takes a score as its parameter and returns a grade as a
string.
2. Rewrite your pay computation with time-and-a-half for overtime and create a
function called computepay which takes two parameters (hours and rate).