0% found this document useful (0 votes)
3 views23 pages

Functions

Vtu

Uploaded by

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

Functions

Vtu

Uploaded by

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

Chapter 3

FUNCTIONS
Introduction
• Python provides several built-in functions like print ( ), input( ) and len( ).
• But user can also write his own functions. A function is like a mini-program within a
program.
• Example:
def hello():
print('Howdy!’)
print('Howdy!!!’)
print('Hello there.’)
hello()
OUTPUT: Howdy!
Howdy!!!
Hello there.
P
def Statements with Parameters
• Consider the example: print(x) or len (x)
• Here we are passing values to the function print and len. These values are known
as arguments.
• User can also define his own functions that accepts arguments.
• Example:
def hello(name): OUTPUT:
print('Hello ' + name) Hello Alice
hello('Alice’) Hello Bob
hello('Bob')

P
Note
• The value stored in a parameter is forgotten when function returns.
• If the command print(name) is added after hello(‘Bob’) in the previous program,
the program would give you an NameError .
• Because there is no variable named ‘name’.
• This variable was destroyed after the function call hello(‘Bob’) had returned.

P
Return Values and return Statements
• When we 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.
• When creating a function using the def statement, you can specify what the return
value should be with a return statement. A return statement consists of the following:
• The return keyword
• The value or expression that the function should return

P
Example
def add(num1,num2):
sum1 = num1 + num2
print(“Addition of A & B:”, sum1)
A = int(input(“enter the first number”))
B = int(input(“enter the second number”))
add(A,B)

P
The None Value
• In Python there is a value called None, which represents the absence of a value.
None is the only value of the NoneType data type.
• Like the Boolean True and False values, None must be typed with a capital N.
• 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.
• Python adds return None to the end of any function definition with no return
statement.

P
Keyword Arguments and print( )
• 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 second
argument is the high end (while random.randint(10, 1) causes an error).
•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.
P
Example 1: Example 2:
print('Hello’) print('Hello', end=’’)
print('World’)
print('World’)
OUTPUT:
OUTPUT:
Hello
Hello World
World
• The two strings appear on separate • The output is printed on a single line
lines because the print() function because there is no longer a newline
automatically adds a newline character printed after 'Hello’.
to the end of the string it is passed. • Instead, the blank string is printed.

P
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.
• 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.

P
Scopes matter for several reasons:
• Code in the global scope cannot use any local variables.
• However, a local scope can access global variables.
• Code in a function’s local scope cannot use variables in any other local scope.
• We can use the same name for different variables if they are in different
scopes.
•The reason Python has different scopes instead of just making everything 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 list code lines that may be causing a bug.

P
Local Variables Cannot Be Used in the Global Scope
def num():
value = 31337
num()
print(value)

P
Local Scopes Cannot Use Variables in Other Local
Scopes
def num():
value = 99
bacon()
print(value)
def bacon():
value2 = 101
value = 0
num()

P
Global Variables Can Be Read from a Local Scope
def num():
print(value)
value = 42
num()
print(value)

P
Local and Global Variables with the Same Name
def spam():
name = 'spam local’
print(name). # prints 'spam local’
def bacon():
name = 'bacon local’
print(name) # prints ‘bacon local’
spam()
print(name) # prints ‘bacon local’
name = 'global’
bacon()
print(name) # prints ‘global’
P
OUTPUT
bacon local
spam local
bacon local
Global
• User must avoid using local variables that have the same name as a global
variable or another local variable.
• But technically, it’s perfectly legal to do so in Python.

P
The global Statement
• If you need to modify a global variable from within a function, use the global
statement.

def spam():
global name
name = 'spam’
name = 'global’
spam()
print(name)
OUTPUT: spam
P
There are four rules to tell whether a variable is in a local scope or global scope:
1. If a variable is being used in the global scope (that is, outside of all functions),
then it is always a global variable.
2. If there is a global statement for that variable in a function, it is a global variable.
3. Otherwise, if the variable is used in an assignment statement in the function, it is
a local variable.
4. But if the variable is not used in an assignment statement, it is a global variable.

P
Exception Handling
• Getting an error or exception, in your Python program means the entire program
will crash.
• Programmer don’t want this to happen in real-world programs. Instead,
programmer want the program to detect errors, handle them, and then continue to
run.
• Consider the following program, which has a “divide-by- zero” error.
def spam(divideBy):
return 42 / divideBy
print(spam(2)) OUTPUT: 21.0
print(spam(12)) 3.5
print(spam(0)) error
print(spam(1))
P
• A ZeroDivisionError happens whenever you try to divide a number by zero.
• Errors can be handled with try and except statements. The code that could
potentially have an error is put in a try clause.
def spam(divideBy):
try:
return 42 / divideBy
except ZeroDivisionError:
print('Error: Invalid argument.’)
print(spam(2))
print(spam(12)) OUTPUT: 21.0
print(spam(0)) 3.5
print(spam(1)) Error: Invalid argument.
None
42.0
P
def spam(divideBy): OUTPUT:
return 42 / divideBy 21.0
3.5
try: Error: Invalid
print(spam(2)) argument.
print(spam(12))
print(spam(0))
print(spam(1))
except ZeroDivisionError:
print('Error: Invalid argument.')
P
Different types of runtime errors
• Divide by zero
• Segmentation Fault
• Error while type conversion
•Attempt to perform operations(mathematical operations on string)

P
A Short Program: guess the number

You might also like