Functions in Python: Basics and Usage

 
15-110: Principles of
Computing
 
Functions- Part I
Lecture 3, September 09, 2018
 
Mohammad Hammoud
Carnegie Mellon University in Qatar
 
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
 
Announcement:
Homework Assignment (HA) 01 is out. It is due on Thursday, Sep 13, 2018
by 10:00AM
 
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
 
 
 
 
 
 
Multiple-line Snippets and Functions
>>> def hello():
...     print("Hello")
...     print("Programming is fun!")
...
>>>
 
These 
indentations
 are necessary to
indicate that these two statements
belong to the same 
block of code
,
which belongs to this function
If indentations are not provided, an error will be generated
Indentations Are Mandatory
>>> def hello():
... print("Hello")
  File "<stdin>", line 2
    print("Hello")
        ^
IndentationError: expected an indented block
>>>
 
After defining a function, we can call (or 
invoke
) it by typing its name
followed by parentheses
 
 
 
 
 
 
Invoking Functions
>>> def hello():
...     print("Hello")
...     print("Programming is fun!")
...
>>> hello()
Hello
Programming is fun!
>>>
 
This is how we invoke our
defined function 
hello()
;
notice that the two print
statements (which form one
code 
block
) were executed
in sequence!
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  
Invoking Functions
>>> def hello():
...     print("Hello")
...     print("Programming is fun!")
...
>>> hello
<function hello at 0x101f1e268>
>>>
We can also add 
parameters
 (or 
arguments
) to our defined functions  
Parameters
>>> def hello(person):
...     print("Hello " + person)
...     print("Programming is fun!")
...
>>> hello("Mohammad")
Hello Mohammad
Programming is fun!
>>>
 
person
 is a parameter;
it acts as an 
input
 to the
function 
hello(…)
We can add multiple parameters and not only one
Multiple Parameters
>>> def hello(person, course):
...     print("Hello " + person + “ from “ + course)
...     print("Programming is fun!")
...
>>> hello("Mohammad“, “15-110”)
Hello Mohammad from 15-110
Programming is fun!
>>>
In addition, parameters can be assigned default values
Parameters with Default Values
def print_func(i, j = 100):
        print(i, j)
print_func(10, 20)
Run
10 20
def print_func(i, j = 100):
        print(i, j)
print_func(10)
Run
10 100
def print_func(i, j = 100):
        print(i, j)
print_func()
Run
 
ERROR
Consider the following code
Modularity and Maintenance
print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday, dear Fred")
print("Happy birthday to you!")
 
Can we write this program with
ONLY two 
prints?
def happy():
        print("Happy birthday to you!")
def singFred():
        happy()
        happy()
        print("Happy birthday, dear Fred")
        happy()
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!
Consider the following code
Extensibility and Readability
print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday, dear Fred")
print("Happy birthday to you!")
What if we want to sing a verse for 
Lucy right after Fred?
print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday, dear Fred")
print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday, dear Lucy")
print("Happy birthday to you!")
 
What if we utilize functions?
Consider the following code
Extensibility and Readability
print("Happy birthday to you!")
print("Happy birthday to you!")
print("Happy birthday, dear Fred")
print("Happy birthday to you!")
def happy():
        print("Happy birthday to you!")
def sing(name):
        happy()
        happy()
        print("Happy birthday, dear " + name)
        happy()
sing("Fred")
sing("Lucy")
Easy to 
extend
, more
 
readable
,
 
and necessitates 
less typing!
What if we want to sing a verse for 
Lucy right after Fred?
 
Formally, a function can be defined as follows:
 
 
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>
 
 
 
 
 
Formal Definition of Functions
 
def
 
<name>
(
<formal-parameters>
)
:
 
<body>
 
Consider the following code
 
 
 
 
 
Local Variables
def func1(x, y):
        #local scope
        z = 4
        print(x, y, z)
func1(2, 3)
print(x, y, z)
Run
2 3 4
Traceback (most recent call last):
  File "func1.py", line 6, in <module>
    print(x, y, z)
NameError: name 'x' is not defined
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
 
Consider the following code
 
 
 
 
 
Global Variables
#global scope
x = 100
def func2():
        print(x)
func2()
print(x)
Run
100
100
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()
Consider the following code
Local vs. Global Variables
x = 100
def func3():
        x = 20
        print(x)
func3()
print(x)
Run
20
100
The global variable x is distinct from the local variable x inside func3()
Consider the following code
Parameters vs. Global Variables
x = 100
def func4(x):
        print(x)
func4(20)
print(x)
Run
20
100
The global variable x is distinct from the parameter x of func4(…)
Consider the following code
The global Keyword
def func5():
        global x
        x = 20
        print(x)
func5()
print(x)
Run
20
20
The 
global 
keyword
 
binds
 variable x in the global scope; hence, can be accessed inside
and outside func5()
We can get information from a function by having it 
return
 a value
Getting Results From Functions
>>> def square(x):
...     
return
 x * x
...
>>> square(3)
9
>>>
>>> def cube(x):
...     
return
 x * x * x
...
>>> cube(3)
27
>>>
>>> def power(a, b):
...     
return 
a ** b
...
>>> power(2, 3)
8
>>>
 
Consider the following code
 
 
 
 
 
Pass By Value
>>> 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
>>>
Is there a way for a function to communicate back its result without
returning it?
Pass By Value
>>> def addInterest(balance, rate):
...     newBalance = balance * rate
...     balance = newBalance
...
>>> def test():
...     amount = 1000
...     rate = 0.05
...     addInterest(amount, rate)
...     print(amount)
...
>>> test()
1000
>>>
 
What will be the result?
Is there a way for a function to communicate back its result without
returning it?
Pass By Value
>>> def addInterest(balance, rate):
...     newBalance = balance * rate
...     balance = newBalance
...
>>> def test():
...     amount = 1000
...     rate = 0.05
...     addInterest(amount, rate)
...     print(amount)
...
>>> test()
1000
>>>
 
Why 1000 and NOT
1050.0?
The function only receives the 
values
 of the parameters
Pass By Value
>>> def addInterest(balance, rate):
...     newBalance = balance * rate
...     balance = newBalance
...
>>> def test():
...     amount = 1000
...     rate = 0.05
...     addInterest(amount, rate)
...     print(amount)
...
>>> test()
1000
>>>
 
addInterest(…) gets
ONLY the 
value
 of
amount (i.e., 1000)
 
1000
Python is said to
pass parameters
by value
!
Consider the following code
Pass By Value vs. Returning a Value
def increment_func(x):
        x = x + 1
x = 1
increment_func(x)
print(x)
Run
1
def increment_func(x):
        x = x + 1
        return x
x = 1
x = increment_func(x)
print(x)
Run
2
 
There are different forms of the print function
1)
print(), which produces a blank line of output
 
 
 
 
 
 
 
 
 
 
 
 
 
