Introduction To Py
Introduction To Py
Functions provide us means to manage complexity of programming by dividing the code into
blocks that will:
• Allows to have code blocks with well-defined roles
• Promote reusability and minimise redundancy
• Increase readability
• easy maintenance
Functions
Python Functions
User-defined
Built-in Functions
Functions
e.g.
• print()
• len()
• range()
Full list of functions available at
https://docs.python.org/3/library/functions.html
User defined functions
Function name parameters
If return is not present, the function exits when the control flow falls off the end of the
function body
Coding Functions (2)
Arguments are passed by position, unless you say otherwise, and they match from left to
right
can also pass arguments by name with name=value keyword syntax, and unpack
arbitrarily many arguments to send with *pargs and **kargs starred-argument notation
Functions - examples
sum_numbers()
Exercise 1
The above defines the default value to an argument. This value will be taken in case you don’t pass a value
when you invoke the function.
Arbitrary arguments
defined by using *
Functions with optional arguments (2)
def example2(arg1,**arg2): dictionary of keyword arguments defined by using **
print(arg1)
for key, value in arg2.items():
print(f’{key}: {value}’)
You need to define the function before calling it. i.e. define your functions at the
beginning of your program
The variables that are defined inside the function are local to that function. i.e. they
cannot be accessed outside the function
The variables that are defined outside the function are called a global variable. How to
change a value of global variable inside a function?
Two functions cannot have the same name. If two functions are declared with the same
name the latter will override the prior function
global and local variables
global variable
local variable
creating global variables inside functions
global variable
global variable
Flow of Execution with Functions
Write a function to get two inputs; first name, last name and print the full name
Exercise 3
Write a function to calculate salary of an employee when the following arguments are
given
name, employee type (full time, part time) , basic salary, hourly rate, number of hours
You should get employee name, type, basic salary, hourly rate , and number of hours (as
may be the case) as user input outside the function and pass the relevant values to the
function to calculate the salary
Exercise 5
“Introduction to Python”
Exercise 6
“Introduction-to-Python”
Questions?