SlideShare a Scribd company logo
Programming Fundamentals
Lecture 4: Functions and Modules
This Lecture
• Functions
– Built in functions
– Concept of process abstraction
– Writing functions
– Scope, parameters and return values
• Modules
– Programming language structure
– Modules
– External modules
– Python’s standard library
– The ā€œmathā€, ā€œrandomā€ and other modules
– Creating a module
2
Textbook
• Starting Out with Python, 4th Edition (Global)
– Tony Gaddis
• Reading the chapter(s) is required
– Read the indicated chapter(s) before class
• This week covers the following textbook chapter(s):
– Chapter 5 – Functions
• Entire chapter
3
Functions
Built-In Functions
• Throughout the unit, we have made use of numerous functions that are part of
the Python language
• Some of them have been built-in functions, e.g.
– input() and print() for input and output
– int(), float() and str() to convert data types
– len(), sum(), min() and max() with data structures
• Some of them are specific to certain data types/structures, e.g.
– Strings (str.isupper(), str.lower(), str.count()…)
– Lists (list.append(), list.sort(), list.index()…)
• Some of them are only available as part of a module that you need to import, e.g.
random.randint()
5
Built-In Functions
• Different languages offer different functions, often specialising in areas that the
language is intended for
• Some languages offer lots of built-in functions, others do not
– A language without many functions requires you to write more code to achieve useful
things, but there is less to remember
– A language with lots of functions can allow you to write concise code, but you need to
find/remember the functions
• Groups of functions relating to a specialised task or concept (e.g. generating or
working with random values) are often stored in modules
– If the functions are needed, they can be ā€œimportedā€ (included) in the program
– This helps to keep programs small and efficient by not weighing them down with
things they probably won’t need
6
Process Abstraction
• Functions serve to abstract a process – they give you a way of performing a task
without needing to know the details of how that task is done
– We use the concept of process abstraction every day:
• You don’t need to know how an elevator works, just that you get in and press a button to be
taken to the specified floor
• You don’t need to know how a car’s accelerator works, just that you press it to make the car
go faster
• e.g. All you need to know to use the sum() function is that if you pass it a list of
numbers, it will return the total of them
– Name of function
– Data to pass to it (input)
– Expected result (output)
Input Output
Function
(Process)
7
Writing Your Own Functions
• All languages allow you to define your own functions
– This becomes extremely useful as you start to write longer and more complex
programs, for a number of reasons:
• Code Reuse: A function can be written to perform a task, and then called as many times as
needed throughout the program – no need to write the same/similar code multiple times
• More Readable Code: It’s easier to read and understand a meaningful function name than
a large sequence of statements
• Better Testing: Self-contained functions with known parameters and return values make
testing code easier
• Faster Development: Functions can be reused between different programs or parts of a
program, saving a lot of time
• Easier Teamwork: Functions separate sections of code in a way that makes it easy to
divide work between different people
8
Writing Your Own Functions
• Functions should ideally have these general characteristics:
– A function should perform a well-defined task or process
– Data the function needs should be passed in via parameters
– If the function produces a result, it should return the result
– Code inside a function should be independent of calling code
• Functions should be ā€œmodularā€, with clear input and output
– The output of a function may become an input of another function
• While many languages allow you to break these ideals, you should always try to
stick to them to ensure that you are creating worthwhile functions
– Most of the benefits on the previous slide are only likely to be seen or maximised if
these ideals are upheld, while poorly-conceived functions can worsen a program
9
Declaring a Function
• A function ā€œdeclarationā€ or ā€œdefinitionā€ is the code which defines a function so that
it can be used (ā€œcalledā€) later on
– This involves specifying a function name, details of any parameters that can be
passed to it, and the lines of code that the function performs when it is called
– The code may include return statements to return a result back to the program
– The code is not run at this time – you are just defining the function
– General format of a function declaration in most languages:
function <function name>(<parameters>)
{
<function body>
}
Declare functions at the start of a program,
and then call them where they’re needed
10
Declaring a Function
• Let’s design and implement a function named ā€œrepeatā€, that:
– Receives two parameters (i.e. You must specify two values when calling it):
• ā€œtextā€ - A string (what you want to repeat)
• ā€œcountā€ – An integer (how many times to repeat it)
– Returns a string of ā€œtextā€ repeated ā€œcountā€ times
• i.e. The result of the function is a string consisting of ā€œtextā€, repeated ā€œcountā€ times
• e.g. calling repeat('Bang!', 3) should return a string of 'Bang!Bang!Bang!'
• Note: The function returns the string – it doesn’t print the string
– We have covered what we need to implement this function:
• A for loop to repeat a certain number of times…
• Concatenation to join strings together…
11
Declaring a Function
• Here is pseudocode of a suitable design for the function:
• Here it is in code:
Define ā€œrepeatā€ function (receives ā€œtextā€ and ā€œcountā€)
Set ā€œresultā€ to an empty string
Repeat ā€œcountā€ times
Concatenate ā€œtextā€ to the end of ā€œresultā€
Return ā€œresultā€
Pseudocode
def repeat(text, count):
result = ''
for num in range(count):
result = result + text
return result
print( repeat('Hello!', 4) )
Python
Hello!Hello!Hello!Hello!
This code only declares the function, making it
so that you can now call it in subsequent code.
12
Declaring a Function in Python
• Declaring a function in Python uses the keyword ā€œdefā€, and uses a colon and
indentation rather than curly brackets:
def <function name>(<parameters>):
<function body>
• Example in Python:
• Note: Python doesn’t need a function to do this, since you can simply multiply
strings and integers, e.g. 'Hello!' * 4, to repeat a string…
def repeat(text, count):
result = ''
for num in range(count):
result = result + text
return result
print( repeat('Hello!', 4) )
Python
Hello!Hello!Hello!Hello!
15
Side Note: Common Syntax Structures
• Hopefully as you learn more and more programming concepts, you’ll start to see
the similarities - The structure of different statements are often very similar…
Most Languages
if (<boolean expression>)
{
<true code>
}
while (<boolean expression>)
{
<loop body>
}
function <function name>(<parameters>)
{
<function body>
}
Python
if <boolean expression>:
<true code>
while <boolean expression>:
<loop body>
def <function name>(<parameters>):
<function body>
16
• We’ve used pseudocode and flowcharts to illustrate the flow of programs and
their control structures throughout the unit
– When a step of your program involves using one of your functions, refer to it by name
in the pseudocode, e.g. ā€œCall get_total function and store result as totalā€
– Function calls in flowcharts are represented using this shape:
• A separate section of pseudocode or separate flowchart should be created to
illustrate the definition/body of each function
– This allows pseudocode and flowcharts to remain concise and easy to follow
(which is exactly what functions do to the program itself!)
– Think of pseudocode for functions as appendices of a book – they don’t get in the way
of the main text, but they’re there for you to refer to if you need more information
Functions in Pseudocode and Flowcharts
17
Functions in Flowcharts
Prompt for mark
get_grade(mark)
Add mark to total
Show grade
Show avg grade
Calculate avg mark
While True
True
get_grade(avg)
get_grade(num)
If num >= 80 Set grade to HD
Set grade to F
True
False
If num >= 70 Set grade to D
True
Enter function
Return grade
If num >= 60 Set grade to CR
True
False
If num >= 50 Set grade to P
True
False
False
If mark == x
True
False
Break out of loop
Start program
End program
18
import random
def check_credentials(username, password):
if username == 'admin' and password == 'abc123':
return True
else:
return False
def generate_randoms():
number = random.randint(1, 100)
letter = random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
print('Your number is', number)
print('Your letter is', letter)
print('Please Log In.')
uname = input('Username: ')
pword = input('Password: ')
if check_credentials(uname, pword):
print('Login Successful.')
generate_randoms()
else:
print('Invalid credentials.')
Python
Flow of Control in a Program with Functions
Please Log In.
Username:
Password:
Login Successful.
Your number is 45
Your letter is S
admin
abc123
ā‘ 
ā‘”
ā‘¢
⑤
ā‘„
⑦
ā‘§
⑨
ā‘£
19
Scope, Parameters and Return Values
Scope and Local Variables
• A variable’s ā€œscopeā€ is the part of a program in which it exists and can be referred
to – generally, this is ā€œfrom when it is created, until the program ends/it is deletedā€
• A variable that is created inside a function is known as a ā€œlocal variableā€ and its
scope is limited to that function
– i.e. You cannot access the variable from outside the function
– When a function ends (reaches the end of its code or reaches a return statement)
after being called, any local variables that were defined inside it cease to exist
def example():
local_var = 'Hello!'
print('Printing from inside function:', local_var)
example() # prints as expected
print('Printing from outside function:', local_var) # causes error
Python
21
Scope and Global Variables
• Variables created outside of a function (i.e. directly in the main part of a program)
are known as ā€œglobal variablesā€
– Global variables can be (but shouldn’t be) accessed from any function:
– Trying to assign a value to a global variable will create a local variable instead, unless
declared as a global in the function… As you can see, this gets very confusing:
def example():
print('var in funct:', var)
var = 'A'
example() # var is NOT passed in as a parameter
print('var in global:', var)
Python
var in funct: A
var in global: A
def example():
global var
var = 'B'
print('var in funct:', var)
var = 'A'
example()
print('var in global:', var)
Python
var in funct: B
var in global: B
def example():
var = 'B'
print('var in funct:', var)
var = 'A'
example()
print('var in global:', var)
Python
var in funct: B
var in global: A
22
Scope and Global Variables
• Different languages use slightly different rules regarding variable scope and
access to global variables
• You should avoid referring to global variables from inside functions
– Use parameters to pass data into a function if needed
• Using global variables in functions is discouraged since:
– It prevents functions from being independent of the code that calls them, making them
harder to reuse in other programs
– It makes errors hard to track down, since a variable’s value may be changed from
anywhere in the program
– It makes programs hard to follow and understand
23
Parameters
• When you define a function, you can define its parameters
– This defines what data can be passed in to the function when it is called in your code
– Hence, a function can be instructed to perform its task on the data you give it,
or in a particular way (or both)
– If a function does not need any data/instructions, it may have no parameters (rare)
• e.g. The built-in function round() can take two parameters:
– A number to round, and a number of digits to round it to, e.g.
round(9.24574, 2) returns 9.25
– The first parameter is required (since it makes no sense to call the function without it),
but the second one is optional in this case
• If omitted, the function rounds the value to the nearest integer,
e.g. round(9.24574) returns 9
24
Parameters
• The parameter names you specify when defining a function become local
variables in the function when it is called
– Their values will be provided when the function is called
• These can be literal values or the values of variables from outside the function
– A parameter can be made optional by giving it a default value
• You must provide a value for each non-optional parameter
25
def repeat(text, count = 2):
result = ''
for num in range(count):
result = result + text
return result
print(repeat('Hello!', 4))
word = 'Duck, '
phrase = repeat(word) + 'Goose!'
print(phrase)
Python
Hello!Hello!Hello!Hello!
Duck, Duck, Goose!
Parameter Scope
• The parameters of a function are local variables
– i.e. They only exist within the function, even if they have the same name as a global
variable outside of the function
– Only the value of a variable is passed to the function / returned from the function
26
def dec_to_percent(num):
if num > 1:
num = '100%'
elif num < 0:
num = '0%'
else:
num = str(round(num * 100)) + '%'
return num
num = 0.235
print('Result of dec_to_percent(num):', dec_to_percent(num))
print('Value of 'num' in main program:', num)
Python
Result of dec_to_percent(num): 24%
Value of 'num' in main program: 0.235
Assigning a value to num in
the function does not change
num in the main program –
they are different variables
Returning Data from Functions
• Just as parameters allow us to pass data into a function, a return statement
allows us to return data from a function back to the code that called it
– This allows functions to remain independent of the code that calls them, passing data
in and returning the result as needed
• A return statement is quite simple: return <value>
– The value can be of any data type/structure (string, int, list…), and can be a literal
value, a value referred to by a variable, a function that will return a value…
•return 'HD'
– It can even be an expression resulting in a value:
• No need to store something in a variable before returning it!
27
•return result •return round(result, 2)
def add(num_one, num_two):
result = num_one + num_two
return result
Python def add(num_one, num_two):
return num_one + num_two
Python
same
as
This version is more efficient!
Returning Data from Functions
• A function can contain multiple return statements
– The function will end and return the value of the first return statement that it
encounters in the function code
def get_grade(mark):
if mark >= 80:
return 'HD'
elif mark >= 70:
return 'D'
elif mark >= 60:
return 'CR'
elif mark >= 50:
return 'P'
else:
return 'F'
Python
Define ā€œget_gradeā€ function, receives mark parameter
If mark is >= 80
Return 'HD'
Otherwise, if mark is >= 70
Return 'D'
Otherwise, if mark is >= 60
Return 'CR'
Otherwise, if mark is >= 50
Return 'P'
Otherwise
Return 'F'
Pseudocode
28
Returning Data from Functions
• A function that returns a result can be used in your code wherever using a value
of that type would be valid
– When a line of code is executed, any functions in it are executed and the returned
values take the place of the function calls
• Returning a float:
• Returning a boolean:
• Returning a list:
Remember: Functions return values, not variables. It is up to you to use the value as needed!
for uname in ['jbloggs', 'bsmith', 'fwoods']:
print('Username:', uname)
if True:
print('Login Successful.')
else:
print('Invalid credentials.')
discountedTotal = 299.75 * 0.75
if check_credentials(uname, pword):
print('Login Successful.')
else:
print('Invalid credentials.')
Python
discounted_total = total(price, qty) * 0.75 Python
for uname in get_user_list():
print('Username:', uname)
Python
29
Functions Summary
• Functions allow you to abstract a process – to perform a task without needing to
know how the task is performed
– Functions should be independent of the code that calls them
• Programming languages have numerous built-in functions to perform common
tasks, and you can write your own
• Parameters allow you to pass data into a function, to specify what it should work
on or how it should do things
• Functions can return data back to the calling program
• Variables in a function have local scope
30
xkcd.com
31
Modules
Programming Language Structure
• All programming languages have the same overall structure:
– Built-In functions: Functions that are core to the language and are always available
without needing to ā€œimportā€ anything
• Python examples: print(), input(), len(), int()…
– Standard library modules: Specialised packages of functionality that are always
included with the language, but need to be imported to be used in a program
• Python examples: random, math, threading, email…
– External modules: Specialised packages of functionality that are not included with
the language and often made by third parties. Need to be downloaded and imported
• Python examples: NumPy (advanced maths), Pygame (2D games/graphics),
BeautifulSoup (XML/HTML parsing), Flask (web server)…
33
Programming Language Structure
• The ā€œStandard Libraryā€ of a programming language refers to its built-in functions
and its standard library modules
– It essentially describes the language’s capabilities ā€œout of the boxā€;
what it can do without any external modules
• Languages take different approaches regarding what should be built-in and what
should be offered as a module
– Balance of convenience/usability and necessity/compactness
34
Specialised or
General?
Needs to be
Imported?
Part of Standard
Library?
Built-In Functions General No Yes
Standard Library
Modules
Specialised Yes Yes
External Modules Specialised Yes No
Using Modules
• The terminology of ā€œmoduleā€ differs between languages:
– Library, package, extension, class…
• Regardless of whether it is part of the standard library or an external module,
a module must be ā€œimportedā€ before you can make use of its functionality
– Usually via a statement named ā€œimportā€, ā€œincludeā€ or ā€œrequireā€
– This causes the module to be loaded into memory, adding its code to your program so
that you can use the things it contains in your program
• This increases the memory usage/requirements of your program
• In some languages, you can import part of a module rather than the whole thing,
which is useful if you only need one or two specific parts of it
– How this is done varies from language to language
35
Using Modules
• Once imported, you can make use of the functionality that a module provides.
This can consist of numerous:
– Functions, performing specific tasks relevant to the module’s area
– Pre-defined variables, defining values that are useful / relevant to the module and
giving them user-friendly names – these are often read-only ā€œconstantsā€
– Classes (Object Oriented Programming), a combination of variables and functions
representing specific ā€œentitiesā€ – covered in Module 8
• For example, the math module in Python includes:
– Functions math.ceil(), math.sin(), math.sqrt()…
– Variables math.pi and math.e
36
import math
math.ceil(2.5)
3
math.pi
3.141592653589793
Python
import java.util.Scanner;
...
Scanner input = new Scanner(System.in);
String text = "";
text += input.next();
Java
External Modules
• While some external modules are written by the creators of the language,
most of them are written by users – programmers who use the language
37
User needs specific
functionality
User writes code
to achieve it
User generalises
and polishes code
User releases
module to public
– Modules typically begin as a need for a piece
of functionality that is not available
– The initial code may just solve the specific
problem/need - made for individual purpose
– To make it more useful to others, the code is
expanded, generalised and polished
– It is then released to the public as a module,
making the functionality available to all
External Modules
• The breadth and quality of a language’s external modules depends upon the size
and activity of its community/users
– A mature, popular and well-established language is likely to have a large repository of
high quality external modules
– A new and not widely used language may not have many
• Some languages have online repositories of external modules to help people find
what they are looking for, e.g.:
– Python: https://pypi.python.org/pypi (downloadable via the ā€œpipā€ tool)
– C++: http://www.boost.org/
– Java: http://search.maven.org/
• Despite these repositories, you are likely to find yourself searching Google for what you
need to see if there is a module that can help you!
38
– PHP: http://pecl.php.net/
– Perl: http://www.cpan.org/
External Modules
• Consider these things when using external modules:
– They may have been coded for an earlier or later version of the programming
language you are using
• Is it compatible with the version you are using?
• Is it still needed/relevant in your version?
– They are not necessarily as well coded, tested or maintained as the language’s
standard library
• Are there bugs? Is the code efficient?
• Are there potential security vulnerabilities?
Even popular and widely-used modules
can have significant security vulnerabilities
39
Python’s Standard Library & the ā€œmathā€ Module
• Python has quite a comprehensive standard library
– Documentation for it is at https://docs.python.org/3/library/
• This encompasses built-in functions and standard modules
– There are standard library modules for a great many things:
• Interacting with the OS, file compression, threading, networking, Internet stuff, multimedia,
GUIs, email, many data/file formats…
• The math module
– Defines variables math.pi and math.e, and numerous useful mathematical
functions. Some examples:
math.sqrt(49)
7.0
math.pow(2, 4)
16.0
Python
math.pi
3.141592653589793
math.floor(math.pi)
3
Python
40
The ā€œrandomā€ Module
• The random module
– random.random() returns a random floating point number between 0 and 1, e.g.
0.25181160914155465
• This is the most basic random function, and is used in many of the more convenient ones
– random.randint(min, max) returns a random integer between min and max
– random.choice(sequence) returns one item at random from sequence (which
can be a list, tuple, string, etc)
– random.sample(sequence, num) chooses num different items at random from
sequence and returns them as a list
– random.shuffle(sequence_variable) randomly shuffles the items in
sequence_variable (actually changes the variable itself)
41
Some Other Modules
• The ā€œtimeā€, ā€œdatetimeā€ and ā€œcalendarā€ modules
– Additional data types and classes for date/time related things
– Date formatting, manipulation, comparison, validation, etc.
• The ā€œosā€, ā€œsysā€ and ā€œshutilā€ modules
– Interacting with the operating system (OS), users, processes and the file system
– Some things are OS dependent (e.g. only work on Unix)
Large and complex programs are
likely to use many modules
43
Creating a Module
• Creating your own module is simple, and it can be an effective way of reusing
your functions between programs
1. Create file containing the function definitions, variables and anything else that you
want the module to contain
• The file should not do anything; it just defines things to be used
2. Save the file with a filename that doesn’t conflict with existing modules or Python
keywords
• The name should reflect the purpose/functionality of the module
3. Place the file in the same folder as the file you want to import it in, or in the ā€œLibā€
folder of your Python installation folder
4. Import the module by its filename (without the ā€œ.pyā€)
• e.g. convert.py would be imported with import convert
44
Creating a Module
• convert.py defines some variables for the number of millimetres in Imperial units,
and defines some functions to convert Metric units to Imperial units
45
MM_IN_INCH = 25.4
MM_IN_FOOT = 304.8
MM_IN_YARD = 914.4
MM_IN_MILE = 1609344
def cm_to_inches(cm):
return cm * 0.393
def m_to_feet(m):
return m * 3.281
def m_to_yards(m):
return m * 1.094
def km_to_miles(km):
return km * 0.621
Python
convert.py
import convert
print('20 metres is', convert.m_to_feet(20),
'feet.')
20 metres is 65.62 feet.
print('4 miles is', convert.MM_IN_MILE * 4,
'millimetres.')
4 miles is 6437376 millimetres.
Python
– This program imports the module and
uses functions and variables from it
Conclusion
• Functions allow you to abstract a process
– Should be independent of code that calls them, receiving data via parameters and
returning results via return statements
– Languages have built-in functions, or you can write your own
– Variables in a function have local scope
• Modules are packages of functionality that expand a language’s capabilities in a
specific area
– The Standard Library of a language encompasses all of the built-in and standard
modules that the language comes with
– External modules can further expand the capabilities
– Modules typically contain functions, variables and classes
46
Ad