More on the Print Function
>>> print()
>>>
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
More on the Print Function
>>> print(3+4)
7
>>> print(3, 4, 3+4)
3 4 7
>>> print("The answer is ", 3 + 4)
The answer is  7
>>> print("The answer is", 3 + 4)
The answer is 7
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
More on the Print Function
>>> def answer():
...     print("The answer is:", end = " ")
...     print(3 + 4)
...
>>> answer()
The answer is: 7
>>>
 
Notice how we used the end
parameter to allow multiple
prints to build up a single line
of output!
 
Functions- Part II
 
 
 
 
 
Next Class…
Slide Note
Embed
Share

In this lecture on functions in Python, the focus is on the basics of defining and using functions. The session covers the formal definition of functions, parameters, local and global scopes of variables, return values, and pass-by-value concept. It emphasizes the importance of proper indentation in defining functions and executing multiple-line code snippets. Additionally, the process of invoking functions, including with and without parentheses, is explained. The introduction of parameters adds versatility to functions, allowing for the inclusion of inputs such as 'person' in the defined function. Overall, this session sheds light on the essential aspects of leveraging functions in Python programming.

  • Python functions
  • Basics
  • Usage
  • Variables
  • Indentation

Uploaded on Jul 30, 2024 | 4 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. 15-110: Principles of Computing Functions- Part I Lecture 3, September 09, 2018 Mohammad Hammoud Carnegie Mellon University in Qatar

  2. 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 Announcement: Homework Assignment (HA) 01 is out. It is due on Thursday, Sep 13, 2018 by 10:00AM

  3. 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(): ... print("Hello") ... print("Programming is fun!") ... >>> These indentations are necessary to indicate that these two statements belong to the same block of code, which belongs to this function

  4. 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 >>>

  5. Invoking Functions After defining a function, we can call (or invoke) it by typing its name followed by parentheses >>> def hello(): ... print("Hello") ... print("Programming is fun!") ... >>> hello() Hello Programming is fun! >>> This is how we invoke our defined function hello(); notice that the two print statements (which form one code block) were executed in sequence!

  6. 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> >>>

  7. Parameters We can also add parameters (or arguments) to our defined functions person is a parameter; it acts as an input to the function hello( ) >>> def hello(person): ... print("Hello " + person) ... print("Programming is fun!") ... >>> hello("Mohammad") Hello Mohammad Programming is fun! >>>

  8. 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("Mohammad , 15-110 ) Hello Mohammad from 15-110 Programming is fun! >>>

  9. Parameters with Default Values In addition, parameters can be assigned default values def print_func(i, j = 100): print(i, j) def print_func(i, j = 100): print(i, j) def print_func(i, j = 100): print(i, j) print_func(10, 20) print_func(10) print_func() Run Run Run 10 20 10 100 ERROR

  10. Modularity and Maintenance 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") print("Happy birthday to you!") def singFred(): happy() happy() print("Happy birthday, dear Fred") happy() Can we write this program with 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!

  11. Extensibility and Readability Consider the following code print("Happy birthday to you!") print("Happy birthday to you!") print("Happy birthday, dear Fred") print("Happy birthday to you!") print("Happy birthday to you!") print("Happy birthday to you!") print("Happy birthday, dear Lucy") print("Happy birthday to you!") print("Happy birthday to you!") print("Happy birthday to you!") print("Happy birthday, dear Fred") print("Happy birthday to you!") What if we want to sing a verse for Lucy right after Fred? What if we utilize functions?

  12. 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") print("Happy birthday to you!") def sing(name): happy() happy() print("Happy birthday, dear " + name) happy() What if we want to sing a verse for Lucy right after Fred? sing("Fred") sing("Lucy") Easy to extend, morereadable,and necessitates less typing!

  13. 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>

  14. Local Variables Consider the following code def func1(x, y): #local scope z = 4 print(x, y, z) 2 3 4 Traceback (most recent call last): File "func1.py", line 6, in <module> print(x, y, z) NameError: name 'x' is not defined Run func1(2, 3) 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 localto func1( ), hence, referred to as a local variable

  15. Global Variables Consider the following code #global scope x = 100 100 100 def func2(): print(x) Run 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()

  16. Local vs. Global Variables Consider the following code x = 100 def func3(): x = 20 print(x) 20 100 Run func3() print(x) The global variable x is distinct from the local variable x inside func3()

  17. Parameters vs. Global Variables Consider the following code x = 100 def func4(x): print(x) 20 100 Run func4(20) print(x) The global variable x is distinct from the parameter x of func4( )

  18. The global Keyword Consider the following code def func5(): global x x = 20 print(x) 20 20 Run func5() print(x) The global keywordbinds variable x in the global scope; hence, can be accessed inside and outside func5()

  19. Getting Results From Functions We can get information from a function by having it return a value >>> def square(x): ... return x * x ... >>> square(3) 9 >>> >>> def cube(x): ... return x * x * x ... >>> cube(3) 27 >>> >>> def power(a, b): ... return a ** b ... >>> power(2, 3) 8 >>>

  20. 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 >>>

  21. 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) ... print(amount) ... >>> test() 1000 >>> What will be the result?

  22. 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) ... print(amount) ... >>> test() 1000 >>> Why 1000 and NOT 1050.0?

  23. Pass By Value The function only receives the values of the parameters 1000 addInterest( ) gets ONLY the value of amount (i.e., 1000) >>> def addInterest(balance, rate): ... newBalance = balance * rate ... balance = newBalance ... >>> def test(): ... amount = 1000 ... rate = 0.05 ... addInterest(amount, rate) ... print(amount) ... >>> test() 1000 >>> Python is said to pass parameters by value!

  24. Pass By Value vs. Returning a Value Consider the following code def increment_func(x): x = x + 1 return x def increment_func(x): x = x + 1 x = 1 x = increment_func(x) print(x) x = 1 increment_func(x) print(x) Run Run 1 2

  25. More on the Print Function There are different forms of the print function 1) print(), which produces a blank line of output >>> print() >>>

  26. 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) 3 4 7 >>> print("The answer is ", 3 + 4) The answer is 7 >>> print("The answer is", 3 + 4) The answer is 7

  27. 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(): ... print("The answer is:", end = " ") ... print(3 + 4) ... >>> answer() The answer is: 7 >>> Notice how we used the end parameter to allow multiple prints to build up a single line of output!

  28. Next Class Functions- Part II

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#