0% found this document useful (0 votes)
34 views

Lecture 7 Functions PartI

Functions allow programmers to organize code into reusable blocks. Functions take parameters as input and can return values. Variables declared inside functions are local, while variables declared outside are global and can be accessed anywhere. Functions improve modularity, readability, and extensibility of code.

Uploaded by

thezynkofficial
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Lecture 7 Functions PartI

Functions allow programmers to organize code into reusable blocks. Functions take parameters as input and can return values. Variables declared inside functions are local, while variables declared outside are global and can be accessed anywhere. Functions improve modularity, readability, and extensibility of code.

Uploaded by

thezynkofficial
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Principles of programming

languages
Functions- Part I
Today…
• Last Session:
• Basic Elements of Python Programs

• Today’s Session:
• Functions- Part I:
• Why using functions?
• Formal definition, parameters, local and global scopes of variables, return values, and
pass-by-value
Multiple-line Snippets and Functions
• So far, we have been using only one-line snippets in the interactive
mode, but we may want to go beyond that and execute an entire
sequence of statements

• Python allows putting a sequence of statements together to create a


brand-new command or function
>>> def hello():
These indentations are necessary to ... print("Hello")
indicate that these two statements ... print("Programming is fun!")
belong to the same block of code, ...
which belongs to this function >>>
Indentations Are Mandatory
• If indentations are not provided, an error will be generated

>>> def hello():


... print("Hello")
File "<stdin>", line 2
print("Hello")
^
IndentationError: expected an indented block
>>>
Invoking Functions
• After defining a function, we can call (or invoke) it by typing its name
followed by parentheses

>>> def hello():


This is how we invoke our
... print("Hello")
defined function hello(); ... print("Programming is fun!")
notice that the two print ...
statements (which form one >>> hello()
code block) were executed Hello
in sequence! Programming is fun!
>>>
Invoking Functions
• Invoking a function without parentheses will NOT generate an error,
but rather the location (address) in computer memory where the
function definition has been stored

>>> def hello():


... print("Hello")
... print("Programming is fun!")
...
>>> hello
<function hello at 0x101f1e268>
>>>
Parameters
• We can also add parameters (or arguments) to our defined functions

person is a parameter; >>> def hello(person):


