Chapter3 Functions
Chapter3 Functions
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
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
• Output
call stack in abcdCallStack.py
• 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?
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!)
• 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
• 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
• 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'
def bacon():
eggs = 'bacon’ # (2) Creates a new local variable eggs inside bacon()
def ham():
print(eggs) # (3) Prints the global eggs
• 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
• 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.