0% found this document useful (0 votes)
7 views131 pages

A1796840057 20248 5 2025 Lecture 4 Function

The document provides an overview of functions in Python, explaining their definition, creation, and invocation, as well as the concepts of parameters and arguments. It distinguishes between built-in and user-defined functions, discusses return values, and highlights the importance of functions in organizing code and avoiding repetition. Additionally, it covers local and global variables, type conversions, and various ways to pass arguments to functions.

Uploaded by

AMAR
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)
7 views131 pages

A1796840057 20248 5 2025 Lecture 4 Function

The document provides an overview of functions in Python, explaining their definition, creation, and invocation, as well as the concepts of parameters and arguments. It distinguishes between built-in and user-defined functions, discusses return values, and highlights the importance of functions in organizing code and avoiding repetition. Additionally, it covers local and global variables, type conversions, and various ways to pass arguments to functions.

Uploaded by

AMAR
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/ 131

Functions and

Recursion
Python Functions

• A function is a block of code which only runs when it is called.


• You can pass data, known as parameters, into a function.
• A function can return data as a result.
• Function: A named sequence of statements that performs some
useful operation. Functions may or may not take arguments and may
or may not produce a result.

• Function definition: A statement that creates a new function,


specifying its name, parameters, and the statements it executes.

• Function call: A statement that calls a function definition to perform


a specific task.
Creating a Function

• In Python a function is defined using the def keyword:

def my_function():
print("Hello from a function")
Calling a Function

• To call a function, use the function name followed by parenthesis:

def my_function():
print("Hello from a function")

my_function()
Stored (and reused) Steps
def
thing(): Program:
print('Hello') Output:
def thing():
print('Fun') print('Hello')
print('Fun') Hello
thing() Fun
thing()
print('Zip') Zip
print('Zip') thing()
Hello
Fun
thing()
We call these reusable pieces of code “functions”
Python Functions
• There are two kinds of functions in Python.

- Built-in functions that are provided as part of Python - print(),


input(), type(), float(), int() ...

- Functions that we define ourselves and then use

• We treat function names as “new” reserved words


(i.e., we avoid them as variable names)
Function Definition
• In Python a function is some reusable code that takes
arguments(s) as input, does some computation, and then returns
a result or results

• We define a function using the def reserved word

• We call/invoke the function by using the function name,


parentheses, and arguments in an expression
Argument

big = max('Hello world')


Assignment
'w'

Result
>>> big = max('Hello world')
>>> print(big)
w
>>> tiny = min('Hello world')
>>> print(tiny)

>>>
Max Function
A function is some
>>> big = max('Hello world') stored code that we
>>> print(big)
use. A function takes
w
some input and
produces an output.

'Hello world' max() 'w'


(a string) function (a string)

Guido wrote this code


Max Function
A function is some
>>> big = max('Hello world') stored code that we
>>> print(big)
use. A function takes
w
some input and
def max(inp):
produces an output.
blah
'Hello world' blah 'w'
for x in inp:
(a string) blah
(a string)
blah

Guido wrote this code


Type Conversions
>>> print(float(99) / 100)
• When you put an integer 0.99
>>> i = 42
and floating point in an >>> type(i)
expression, the integer <class 'int'>
is implicitly converted to >>> f = float(i)
>>> print(f)
a float 42.0
>>> type(f)
• You can control this with <class 'float'>
the built-in functions int() >>> print(1 + 2 * float(3) / 4 – 5)
and float() -2.5
>>>
String >>> sval = '123'
>>> type(sval)
<class 'str'>
Conversions >>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
• You can also use int() TypeError: cannot concatenate 'str'
and 'int'
and float() to convert >>> ival = int(sval)
between strings and >>> type(ival)
<class 'int'>
integers >>> print(ival + 1)
124
• You will get an error if the >>> nsv = 'hello bob'
>>> niv = int(nsv)
string does not contain Traceback (most recent call last):
numeric characters File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
Functions of Our Own…
Building our Own Functions
• We create a new function using the def keyword followed by
optional parameters in parentheses

• We indent the body of the function

• This defines the function but does not execute the body of the
function
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all
day.')
print("I'm a lumberjack, and I'm okay.")
print_lyrics(): print('I sleep all night and I work all day.')

x = 5
print('Hello')

def print_lyrics():
print("I'm a lumberjack, and I'm okay.") Hello
print('I sleep all night and I work all day.')
Yo
print('Yo') 7
x = x + 2
print(x)
Definitions and Uses
• Once we have defined a function, we can call (or invoke) it
as many times as we like

• This is the store and reuse pattern


x = 5
print('Hello')

def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')

print('Yo')
print_lyrics()
x = x + 2
Hello
print(x) Yo
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
7
Arguments
• An argument is a value we pass into the function as its input
when we call the function

• We use arguments so we can direct the function to do different


kinds of work when we call it at different times

• We put the arguments in parentheses after the name of the