it acts as an input to the ... print("Hello " + person)
function hello(…) ... print("Programming is fun!")
...
>>> hello(“Lukaku")
Hello Lukaku
Programming is fun!
>>>
Multiple Parameters
• We can add multiple parameters and not only one

>>> def hello(person, course):


... print("Hello " + person + “ from “ + course)
... print("Programming is fun!")
...
>>> hello(“Simba“, “15-110”)
Hello Simba from 15-110
Programming is fun!
>>>
Parameters with Default Values
• In addition, parameters can be assigned default values
def print_func(i, j = 100): def print_func(i, j = 100): def print_func(i, j = 100):
print(i, j) print(i, j) print(i, j)

print_func(10, 20) print_func(10) print_func()


Run

Run

Run
10 20 10 100 ERROR
Parameters vs. Arguments
• The terms parameter and argument refer to the same thing: passing
information to a function. But, there is a subtle difference between
the two.
• A parameter is the variable inside the parenthesis in a function. An
argument is the value that is passed to a function when it is called.
Modularity and Maintenance
• Consider the following code def happy():
print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday to you!") def singFred():
print("Happy birthday, dear Fred") happy()
print("Happy birthday to you!") happy()
print("Happy birthday, dear Fred")
Can we write this program with
happy()
ONLY two prints?
singFred()

More modular & maintainable– changing anything in the lyric “Happy birthday to you!”
requires making a change at only one place in happy(); thanks to the happy function!
Extensibility and Readability
• Consider the following code
print("Happy birthday to you!")
print("Happy birthday to you!") print("Happy birthday to you!")
print("Happy birthday to you!") print("Happy birthday, dear Fred")
print("Happy birthday, dear Fred") print("Happy birthday to you!")
print("Happy birthday to you!") print("Happy birthday to you!")
print("Happy birthday to you!")
What if we want to sing a verse for print("Happy birthday, dear Lucy")
Lucy right after Fred? print("Happy birthday to you!")

What if we utilize functions?


Extensibility and Readability
• Consider the following code
def happy():
print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday, dear Fred") def sing(name):
happy()
print("Happy birthday to you!")
happy()
print("Happy birthday, dear " + name)
What if we want to sing a verse for
happy()
Lucy right after Fred?
sing("Fred")
sing("Lucy")

Easy to extend, more readable, and necessitates less typing!


Formal Definition of Functions
• Formally, a function can be defined as follows:
def <name>(<formal-parameters>):
<body>
• The <name> of a function should be an identifier and <formal-parameters>
is a (possibly empty) list of variable names (also identifiers)

• <formal-parameters> and all local variables declared in a function are only


accessible in the <body> of this function

• Variables with identical names declared elsewhere in a program are distinct


from <formal-parameters> and local variables inside a function’s <body>
Local vs Global Variable
• A variable is an important and ubiquitous concept in programming.
Variables are containers for storing data.
• Variables can store many types of data, including usernames, email
addresses, and items in a user’s online game inventory.
• When programming in Python, you will encounter two types of
variables: global and local.
Global Variables
• Global variables are variables declared outside of a function. Global
variables have a global scope.
• This means that they can be accessed throughout an entire program,
including within functions. Consider the following visual
representation of this concept.
• Once we declare a global variable, we can use it throughout our code
Local Variables
• Local variables, on the other hand, are variables declared inside a
function.
• These variables are known to have local scope.
• This means they can be accessed only within the function in which
they are declared
• A local variable can only be accessed within a particular function.
Local Variables
• Consider the following code

def func1(x, y):


#local scope 234
z=4 Traceback (most recent call last):
print(x, y, z) Run File "func1.py", line 6, in <module>
print(x, y, z)
func1(2, 3) NameError: name 'x' is not defined
print(x, y, z)

x, y, and z belong solely to the scope of func1(...) and can only be accessed inside
func1(…); z is said to be local to func1(…), hence, referred to as a local variable
Global Variables
• Consider the following code
#global scope
x = 100

def func2(): 100


Run
print(x) 100

func2()
print(x)

x is said to be a global variable since it is defined within the global scope of the
program and can be, subsequently, accessed inside and outside func2()
Local vs. Global Variables
• Consider the following code

x = 100

def func3():
x = 20 20
Run
print(x) 100

func3()
print(x)

The global variable x is distinct from the local variable x inside func3()
Parameters vs. Global Variables
• Consider the following code

x = 100

def func4(x):
print(x) 20
Run
100
func4(20)
print(x)

The global variable x is distinct from the parameter x of func4(…)


The global Keyword
• Consider the following code

def func5():
global x
x = 20
print(x) 20
Run
20
func5()
print(x)

The global keyword binds variable x in the global scope; hence, can be accessed inside
and outside func5()
Getting Results From Functions
• We can get information from a function by having it return a value

>>> def square(x): >>> def cube(x): >>> def power(a, b):
... return x * x ... return x * x * x ... return a ** b
... ... ...
>>> square(3) >>> cube(3) >>> power(2, 3)
9 27 8
>>> >>> >>>
Pass By Value
• Consider the following code
>>> def addInterest(balance, rate):
... newBalance = balance * (1+rate)
... return newBalance
...
>>> def test():
... amount = 1000
... rate = 0.05
... nb = addInterest(amount, rate)
... print(nb)
...
>>> test()
1050.0
>>>
Pass By Value
• Is there a way for a function to communicate back its result without
returning it?
>>> def addInterest(balance, rate):
... newBalance = balance * rate
... balance = newBalance
...
>>> def test():
... amount = 1000
... rate = 0.05
... addInterest(amount, rate)
What will be the result? ... print(amount)
...
>>> test()
1000
>>>
Pass By Value
• Is there a way for a function to communicate back its result without
returning it?
>>> def addInterest(balance, rate):
... newBalance = balance * rate
... balance = newBalance
...
>>> def test():
... amount = 1000
... rate = 0.05
Why 1000 and NOT ... addInterest(amount, rate)
... print(amount)
1050.0? ...
>>> test()
1000
>>>
Pass By Value
• The function only receives the values of the parameters
1000
addInterest(…) gets >>> def addInterest(balance, rate):
... newBalance = balance * rate
ONLY the value of
... balance = newBalance
amount (i.e., 1000) ...
>>> def test(): Python is said to
... amount = 1000 pass parameters
... rate = 0.05
... addInterest(amount, rate) by value!
... print(amount)
...
>>> test()
1000
>>>
Pass By Value vs. Returning a Value
• Consider the following code
def increment_func(x):
def increment_func(x): x=x+1
x=x+1 return x

x=1 x=1
increment_func(x) x = increment_func(x)
print(x) print(x)
Run

Run
1 2
Python Return

• The Python return keyword exits a function and instructs Python to


continue executing the main program.
• The return keyword can send a value back to the main program. A
value could be a string, a tuple, or any other object.
• This is useful because it allows us to process data within a function.
Then, we can return the data to our main program, so we can use it
outside our function.
• Data processed within a function is only accessible within the
function. This is only the case unless you use the return statement to
send the data elsewhere in the program.
Python Return
• The return keyword can appear anywhere within a function, and
when the code executes the return statement, the function will be
exited.
• The return statement returns a value to the rest of the program, but it
can also be used alone. If no expression is defined after the return
statement, None is returned. Here’s an example of this in action:

• def example_function():
• return "Example"
More on the Print Function
• There are different forms of the print function
1) print(), which produces a blank line of output

>>> print()

>>>
More on the Print Function
• There are different forms of the print function
2) print(<expr>, <expr>, …, <expr>), which indicates that the print function can
take a sequence of expressions, separated by commas

>>> print(3+4)
7
>>> print(3, 4, 3+4)
347
>>> print("The answer is ", 3 + 4)
The answer is 7
>>> print("The answer is", 3 + 4)
The answer is 7
More on the Print Function
• There are different forms of the print function
3) print(<expr>, <expr>, …, <expr>, end = “\n”), which indicates that the print
function can be modified to have an ending text other than the default one
(i.e., \n or a new line) after all the supplied expressions are printed

>>> def answer():


Notice how we used the end ... print("The answer is:", end = " ")
parameter to allow multiple ... print(3 + 4)
prints to build up a single line ...
>>> answer()
of output!
The answer is: 7
>>>
Next Class…
• Functions- Part II

You might also like