More Related Content

Similar to ProgFund_Lecture_4_Functions_and_Modules-1.pdf (20)

(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
Nico Ludwig
Ā 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptx
NileshBorkar12
Ā 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
leavatin
Ā 
Functions in c
Functions in cFunctions in c
Functions in c
reshmy12
Ā 
Python basics
Python basicsPython basics
Python basics
Hoang Nguyen
Ā 
Python basics
Python basicsPython basics
Python basics
Harry Potter
Ā 
Python basics
Python basicsPython basics
Python basics
Fraboni Ec
Ā 
Python basics
Python basicsPython basics
Python basics
James Wong
Ā 
Python basics
Python basicsPython basics
Python basics
Tony Nguyen
Ā 
Python basics
Python basicsPython basics
Python basics
Luis Goldster
Ā 
Python basics
Python basicsPython basics
Python basics
Young Alista
Ā 
ch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdfch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdf
zafar578075
Ā 
Functions in Python and its types for beginners
Functions in Python and its types for beginnersFunctions in Python and its types for beginners
Functions in Python and its types for beginners
Mohammad Usman
Ā 
Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpu
Dhaval Jalalpara
Ā 
3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........
mxdsnaps
Ā 
Intro in understanding to C programming .pptx
Intro in understanding to C   programming .pptxIntro in understanding to C   programming .pptx
Intro in understanding to C programming .pptx
abadinasargie
Ā 
Intro in understanding to C programming .pptx
Intro in understanding to C   programming .pptxIntro in understanding to C   programming .pptx
Intro in understanding to C programming .pptx
abadinasargie
Ā 
functions _
functions                                 _functions                                 _
functions _
SwatiHans10
Ā 
Python Programming - II. The Basics
Python Programming - II. The BasicsPython Programming - II. The Basics
Python Programming - II. The Basics
Ranel Padon
Ā 
Presentation c++
Presentation c++Presentation c++
Presentation c++
JosephAlex21
Ā 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
Nico Ludwig
Ā 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptx
NileshBorkar12
Ā 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
leavatin
Ā 
Functions in c
Functions in cFunctions in c
Functions in c
reshmy12
Ā 
Python basics
Python basicsPython basics
Python basics
Hoang Nguyen
Ā 
Python basics
Python basicsPython basics
Python basics
Harry Potter
Ā 
Python basics
Python basicsPython basics
Python basics
Fraboni Ec
Ā 
Python basics
Python basicsPython basics
Python basics
James Wong
Ā 
Python basics
Python basicsPython basics
Python basics
Tony Nguyen
Ā 
Python basics
Python basicsPython basics
Python basics
Young Alista
Ā 
ch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdfch-3 funtions - 1 class 12.pdf
ch-3 funtions - 1 class 12.pdf
zafar578075
Ā 
Functions in Python and its types for beginners
Functions in Python and its types for beginnersFunctions in Python and its types for beginners
Functions in Python and its types for beginners
Mohammad Usman
Ā 
Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpu
Dhaval Jalalpara
Ā 
3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........3-Python Functions.pdf in simple.........
3-Python Functions.pdf in simple.........
mxdsnaps
Ā 
Intro in understanding to C programming .pptx
Intro in understanding to C   programming .pptxIntro in understanding to C   programming .pptx
Intro in understanding to C programming .pptx
abadinasargie
Ā 
Intro in understanding to C programming .pptx
Intro in understanding to C   programming .pptxIntro in understanding to C   programming .pptx
Intro in understanding to C programming .pptx
abadinasargie
Ā 
functions _
functions                                 _functions                                 _
functions _
SwatiHans10
Ā 
Python Programming - II. The Basics
Python Programming - II. The BasicsPython Programming - II. The Basics
Python Programming - II. The Basics
Ranel Padon
Ā 
Presentation c++
Presentation c++Presentation c++
Presentation c++
JosephAlex21
Ā 

More from lailoesakhan (8)

ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdfProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
lailoesakhan
Ā 
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdfProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
lailoesakhan
Ā 
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdfProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
lailoesakhan
Ā 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
lailoesakhan
Ā 
ProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdfProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdf
lailoesakhan
Ā 
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdfProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
lailoesakhan
Ā 
ProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdfProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdf
lailoesakhan
Ā 
ProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdfProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdf
lailoesakhan
Ā 
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdfProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
lailoesakhan
Ā 
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdfProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
ProgFund_Lecture_2_Data_Types_and_Selection-1.pdf
lailoesakhan
Ā 
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdfProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
lailoesakhan
Ā 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
lailoesakhan
Ā 
ProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdfProgFund_Lecture_7_Intro_C_Sequence.pdf
ProgFund_Lecture_7_Intro_C_Sequence.pdf
lailoesakhan
Ā 
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdfProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
ProgFund_Lecture_5_Recap_and_Case_Study-1.pdf
lailoesakhan
Ā 
ProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdfProgFund_Lecture_1_Introduction_to_Programming.pdf
ProgFund_Lecture_1_Introduction_to_Programming.pdf
lailoesakhan
Ā 
ProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdfProgFund_Lecture7_Programming_Algorithm.pdf
ProgFund_Lecture7_Programming_Algorithm.pdf
lailoesakhan
Ā 
Ad

Recently uploaded (20)

Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
Ā 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
Ā 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
Ā 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
Ā 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
Ā 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
Ā 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
Ā 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
Ā 
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxbMain cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
SunilSingh610661
Ā 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
Ā 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
Ā 
Artificial Intelligence introduction.pptx
Artificial Intelligence introduction.pptxArtificial Intelligence introduction.pptx
Artificial Intelligence introduction.pptx
DrMarwaElsherif
Ā 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
Ā 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
Ā 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
Ā 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
Ā 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
Ā 
New Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdfNew Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdf
mohamedezzat18803
Ā 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
Ā 
Data Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptxData Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptx
RushaliDeshmukh2
Ā 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
Ā 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
Ā 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
Ā 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
Ā 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
Ā 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
Ā 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
Ā 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
Ā 
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxbMain cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
SunilSingh610661
Ā 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
Ā 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
Ā 
Artificial Intelligence introduction.pptx
Artificial Intelligence introduction.pptxArtificial Intelligence introduction.pptx
Artificial Intelligence introduction.pptx
DrMarwaElsherif
Ā 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
Ā 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
Ā 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
Ā 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
Ā 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
Ā 
New Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdfNew Microsoft PowerPoint Presentation.pdf
New Microsoft PowerPoint Presentation.pdf
mohamedezzat18803
Ā 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
Ā 
Data Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptxData Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptx
RushaliDeshmukh2
Ā 
Ad

ProgFund_Lecture_4_Functions_and_Modules-1.pdf

  • 1. Programming Fundamentals Lecture 4: Functions and Modules
  • 2. This Lecture • Functions – Built in functions – Concept of process abstraction – Writing functions – Scope, parameters and return values • Modules – Programming language structure – Modules – External modules – Python’s standard library – The ā€œmathā€, ā€œrandomā€ and other modules – Creating a module 2
  • 3. Textbook • Starting Out with Python, 4th Edition (Global) – Tony Gaddis • Reading the chapter(s) is required – Read the indicated chapter(s) before class • This week covers the following textbook chapter(s): – Chapter 5 – Functions • Entire chapter 3
  • 5. Built-In Functions • Throughout the unit, we have made use of numerous functions that are part of the Python language • Some of them have been built-in functions, e.g. – input() and print() for input and output – int(), float() and str() to convert data types – len(), sum(), min() and max() with data structures • Some of them are specific to certain data types/structures, e.g. – Strings (str.isupper(), str.lower(), str.count()…) – Lists (list.append(), list.sort(), list.index()…) • Some of them are only available as part of a module that you need to import, e.g. random.randint() 5
  • 6. Built-In Functions • Different languages offer different functions, often specialising in areas that the language is intended for • Some languages offer lots of built-in functions, others do not – A language without many functions requires you to write more code to achieve useful things, but there is less to remember – A language with lots of functions can allow you to write concise code, but you need to find/remember the functions • Groups of functions relating to a specialised task or concept (e.g. generating or working with random values) are often stored in modules – If the functions are needed, they can be ā€œimportedā€ (included) in the program – This helps to keep programs small and efficient by not weighing them down with things they probably won’t need 6
  • 7. Process Abstraction • Functions serve to abstract a process – they give you a way of performing a task without needing to know the details of how that task is done – We use the concept of process abstraction every day: • You don’t need to know how an elevator works, just that you get in and press a button to be taken to the specified floor • You don’t need to know how a car’s accelerator works, just that you press it to make the car go faster • e.g. All you need to know to use the sum() function is that if you pass it a list of numbers, it will return the total of them – Name of function – Data to pass to it (input) – Expected result (output) Input Output Function (Process) 7
  • 8. Writing Your Own Functions • All languages allow you to define your own functions – This becomes extremely useful as you start to write longer and more complex programs, for a number of reasons: • Code Reuse: A function can be written to perform a task, and then called as many times as needed throughout the program – no need to write the same/similar code multiple times • More Readable Code: It’s easier to read and understand a meaningful function name than a large sequence of statements • Better Testing: Self-contained functions with known parameters and return values make testing code easier • Faster Development: Functions can be reused between different programs or parts of a program, saving a lot of time • Easier Teamwork: Functions separate sections of code in a way that makes it easy to divide work between different people 8
  • 9. Writing Your Own Functions • Functions should ideally have these general characteristics: – A function should perform a well-defined task or process – Data the function needs should be passed in via parameters – If the function produces a result, it should return the result – Code inside a function should be independent of calling code • Functions should be ā€œmodularā€, with clear input and output – The output of a function may become an input of another function • While many languages allow you to break these ideals, you should always try to stick to them to ensure that you are creating worthwhile functions – Most of the benefits on the previous slide are only likely to be seen or maximised if these ideals are upheld, while poorly-conceived functions can worsen a program 9
  • 10. Declaring a Function • A function ā€œdeclarationā€ or ā€œdefinitionā€ is the code which defines a function so that it can be used (ā€œcalledā€) later on – This involves specifying a function name, details of any parameters that can be passed to it, and the lines of code that the function performs when it is called – The code may include return statements to return a result back to the program – The code is not run at this time – you are just defining the function – General format of a function declaration in most languages: function <function name>(<parameters>) { <function body> } Declare functions at the start of a program, and then call them where they’re needed 10
  • 11. Declaring a Function • Let’s design and implement a function named ā€œrepeatā€, that: – Receives two parameters (i.e. You must specify two values when calling it): • ā€œtextā€ - A string (what you want to repeat) • ā€œcountā€ – An integer (how many times to repeat it) – Returns a string of ā€œtextā€ repeated ā€œcountā€ times • i.e. The result of the function is a string consisting of ā€œtextā€, repeated ā€œcountā€ times • e.g. calling repeat('Bang!', 3) should return a string of 'Bang!Bang!Bang!' • Note: The function returns the string – it doesn’t print the string – We have covered what we need to implement this function: • A for loop to repeat a certain number of times… • Concatenation to join strings together… 11
  • 12. Declaring a Function • Here is pseudocode of a suitable design for the function: • Here it is in code: Define ā€œrepeatā€ function (receives ā€œtextā€ and ā€œcountā€) Set ā€œresultā€ to an empty string Repeat ā€œcountā€ times Concatenate ā€œtextā€ to the end of ā€œresultā€ Return ā€œresultā€ Pseudocode def repeat(text, count): result = '' for num in range(count): result = result + text return result print( repeat('Hello!', 4) ) Python Hello!Hello!Hello!Hello! This code only declares the function, making it so that you can now call it in subsequent code. 12
  • 13. Declaring a Function in Python • Declaring a function in Python uses the keyword ā€œdefā€, and uses a colon and indentation rather than curly brackets: def <function name>(<parameters>): <function body> • Example in Python: • Note: Python doesn’t need a function to do this, since you can simply multiply strings and integers, e.g. 'Hello!' * 4, to repeat a string… def repeat(text, count): result = '' for num in range(count): result = result + text return result print( repeat('Hello!', 4) ) Python Hello!Hello!Hello!Hello! 15
  • 14. Side Note: Common Syntax Structures • Hopefully as you learn more and more programming concepts, you’ll start to see the similarities - The structure of different statements are often very similar… Most Languages if (<boolean expression>) { <true code> } while (<boolean expression>) { <loop body> } function <function name>(<parameters>) { <function body> } Python if <boolean expression>: <true code> while <boolean expression>: <loop body> def <function name>(<parameters>): <function body> 16
  • 15. • We’ve used pseudocode and flowcharts to illustrate the flow of programs and their control structures throughout the unit – When a step of your program involves using one of your functions, refer to it by name in the pseudocode, e.g. ā€œCall get_total function and store result as totalā€ – Function calls in flowcharts are represented using this shape: • A separate section of pseudocode or separate flowchart should be created to illustrate the definition/body of each function – This allows pseudocode and flowcharts to remain concise and easy to follow (which is exactly what functions do to the program itself!) – Think of pseudocode for functions as appendices of a book – they don’t get in the way of the main text, but they’re there for you to refer to if you need more information Functions in Pseudocode and Flowcharts 17
  • 16. Functions in Flowcharts Prompt for mark get_grade(mark) Add mark to total Show grade Show avg grade Calculate avg mark While True True get_grade(avg) get_grade(num) If num >= 80 Set grade to HD Set grade to F True False If num >= 70 Set grade to D True Enter function Return grade If num >= 60 Set grade to CR True False If num >= 50 Set grade to P True False False If mark == x True False Break out of loop Start program End program 18
  • 17. import random def check_credentials(username, password): if username == 'admin' and password == 'abc123': return True else: return False def generate_randoms(): number = random.randint(1, 100) letter = random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ') print('Your number is', number) print('Your letter is', letter) print('Please Log In.') uname = input('Username: ') pword = input('Password: ') if check_credentials(uname, pword): print('Login Successful.') generate_randoms() else: print('Invalid credentials.') Python Flow of Control in a Program with Functions Please Log In. Username: Password: Login Successful. Your number is 45 Your letter is S admin abc123 ā‘  ā‘” ā‘¢ ⑤ ā‘„ ⑦ ā‘§ ⑨ ā‘£ 19
  • 18. Scope, Parameters and Return Values
  • 19. Scope and Local Variables • A variable’s ā€œscopeā€ is the part of a program in which it exists and can be referred to – generally, this is ā€œfrom when it is created, until the program ends/it is deletedā€ • A variable that is created inside a function is known as a ā€œlocal variableā€ and its scope is limited to that function – i.e. You cannot access the variable from outside the function – When a function ends (reaches the end of its code or reaches a return statement) after being called, any local variables that were defined inside it cease to exist def example(): local_var = 'Hello!' print('Printing from inside function:', local_var) example() # prints as expected print('Printing from outside function:', local_var) # causes error Python 21
  • 20. Scope and Global Variables • Variables created outside of a function (i.e. directly in the main part of a program) are known as ā€œglobal variablesā€ – Global variables can be (but shouldn’t be) accessed from any function: – Trying to assign a value to a global variable will create a local variable instead, unless declared as a global in the function… As you can see, this gets very confusing: def example(): print('var in funct:', var) var = 'A' example() # var is NOT passed in as a parameter print('var in global:', var) Python var in funct: A var in global: A def example(): global var var = 'B' print('var in funct:', var) var = 'A' example() print('var in global:', var) Python var in funct: B var in global: B def example(): var = 'B' print('var in funct:', var) var = 'A' example() print('var in global:', var) Python var in funct: B var in global: A 22
  • 21. Scope and Global Variables • Different languages use slightly different rules regarding variable scope and access to global variables • You should avoid referring to global variables from inside functions – Use parameters to pass data into a function if needed • Using global variables in functions is discouraged since: – It prevents functions from being independent of the code that calls them, making them harder to reuse in other programs – It makes errors hard to track down, since a variable’s value may be changed from anywhere in the program – It makes programs hard to follow and understand 23
  • 22. Parameters • When you define a function, you can define its parameters – This defines what data can be passed in to the function when it is called in your code – Hence, a function can be instructed to perform its task on the data you give it, or in a particular way (or both) – If a function does not need any data/instructions, it may have no parameters (rare) • e.g. The built-in function round() can take two parameters: – A number to round, and a number of digits to round it to, e.g. round(9.24574, 2) returns 9.25 – The first parameter is required (since it makes no sense to call the function without it), but the second one is optional in this case • If omitted, the function rounds the value to the nearest integer, e.g. round(9.24574) returns 9 24
  • 23. Parameters • The parameter names you specify when defining a function become local variables in the function when it is called – Their values will be provided when the function is called • These can be literal values or the values of variables from outside the function – A parameter can be made optional by giving it a default value • You must provide a value for each non-optional parameter 25 def repeat(text, count = 2): result = '' for num in range(count): result = result + text return result print(repeat('Hello!', 4)) word = 'Duck, ' phrase = repeat(word) + 'Goose!' print(phrase) Python Hello!Hello!Hello!Hello! Duck, Duck, Goose!
  • 24. Parameter Scope • The parameters of a function are local variables – i.e. They only exist within the function, even if they have the same name as a global variable outside of the function – Only the value of a variable is passed to the function / returned from the function 26 def dec_to_percent(num): if num > 1: num = '100%' elif num < 0: num = '0%' else: num = str(round(num * 100)) + '%' return num num = 0.235 print('Result of dec_to_percent(num):', dec_to_percent(num)) print('Value of 'num' in main program:', num) Python Result of dec_to_percent(num): 24% Value of 'num' in main program: 0.235 Assigning a value to num in the function does not change num in the main program – they are different variables
  • 25. Returning Data from Functions • Just as parameters allow us to pass data into a function, a return statement allows us to return data from a function back to the code that called it – This allows functions to remain independent of the code that calls them, passing data in and returning the result as needed • A return statement is quite simple: return <value> – The value can be of any data type/structure (string, int, list…), and can be a literal value, a value referred to by a variable, a function that will return a value… •return 'HD' – It can even be an expression resulting in a value: • No need to store something in a variable before returning it! 27 •return result •return round(result, 2) def add(num_one, num_two): result = num_one + num_two return result Python def add(num_one, num_two): return num_one + num_two Python same as This version is more efficient!
  • 26. Returning Data from Functions • A function can contain multiple return statements – The function will end and return the value of the first return statement that it encounters in the function code def get_grade(mark): if mark >= 80: return 'HD' elif mark >= 70: return 'D' elif mark >= 60: return 'CR' elif mark >= 50: return 'P' else: return 'F' Python Define ā€œget_gradeā€ function, receives mark parameter If mark is >= 80 Return 'HD' Otherwise, if mark is >= 70 Return 'D' Otherwise, if mark is >= 60 Return 'CR' Otherwise, if mark is >= 50 Return 'P' Otherwise Return 'F' Pseudocode 28
  • 27. Returning Data from Functions • A function that returns a result can be used in your code wherever using a value of that type would be valid – When a line of code is executed, any functions in it are executed and the returned values take the place of the function calls • Returning a float: • Returning a boolean: • Returning a list: Remember: Functions return values, not variables. It is up to you to use the value as needed! for uname in ['jbloggs', 'bsmith', 'fwoods']: print('Username:', uname) if True: print('Login Successful.') else: print('Invalid credentials.') discountedTotal = 299.75 * 0.75 if check_credentials(uname, pword): print('Login Successful.') else: print('Invalid credentials.') Python discounted_total = total(price, qty) * 0.75 Python for uname in get_user_list(): print('Username:', uname) Python 29
  • 28. Functions Summary • Functions allow you to abstract a process – to perform a task without needing to know how the task is performed – Functions should be independent of the code that calls them • Programming languages have numerous built-in functions to perform common tasks, and you can write your own • Parameters allow you to pass data into a function, to specify what it should work on or how it should do things • Functions can return data back to the calling program • Variables in a function have local scope 30
  • 31. Programming Language Structure • All programming languages have the same overall structure: – Built-In functions: Functions that are core to the language and are always available without needing to ā€œimportā€ anything • Python examples: print(), input(), len(), int()… – Standard library modules: Specialised packages of functionality that are always included with the language, but need to be imported to be used in a program • Python examples: random, math, threading, email… – External modules: Specialised packages of functionality that are not included with the language and often made by third parties. Need to be downloaded and imported • Python examples: NumPy (advanced maths), Pygame (2D games/graphics), BeautifulSoup (XML/HTML parsing), Flask (web server)… 33
  • 32. Programming Language Structure • The ā€œStandard Libraryā€ of a programming language refers to its built-in functions and its standard library modules – It essentially describes the language’s capabilities ā€œout of the boxā€; what it can do without any external modules • Languages take different approaches regarding what should be built-in and what should be offered as a module – Balance of convenience/usability and necessity/compactness 34 Specialised or General? Needs to be Imported? Part of Standard Library? Built-In Functions General No Yes Standard Library Modules Specialised Yes Yes External Modules Specialised Yes No
  • 33. Using Modules • The terminology of ā€œmoduleā€ differs between languages: – Library, package, extension, class… • Regardless of whether it is part of the standard library or an external module, a module must be ā€œimportedā€ before you can make use of its functionality – Usually via a statement named ā€œimportā€, ā€œincludeā€ or ā€œrequireā€ – This causes the module to be loaded into memory, adding its code to your program so that you can use the things it contains in your program • This increases the memory usage/requirements of your program • In some languages, you can import part of a module rather than the whole thing, which is useful if you only need one or two specific parts of it – How this is done varies from language to language 35
  • 34. Using Modules • Once imported, you can make use of the functionality that a module provides. This can consist of numerous: – Functions, performing specific tasks relevant to the module’s area – Pre-defined variables, defining values that are useful / relevant to the module and giving them user-friendly names – these are often read-only ā€œconstantsā€ – Classes (Object Oriented Programming), a combination of variables and functions representing specific ā€œentitiesā€ – covered in Module 8 • For example, the math module in Python includes: – Functions math.ceil(), math.sin(), math.sqrt()… – Variables math.pi and math.e 36 import math math.ceil(2.5) 3 math.pi 3.141592653589793 Python import java.util.Scanner; ... Scanner input = new Scanner(System.in); String text = ""; text += input.next(); Java
  • 35. External Modules • While some external modules are written by the creators of the language, most of them are written by users – programmers who use the language 37 User needs specific functionality User writes code to achieve it User generalises and polishes code User releases module to public – Modules typically begin as a need for a piece of functionality that is not available – The initial code may just solve the specific problem/need - made for individual purpose – To make it more useful to others, the code is expanded, generalised and polished – It is then released to the public as a module, making the functionality available to all
  • 36. External Modules • The breadth and quality of a language’s external modules depends upon the size and activity of its community/users – A mature, popular and well-established language is likely to have a large repository of high quality external modules – A new and not widely used language may not have many • Some languages have online repositories of external modules to help people find what they are looking for, e.g.: – Python: https://pypi.python.org/pypi (downloadable via the ā€œpipā€ tool) – C++: http://www.boost.org/ – Java: http://search.maven.org/ • Despite these repositories, you are likely to find yourself searching Google for what you need to see if there is a module that can help you! 38 – PHP: http://pecl.php.net/ – Perl: http://www.cpan.org/
  • 37. External Modules • Consider these things when using external modules: – They may have been coded for an earlier or later version of the programming language you are using • Is it compatible with the version you are using? • Is it still needed/relevant in your version? – They are not necessarily as well coded, tested or maintained as the language’s standard library • Are there bugs? Is the code efficient? • Are there potential security vulnerabilities? Even popular and widely-used modules can have significant security vulnerabilities 39
  • 38. Python’s Standard Library & the ā€œmathā€ Module • Python has quite a comprehensive standard library – Documentation for it is at https://docs.python.org/3/library/ • This encompasses built-in functions and standard modules – There are standard library modules for a great many things: • Interacting with the OS, file compression, threading, networking, Internet stuff, multimedia, GUIs, email, many data/file formats… • The math module – Defines variables math.pi and math.e, and numerous useful mathematical functions. Some examples: math.sqrt(49) 7.0 math.pow(2, 4) 16.0 Python math.pi 3.141592653589793 math.floor(math.pi) 3 Python 40
  • 39. The ā€œrandomā€ Module • The random module – random.random() returns a random floating point number between 0 and 1, e.g. 0.25181160914155465 • This is the most basic random function, and is used in many of the more convenient ones – random.randint(min, max) returns a random integer between min and max – random.choice(sequence) returns one item at random from sequence (which can be a list, tuple, string, etc) – random.sample(sequence, num) chooses num different items at random from sequence and returns them as a list – random.shuffle(sequence_variable) randomly shuffles the items in sequence_variable (actually changes the variable itself) 41
  • 40. Some Other Modules • The ā€œtimeā€, ā€œdatetimeā€ and ā€œcalendarā€ modules – Additional data types and classes for date/time related things – Date formatting, manipulation, comparison, validation, etc. • The ā€œosā€, ā€œsysā€ and ā€œshutilā€ modules – Interacting with the operating system (OS), users, processes and the file system – Some things are OS dependent (e.g. only work on Unix) Large and complex programs are likely to use many modules 43
  • 41. Creating a Module • Creating your own module is simple, and it can be an effective way of reusing your functions between programs 1. Create file containing the function definitions, variables and anything else that you want the module to contain • The file should not do anything; it just defines things to be used 2. Save the file with a filename that doesn’t conflict with existing modules or Python keywords • The name should reflect the purpose/functionality of the module 3. Place the file in the same folder as the file you want to import it in, or in the ā€œLibā€ folder of your Python installation folder 4. Import the module by its filename (without the ā€œ.pyā€) • e.g. convert.py would be imported with import convert 44
  • 42. Creating a Module • convert.py defines some variables for the number of millimetres in Imperial units, and defines some functions to convert Metric units to Imperial units 45 MM_IN_INCH = 25.4 MM_IN_FOOT = 304.8 MM_IN_YARD = 914.4 MM_IN_MILE = 1609344 def cm_to_inches(cm): return cm * 0.393 def m_to_feet(m): return m * 3.281 def m_to_yards(m): return m * 1.094 def km_to_miles(km): return km * 0.621 Python convert.py import convert print('20 metres is', convert.m_to_feet(20), 'feet.') 20 metres is 65.62 feet. print('4 miles is', convert.MM_IN_MILE * 4, 'millimetres.') 4 miles is 6437376 millimetres. Python – This program imports the module and uses functions and variables from it
  • 43. Conclusion • Functions allow you to abstract a process – Should be independent of code that calls them, receiving data via parameters and returning results via return statements – Languages have built-in functions, or you can write your own – Variables in a function have local scope • Modules are packages of functionality that expand a language’s capabilities in a specific area – The Standard Library of a language encompasses all of the built-in and standard modules that the language comes with – External modules can further expand the capabilities – Modules typically contain functions, variables and classes 46