function
big = max('Hello world')
Argument
Parameters
>>> def greet(lang):
... if lang == 'es':
A parameter is a variable which ... print('Hola')
... elif lang == 'fr':
we use in the function definition. ... print('Bonjour')
It is a “handle” that allows the ... else:
... print('Hello')
code in the function to access ...
>>> greet('en')
the arguments for a particular Hello
function invocation. >>> greet('es')
Hola
>>> greet('fr')
Bonjour
>>>
Return Values
Often a function will take its arguments, do some computation, and
return a value to be used as the value of the function call in the
calling expression. The return keyword is used for this.

def greet():
return "Hello" Hello Glenn
Hello Sally
print(greet(), "Glenn")
print(greet(), "Sally")
Return Value
>>> def greet(lang):
... if lang == 'es':
• A “fruitful” function is one ... return 'Hola'
... elif lang == 'fr':
that produces a result (or ... return 'Bonjour'
return value) ... else:
... return 'Hello'
...
• The return statement ends >>> print(greet('en'),'Glenn')
the function execution and Hello Glenn
>>> print(greet('es'),'Sally')
“sends back” the result of Hola Sally
the function >>> print(greet('fr'),'Michael')
Bonjour Michael
>>>
Arguments, Parameters, and
Results
>>> big = max('Hello world') Parameter
>>> print(big)
w
def max(inp):
blah
blah
'Hello world' for x in inp: 'w'
blah
blah
Argument return 'w'
Result
Multiple Parameters / Arguments
• We can define more than one
parameter in the function def addtwo(a, b):
definition added = a + b
return added
• We simply add more arguments
x = addtwo(3, 5)
when we call the function print(x)

• We match the number and order 8


of arguments and parameters
Void (non-fruitful) Functions

• When a function does not return a value, we call it a “void”


function

• Functions that return values are “fruitful” functions


• Void functions are “not fruitful”
To function or not to function...
• Organize your code into “paragraphs” - capture a complete
thought and “name it”

• Don’t repeat yourself - make it work once and then reuse it

• If something gets too long or complex, break it up into logical


chunks and put those chunks in functions

• Make a library of common stuff that you do over and over -


perhaps share this with your friends...
Summary
• Functions • Arguments
• Built-In Functions • Results (fruitful functions)
• Type conversion (int, float) • Void (non-fruitful) functions
• String conversions • Why use functions?
• Parameters
Exercise

Rewrite your pay computation with time-and-a-


half for overtime and create a function called
computepay which takes two parameters ( hours
and rate).

Enter Hours: 45
Enter Rate: 10

Pay: 475.0
475 = 40 * 10 + 5 * 15
Function calls
Function Name Arguments

>>> type(“32”)
<type ‘str’> Return Value
Adding new or user defined functions
• A function is a named sequence of statements that performs a
desired operation. This operation is specified in a function definition.

• The syntax for a function definition is:


Why we need to create functions

• Creating a new function gives you an opportunity to name a group of


statements. Functions can simplify a program by hiding a complex
computation behind a single command and by using English words in
place of arcane code.

• Creating a new function can make a program smaller by eliminating


repetitive code.
Few points to remember
• Only the function definition generates no output.
• The statements inside the function do not get executed until the
function is called.
• You have to create a function before you can execute it. In other
words, the function definition has to be executed before the first
time it is called.
Flow of execution
• In order to ensure that a function is defined before its first use, you
have to know the order in which statements are executed, which is
called the flow of execution.
3
4
5
6

Execution Starts 1
2
7
Parameters and arguments

• Arguments are the values that control how the function does its job.
• For example, if you want to find the sine of a number, you have to
indicate what the number is. Thus, sin takes a numeric value as an
argument.

• Some functions take more than one argument. For example, pow
takes two arguments, the base and the exponent. Inside the function,
the values that are passed get assigned to variables called
parameters.
Arguments

• Information can be passed into functions as arguments.


• Arguments are often shortened to args in Python documentations.
• Arguments are specified after the function name, inside the
parentheses. You can add as many arguments as you want, just
separate them with a comma.
• The following example has a function with one argument (fname).
When the function is called, we pass along a first name, which is
used inside the function to print the full name:
Parameters or Arguments?

• The terms parameter and argument can be used for the same
thing: information that are passed into a function.
• From a function's perspective:
• A parameter is the variable listed inside the parentheses in the
function definition.
• An argument is the value that is sent to the function when it is
called.
• A parameter is the variable listed inside the parentheses in the
function definition.

• An argument is the value that are sent to the function when it is


called.
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")
Number of Arguments

• By default, a function must be called with the correct number of


arguments. Meaning that if your function expects 2 arguments, you
have to call the function with 2 arguments, not more, and not less.
• If you try to call the function with 1 or 3 arguments, you will get an
error.
• This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")
Error
• This function expects 2 arguments, but gets only 1:
• def my_function(fname, lname):
print(fname + " " + lname)

my_function("Emil")
Arbitrary Arguments, *args

