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

Chapter3 Functions

Uploaded by

Kavitha Palani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Chapter3 Functions

Uploaded by

Kavitha Palani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

Module 1

Ch 3. FUNCTIONS
Contents
• Introduction
• def Statements with Parameters
• Local and Global Scope
• The global Statement
• Exception Handling
• Project: A Short Program: Zigzag
• Summary
Introduction
• You’re already familiar with the built- in functions like print(), input(),
and len() functions from the previ- ous chapters.
• but you can also write your own functions.
• A function is like a miniprogram within a program.
Lets Try This
def hello(): Output:
print(‘Hello!’) Hello
print(‘Goodmorning!!!’) Goodmorning
print(‘CMRIT.’) CMRIT

How to call the fuction?


hello() # Call to function
Description
• The first line is a def statement, which defines a function named hello().
• The code in the block that follows the def statement is the body of the
function.
• This code is executed when the function is called, not when the function is
first defined.
• function call is just the function’s name followed by parentheses, possibly
with some number of arguments in between the parentheses.
• When the program execution reaches these calls, it will jump to the top line in
the function and begin executing the code there.
• When it reaches the end of the function, the execution returns to the line that
called the function and continues moving through the code as before.
Purpose
• A major purpose of functions is to group code that gets executed mul-
tiple times. Without a function defined, you would have to copy and
paste this code each time,
• In general, you always want to avoid duplicating code because if you
ever decide to update the code—if, for example, you find a bug you
need to fix—you’ll have to remember to change the code everywhere
you copied it.
• As you get more programming experience, you’ll often find yourself
deduplicating code, which means getting rid of duplicated or copy-and-
pasted code. Deduplication makes your programs shorter, easier to
read, and easier to update.
def Statements with
Parameters
def Statements with Parameters
• When you call the print() or len() function, you pass them values,
called arguments, by typing them between the parentheses.
• print(“Hello”)
• len(“hello”)
•5
• You can also define your own functions that accept arguments.
• E.g def hello(name):
print('Hello, ' + name)
hello(“hello”) #call
Output :
Define, Call, Pass, Argument,
Parameter
• The terms define, call, pass, argument, and parameter can be confusing. Let’s
look at a code example to review these terms:
def sayHello(name):
print('Hello, ' + name)
sayHello('Al') # Calling the function

To define a function is to create it, just like an assignment statement like spam =
42 creates the spam variable. The def statement defines the sayHello() function
The sayHello('Al') line calls the now-created function by send- ing the execution
to the top of the function’s code.
Define, Call, Pass, Argument,
Parameter
• This function call is also known as passing the string value 'Al' to the
function. A value being passed to a function in a function call is an
argument.
• The argument 'Al' is assigned to a local variable named name.
Variables that have arguments assigned to them are parameters.
Return Values and return
Statements
• When you call the len() function and pass it an argument such as 'Hello', the
function call evaluates to the integer value 5, which is the length of the string
you passed it.
• In general, the value that a function call evaluates to is called the return value
of the function.
• A return statement con- sists of the following:
• The return keyword
• The value or expression that the function should return
def add(a,b):
c=a+b
return c
add(2,4)
Lets try this

When an expression is used with a return


statement, the return value
is what this expression evaluates to
Note
• Expressions are composed of values and operators. A function call
can be used in an expression because the call evaluates to its return
value.

def add(a, b):


return a + b # Function returns a value
result = add(3, 5) * 2 # Function call inside an expression
print(result)
The None Value

• The None Value


• In Python, there is a value called None, which represents the absence
of a value.
• The None value is the only value of the NoneType data type. (Other
programming languages might call this value null, nil, or undefined.)
Just like the Boolean True and False values, None must be typed with
a capital N.
• This value-without-a-value can be helpful when you need to store
something that won’t be confused for a real value in a variable.
• One place where None is used is as the return value of print().
• The print() function displays text on the screen, but it doesn’t need to
return anything in the same way len() or input() does. But since all
function calls need to evaluate to a return value, print() returns None.
print() returns None.
• Let’s understand with the below program
>>> spam = print('Hello!')
Hello!
>>> None == spam
True
• Behind the scenes, Python adds return None to the end of any function definition
with no return statement.
• This is similar to how a while or for loop implicitly ends with a continue
statement.
• Also, if you use a return statement without a value (that is, just the return
keyword by itself), then None is returned.
Keyword Arguments and the
print() Function
• Most arguments are identified by their position in the function call.
For example,
• random.randint(1, 10) is different from random.randint(10, 1).
• The function call random.randint(1, 10) will return a random integer
between 1 and 10 because the first argument is the low end of the
range and the sec-ond argument is the high end (while
random.randint(10, 1) causes an error).
Keyword Arguments and the
print() Function
• However, rather than through their position, keyword arguments are
identified by the keyword put before them in the function call.
• Keyword arguments are often used for optional parameters.
• For example, the print() function has the optional parameters end and
sep to specify what should be printed at the end of its arguments and
between its arguments (separating them), respectively.
Lets try this
print('Hello’)
print('World’)
O/p :
Hello
World
The two outputted strings appear on separate lines because the print()
function automatically adds a newline character to the end of the string
it is passed.
Lets Try this
• You can set the end keyword argument to change the new- line
character to a different string. For example,
print('Hello', end=’ ’)
print('World’)
Hello World
The output is printed on a single line because there is no longer a
newline printed after 'Hello'. Instead, the blank string is printed. This is
useful if you need to disable the newline that gets added to the end of
every print() function call
Lets try this
• when you pass multiple string values to print(), the function will
automatically separate them with a single space.
>>> print('cats', 'dogs', 'mice’)
cats dogs mice
• But you could replace the default separating string by passing the sep
keyword argument a different string
>>> print('cats', 'dogs', 'mice', sep=',’)
cats,dogs,mice
The Call Stack

• Similar to our meandering conversation, calling a function doesn’t


send the execution on a one-way trip to the top of a function.
• Python will remember which line of code called the function so that
the execution can return there when it encounters a return
statement.
• If that original function called other functions, the execution would
return to those function calls first, before returning from the original
function call.
Example : call stack in abcdCallStack.py

• Output
call stack in abcdCallStack.py

• The top of the call stack is which


function the execution is
currently in. When the call stack
is empty, the execution is on a
line outside of all functions.
• It’s enough to understand that
function calls return to the line
number they were called from.
Local and Global Scope

• Parameters and variables that are assigned in a called function are


said to exist in that function’s local scope.
• Variables that are assigned outside all functions are said to exist in the
global scope.
• A variable that exists in a local scope is called a local variable,
• while a variable that exists in the global scope is called a global
variable.
• A variable must be one or the other; it cannot be both local and
global.
global scope
• Think of a scope as a container for variables.
• When a scope is destroyed, all the values stored in the scope’s
variables are forgotten.
• There is only one global scope, and it is created when your program
begins. When your program terminates, the global scope is destroyed,
and all its variables are forgotten.
• Otherwise, the next time you ran a program, the variables would
remember their values from the last time you ran it.
local scope
• A local scope is created whenever a function is called.
• Any variables assigned in the function exist within the function’s local
scope.
• When the function returns, the local scope is destroyed, and these
variables are forgotten. The next time you call the function, the local
variables will not remember the values stored in them from the last
time the function was called.
• Local variables are also stored in frame objects on the call stack.
Scopes matter for several reasons:

• Code in the global scope, outside of all functions, cannot use any local
variables.
• However, code in a local scope can access global variables.
• Code in a function’s local scope cannot use variables in any other local
scope.
• You can use the same name for different variables if they are in
different scopes. That is, there can be a local variable named spam
and a global variable also named spam.
• The reason Python has different scopes instead of just making every-
thing a global variable is so that when variables are modified by the
code in a particular call to a function, the function interacts with the
rest of the program only through its parameters and the return value.
• This narrows down the number of lines of code that may be causing a
bug.
Why Does Python Use Different Scopes Instead of Just
Global Variables?

• Imagine if all variables in a program were global. That would mean


any function, anywhere in the program, could change them. This
would make it very hard to find bugs because:
❌ Any part of the code could change a variable’s value unexpectedly.
❌ If something goes wrong, you wouldn’t know where the mistake
happened.
How Different Scopes Help

Python separates variables into local and global scopes to make debugging easier.
🔹 Local Variables (Inside a Function):
• These exist only inside the function.
• If something goes wrong, you know that only the function’s code is responsible.
• Once the function ends, these variables are deleted, so they don’t interfere with
other parts of the program.
🔹 Global Variables (Outside a Function):
• These exist throughout the entire program
• Any function can modify them, which can lead to unexpected changes and hard-
to-find bugs.
Example: Why Local Variables Are Better
❌ Using Global Variables (Risky)

x = 10 # Global variable

def update_x():
global x # Modifying global variable
x = 20

update_x()
print(x) # Output: 20 (but hard to track where it changed!)

Problem: Any function can change x, making debugging difficult.


Using Local Variables (Safer)
def update_x():
x = 20 # Local variable
return x
new_x = update_x()
print(new_x) # Output: 20
Solution: The function only affects new_x, so no unintended changes
happen.
NOTE:
While using global variables in small programs is fine, it is a bad habit to rely
on global variables as your programs get larger and larger.
Local Variables Cannot Be Used in the Global Scope

• Example • The error happens because the eggs variable


exists only in the local scope created when
def spam(): spam() is called.
• Once the program execution returns from
eggs = 31337 spam, that local scope is destroyed, and there
is no longer a variable named eggs.
spam() • So when your program tries to run print(eggs),
print(eggs) Python gives you an error saying that eggs is
not defined.
• This makes sense if you think about it; when
the program execution is in the global scope,
no local scopes exist, so there can’t be any
local variables.
• This is why only global variables can be used in
the global scope.
Local Scopes Cannot Use Variables in Other Local Scopes

• A new local scope is created


whenever a function is called,
including when a function is
called from another function.
• local variables in one function
are completely separate from
the local variables in another
function.
Local Scopes Cannot Use Variables in Other Local Scopes

• When the program starts, the spam() function is called, and a local scope is
created.
• The local variable eggsis set to 99. Then the bacon() function is called, and a second
local scope is created. Multiple local scopes can exist at the same time. In this new
local scope, the local variable ham is set to 101, and a local variable eggs—which is
different from the one in spam()’s local scope—is also created and set to 0.
• When bacon() returns, the local scope for that call is destroyed, includ- ing its eggs
variable. The program execution continues in the spam() func- tion to print the
value of eggs.
• Since the local scope for the call to spam() still exists, the only eggs variable is the
spam() function’s eggs variable, which was set to 99. This is what the program
prints.
Global Variables Can Be Read from a Local
Scope

def spam(): • There is no parameter named


print(eggs) eggs or any code that assigns
eggs a value in the spam()
eggs = 42 function, when eggs is used in
spam() spam(), Python considers it a
print(eggs) reference to the global variable
eggs. This is why 42 is printed
when the previous program is
run.
Local and Global Variables with the Same Name

• Technically, it’s perfectly acceptable to use the same variable name


for a global variable and local variables in different scopes in Python.
But, to simplify your life, avoid doing this.
To see what happens, enter the code into the file editor

• Output
def spam():
eggs = 'spam local’ # (1) Local variable inside spam()
print(eggs) # Prints 'spam local'

def bacon():
eggs = 'bacon local’ # (2) Local variable inside bacon()
print(eggs) # Prints 'bacon local'
spam() # (3) Calls spam()
print(eggs) # (4) Prints 'bacon local' again

eggs = 'global’ # (5) Global variable


bacon() # (6) Calls bacon()
print(eggs) # (7) Prints 'global'
Local and Global Variables with the Same Name

• There are actually three different variables in this program, but


confusingly they are all named eggs. The variables are as follows:
• A variable named eggs that exists in a local scope when spam() is called.
• A variable named eggs that exists in a local scope when bacon() is called.
• A variable named eggs that exists in the global scope.
• Since these three separate variables all have the same name, it can be
confusing to keep track of which one is being used at any given time.
• This is why you should avoid using the same variable name in
different scopes.
The global Statement

• If you need to modify a global variable from within a function, use the
global statement. If you have a line such as global eggs at the top of a
function, it tells Python,
• “In this function, eggs refers to the global variable, so don’t create a
local variable with this name.”
def spam():
global eggs # (1) Declare that 'eggs' refers to the global variable
eggs = 'spam’ # (2) Modify the global 'eggs'

eggs = 'global’ # (3) Global variable is initially assigned 'global'


spam() # (4) Call spam(), which modifies 'eggs'
print(eggs) # (5) Prints the modified value of 'eggs'

• Because eggs is declared global at the top of spam(),


• when eggs is set to 'spam', this assignment is done to the globally
scoped eggs.
• No local eggs variable is created.
Rules to tell whether a variable is in
a local scope or global scope:
• If a variable is being used in the global scope (that is, outside of all
functions), then it is always a global variable.
• If there is a global statement for that variable in a function, it is a
global variable.
• Otherwise, if the variable is used in an assignment statement in the
function, it is a local variable.
• But if the variable is not used in an assignment statement, it is a
global variable.
Lets Try it
def spam():
global eggs # (1) Declares eggs as a global variable
eggs = 'spam’ # Modifies the global eggs

def bacon():
eggs = 'bacon’ # (2) Creates a new local variable eggs inside bacon()

def ham():
print(eggs) # (3) Prints the global eggs

eggs = 42 # (4) Global variable eggs is initially set to 42


spam() # (5) Calls spam(), which modifies the global eggs
print(eggs) # (6) Prints the modified global eggs
Lets Try it
• Output
spam
In a function, a variable will either
always be global or always be
local. The code in a function can’t
use a local variable named eggs
and then use the global eggs
variable later in that same
function.
Note
• If you ever want to modify the value stored in a global variable from
in a function, you must use a global statement on that variable.
• If you try to use a local variable in a function before you assign a value
to it, as in the following program, Python will give you an error
Example
• This error happens because
Python sees that there is
an assignment statement for
eggs in the spam() functionand,
therefore, considers eggs to be
local. But because print(eggs) is
executed before eggs is assigned
anything, the local variable eggs
doesn’t exist. Python will not fall
back to using the global eggs
variable.
Exception Handling

• Right now, getting an error, or exception, in your Python program


means the entire program will crash.
• You don’t want this to happen in real-world pro- grams. Instead, you
want the program to detect errors, handle them, and then continue
to run.
Exception Handling

• For example, consider the following program, which has a divide-by-


zero error.
Exception Handling

• Errors can be handled with try and except statements. The code that
could potentially have an error is put in a try clause. The program
execution moves to the start of a following except clause if an error
happens.
• You can put the previous divide-by-zero code in a try clause and have
an except clause contain code to handle what happens when this
error occurs.
Exception Handling
Exception Handling

• When code in a try clause causes an error, the program execution


immediately moves to the code in the except clause.
• After running that code, the execution continues as normal. The
output of the previous pro- gram is as follows:
Exception Handling

• Note that any errors that occur in function calls in a try block will also be caught.
Consider the following program, which instead has the spam() calls in the try
block:
• The reason print(spam(1)) is never executed is because once the execution jumps
to the code in the except clause, it does not return to the try clause. Instead, it
just continues moving down the program as normal.
Project
• A Short Program: Zigzag
Refer code File/ PPts from Project Folder
Summary

• Functions are the primary way to compartmentalize your code into logical groups.
Since the variables in functions exist in their own local scopes, the code in one
function cannot directly affect the values of variables in other functions. This limits
what code could be changing the values of your vari- ables, which can be helpful
when it comes to debugging your code. Functions are a great tool to help you
organize your code.
• You can think of them as black boxes: they have inputs in the form of parameters
and outputs in the form of return values, and the code in them doesn’t affect
variables in other functions.
• In previous chapters, a single error could cause your programs to crash. In this
chapter, you learned about try and except statements, which can run code when an
error has been detected. This can make your programs more resilient to common
error cases.

You might also like