• If you do not know how many arguments that will be passed into
your function, add a * before the parameter name in the function
definition.
• Arbitrary Arguments are often shortened to *args in Python
documentations.
• This way the function will receive a tuple of arguments, and can
access the items accordingly:
• If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Here [2] tell about the index. Emil is [0], Tobias is [1] and Linus is [2]
Keyword Arguments

• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.
• The phrase Keyword Arguments are often shortened to kwargs in
Python documentations.

def my_function(child3, child2, child1):


print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3


= "Linus")
Default Parameter Value

• The following example shows how to use a default parameter


value.
• If we call the function without argument, it uses the default value:
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Passing a List as an Argument

• You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the function.
• E.g. if you send a List as an argument, it will still be a List when it reaches the
function:

def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)
Return Values

• To let a function return a value, use the return statement:

def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))
Print factorial of 4
Python Global and Local Variables
• Global Variables are those which are defined outside any function and
which are accessible throughout the program, i.e., inside and outside of
every function.
• Local variables are those which are initialized inside a function and
belong only to that particular function. It cannot be accessed anywhere
outside the function.
a=20
def prog():
b=10
print("The value of local variable is=", b)
print("The value of global variable is=", a)
Local vs global
e.g. local scope
• When you create a local variable inside a function, it only exists inside
the function, and you cannot use it outside. For example:
def catTwice(part1, part2):
cat = part1 + part2
print cat

>>> a= “Python”
>>> b=“Class”
>>> catTwice(a,b)
When cat Twice terminates, the variable cat is destroyed. If we try to
print it,
we get an error:

>>> print cat


NameError: cat

• Parameters are also local. For example, outside the function


catTwice(part1, part2), there is no such thing as part1 and part2
Implicit Conversion

x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)
print("z is of type:",type(z))
Type conversion
Float to integer conversion
Integer and String Conversion to Float
Integer and Float Conversion to String
Math Functions
Mathematical Functions

• abs(x) • log(x)
• ceil(x) • pow (x,y)
• cmp (x, y) • sqrt(x,y )
• exp (x) • max (x1,x2….xn)
• floor(x) • min (x1,x2…xn)
Calling a Math Function

For Example,
Composition
Composition
Function Definition
with arguments

Function Call
with arguments of
type String, Integer
and float respectively
Composition for user defined functions
Stack Diagram for functions
• To keep track of which variables can be used where, it is sometimes
useful to draw a stack diagram.
• Stack diagram is used to represent the state of a program during a
function call.
• Each function is represented by a frame. A frame is a box with the
name of a function beside it and the parameters and variables of the
function inside it.
_main_
a “Python”

b “Class”

Part1 “Python”
catTwice
Part2 “Class”

Cat “Python Class”


Functions with results

def sum (x,y):


return x+y

>>> a=sum(8,9)
>>> print(a)
17
Recursion

• Python also accepts function recursion, which means a defined


function can call itself.
• Recursion is a common mathematical and programming concept. It
means that a function calls itself. This has the benefit of meaning
that you can loop through data to reach a result.
Recursion
• It is legal for one function to call another, and you have seen several
examples of that.
• But it is also legal for a function to call itself.
• For example,
>>> countdown(3)

OUTPUT of this function will be :


Stack diagrams for recursive functions

• Earlier we used a stack diagram to represent the state of a program


during a function call. The same kind of diagram can help interpret a
recursive function.
• Every time a function gets called, Python creates a new function
frame, which contains the function's local variables and parameters.
For a recursive function, there might be more than one frame on the
stack at the same time.
• Following figure shows a stack diagram for function countdown (n)
called with n = 3:
Infinite recursion
• If a recursion never reaches a base case, it goes on making recursive
calls forever, and the program never terminates. This is known as
infinite recursion, and it is generally not considered a good idea. Here
is a minimal program with an infinite recursion:

def recurse () : Function is calling


itself without any
recurse() condition to terminate
The recursive call
• In most programming environments, a program with infinite
recursion does not really run forever. Python reports an error
message when the maximum recursion depth is reached:
EXCERCISE
1. Write a Python function to find the Max of three numbers.
2. Write a Python function to sum all the numbers in a list.
3. Write a Python function to multiply all the numbers in a list.
4. Write a Python function to reverse a string.
5. Write a Python function to calculate the factorial of a number (non-
negative integer). The function accept the number as an argument.
6. Write a Python function to check whether a number is in a given
range.
7. Write a Python function that takes a number as a parameter and
check the number is prime or not.
8. Write a Python function that checks whether a passed string is
palindrome or not.
9. Write a Python function to check whether a number is perfect or not.
According to Wikipedia : In number theory, a perfect number is a
positive integer that is equal to the sum of its proper positive divisors,
that is, the sum of its positive divisors excluding the number itself
(also known as its aliquot sum). Equivalently, a perfect number is a
number that is half the sum of all of its positive divisors (including
itself).
Example : The first perfect number is 6, because 1, 2, and 3 are its
proper positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6
is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 =
6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed
by the perfect numbers 496 and 8128.
Python program maximum of three
Python Program to Fine the Largest Among
Three Numbers
Python program maximum of three using
List
Python program maximum of three using
Python max

You might also like