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

Chapter2(Functions)

The document provides an overview of functions in Python, explaining their purpose, benefits, and types including pre-defined and user-defined functions. It covers how to define and call both void and value-returning functions, as well as concepts like scope, local and global variables, and different types of arguments. Additionally, it introduces recursion and lambda functions, along with various examples to illustrate these concepts.
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)
10 views

Chapter2(Functions)

The document provides an overview of functions in Python, explaining their purpose, benefits, and types including pre-defined and user-defined functions. It covers how to define and call both void and value-returning functions, as well as concepts like scope, local and global variables, and different types of arguments. Additionally, it introduces recursion and lambda functions, along with various examples to illustrate these concepts.
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/ 14

Functions in Python

A function: is a block of code that runs (executes) only when it is called from some other point
of the program, function exists within a program for the purpose of performing a specific task.
A program that has been written with each task in its own function is called a modularized
program.

Figure: Using functions to divide and conquer a large task

➢ Benefits of Modularizing a Program with Functions


A program benefits in the following ways when it is broken down into functions:
1. Simpler Code
A program’s code tends to be simpler and easier to understand when it is broken down into
functions.
2. Code Reuse
Functions also reduce the duplication of code within a program.

Prepared By: Enas Abu Samra


3. Better Testing
When each task within a program is contained in its own function, testing and debugging
becomes simpler.
4. Faster Development
Suppose a programmer or a team of programmers is developing multiple programs. They
discover that each of the programs perform several common tasks, such as asking for a
username and a password, and so on. It doesn’t make sense to write
the code for these tasks multiple times. Instead, functions can be written for the commonly
needed tasks, and those functions can be incorporated into each program that needs them.
5. Easier Facilitation of Teamwork
Functions also make it easier for programmers to work in teams.

➢ Each function has:


• Function Definition: the code for a function.
• Function Call: the statement that call a function to execute it.

➢ Types of functions:
1. Pre-Defined Functions.
2. User-Defined Functions:
✓ Void Functions.
✓ Value-Returning Functions.

➢ Pre-Defined Functions (Library Functions)


Python, as well as most programming languages, comes with a standard library of functions that
perform commonly needed tasks. These functions, known as library functions, make a
programmer’s job easier because they perform many of the tasks that programmers commonly
need to perform. Examples: range, print, input functions.

Prepared By: Enas Abu Samra


In order to call a function that is stored in a module, you have to write an import statement at the
top of your program.

➢ Defining and Calling Void Functions

• Defining Void Functions


A void function is a group of statements that exist within a program for the purpose of
performing a specific task. The general format of a function definition in Python:

def function_name(formal parameter list OR without parameters):


statement
statement
etc.

• Calling Void Functions


- A function definition specifies what a function does, but it does not cause the function to
execute. To execute a function, you must call it.
- When you call a void function, it simply executes the statements it contains and then
terminates.
- The general format for calling a void function is:

function_name(actual parameter list OR without parameters)

Notes:
- The number of passed arguments based on the number of the parameters that exist in
function declaration.
- Actual parameter list (argument list) is a list that contains one or more arguments that
are passed to the function.
- Argument is a variable or an expression or a value.
- Formal parameter list (parameter list) is a list that contains one or more parameters
that are received values from the actual parameters.
- Parameter is a variable.
- Consider the matching (same number) in the actual and formal parameter lists when
defining and calling function.
- Any change in the value of the parameters does not affect the arguments and vice versa.

Prepared By: Enas Abu Samra


- Parameters cannot be used outside of a function.
- Parameters and arguments can be given the same names.
- You can call the function more than once.
- In Python, the type of parameter determined by the value passed to it.

Ex1: void_function
def drawRectangle(): #without parameters
print("*************")
print("* *" )
print("* *")
print("*************")

drawRectangle()
print("Another Rectangle: ")
drawRectangle()

Ex2: void_function

Write a void function that receives two string parameters (first name and second name),
this function prints the full name.
Let the user enters his first name and second name, then call the defined function.

Prepared By: Enas Abu Samra


➢ Defining and Calling Value-Returning Functions

• Defining Value-Returning Functions


A value-returning function is a function that returns a value back to the part of the program
that called it. The general format of a function definition in Python:

def function_name(formal parameter list OR without parameters):


statement
statement
return expression.

• Calling Value-Returning Functions


- A function definition specifies what a function does, but it does not cause the function to
execute. To execute a function, you must call it.
- When you call a value-returning function, it executes the statements that it contains, then
returns a value back to the statement that called it.

- The general formats for calling a value-returning function is:

variable_name = function_name(actual parameter list OR without parameters)


OR

print(function_name(actual parameter list OR without parameters))

Notes:
- When the return statement is executed, the function stops, even if there are statements
remaining after the return statement, and the program continues to execute from the place
where the function was called.
- You can return any data type in the return statement
- All notes in a void function correct here.
Ex1: return_function
Write a value-returned function; without parameters; that returns “Hello Python Students”, then
call the defined function.
def func(): #without parameters
print("Hello Python Students")

func()

Prepared By: Enas Abu Samra


Ex2: return_function
Write a value-returned function that receives two int parameters, this function returns the sum of
them, let the user enter two numbers, then call the defined function.

➢ Scope
A variable’s scope is the part of a program in which the variable may be accessed. A variable
is visible only to statements in the variable’s scope. A local variable’s scope is the block in
which the variable is created.

➢ Local Variable
A local variable: is created inside a function block and cannot be accessed by statements that
are outside the block. Different blocks can have local variables with the same names because
the blocks cannot see each other's local variables.

Example:
def number():
num = 5
#Local Variable
print ("Num value inside function is:", num)
number ()
#print ("Num value outside function is:", num) #Error, you can't
access a local variable.

Prepared By: Enas Abu Samra


➢ Global Variable
A global variable: is created by an assignment statement that is written outside all the blocks
in a program file. A global variable can be accessed by any statement in the program file,
including the statements in any block.
Example 1:
num = 10
def number():
#Global Variable
print("Num value inside function is:", num)
number()
print("Num value outside function is:", num)

Example 2:
num = 10 #Global variable
def number():
num = 3 #local variable
print("Num value inside function is:", num) #Num value inside
function is: 3

number ()
print("Num value outside function is:", num) #Num value outside
function is: 10

Example 3:
def Amman():
birds = 5000
print("Amman has", birds, "birds.") #Amman has 5000 birds.
def karak():
birds = 8000
print("Karak has", birds,"birds.") #Karak has 8000 birds.

Amman()
karak()
Example 4:
num1 = 10 # Global variable
def number():
num2 = 3 #local variable
print("Global Var is:", num1)
num2 += num1
print("Local Var after modification is:", num2)

number()

Prepared By: Enas Abu Samra


➢ Positional Arguments

Example:
def full_name (f_name, l_name):
print ("Your full name is:")
print (f_name,l_name)
print("***************")

first_name = input("Please enter your first name:")


last_name = input("Please enter your last name: ")
full_name(first_name, last_name)

➢ Keyword Arguments

Example:
def full_name (f_name, l_name):
print ("Your full name is:")
print (f_name,l_name)
print("***************")

first_name = input("Please enter your first name:")


last_name = input("Please enter your last name: ")
full_name (l_name=last_name, f_name =first_name)

➢ Default Parameters
If we call the function without argument, it uses the default value.
Example:
def show(name,msg="good morning"):
print("Hello", name, msg)

show("Sami") #Hello Sami good morning


show("Rami","How do you do") #Hello Rami How do you do

Example:

def func(name = "Enas", age = 33, gpa = 3.5):


print(name, age, gpa)

func() #Enas 33 3.5


func("Sally", 20, 3.75) #Sally 20 3.75
func("Ahmad",3.75) #Ahmad 3.75 3.5
func("Saja", gpa = 3.75) #Saja 33 3.75

Prepared By: Enas Abu Samra


➢ Mixing Keyword Arguments with Positional Arguments
It is possible to mix positional arguments and keyword arguments in a function call, but the
positional arguments must appear first, followed by the keyword arguments. Otherwise,
an error will occur.
Correct Rules: (positional, positional), (keyword, keyword), (positional, keyword)
Incorrect Rule: (keyword, positional)
Example:
def full_name (f_name, l_name):
print ("Your full name is:")
print (f_name,l_name)
print("***************")

last_name = input("Please enter your last name: ")


full_name("Enas", l_name = last_name)

Example:
def show(name,msg="good morning"):
print("Hello", name, msg)

show("Rami",msg="How do you do") #Hello Rami How do you do


show(msg="How do you do",name="Sami") #Hello Sami How do you do
show(name="Rami","How do you do") #error

➢ 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.
Ex:
def my_function(*kids):
for i in kids:
print(i)

my_function("Nuha", "Suha", "Jhon")

➢ The pass Statement


Function definitions cannot be empty, but if you for some reason have a function definition
with no content, put in the pass statement to avoid getting an error.

Prepared By: Enas Abu Samra


Ex:
def myfunction():
pass

Examples of Functions:
Example1:
Write a returned-function that read 3 integer numbers (x, y, z) then call function that return
the average of numbers.
Sol:
def avg(n,m,o):
average = (n+m+o)/3
return average

x,y,z =int(input("Enter three integer numbers: ")), int(input()),


int(input())
print(avg(x,y,z))

Example2:
Write a return-function that takes an integer number as a parameter and check the number is
prime or not.
Sol:
def test_prime(n):
if (n==1):
return True
elif(n==2):
return True
else:
for x in range(2,n):
if(n % x==0):
return False
return True

print(test_prime(9))

Recursion
- Python also accepts function recursion, which means a defined function can call itself.
- The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of memory or

Prepared By: Enas Abu Samra


processor power. However, when written correctly recursion can be a very efficient and
mathematically-elegant approach to programming.

Example:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)

print(factorial(4))

How to track a Recursion Function?

Prepared By: Enas Abu Samra


Example of Recursion Function:
Write a Python program to find the greatest common divisor(gcd) of two integers using
recursion.
Sol:
def gcd(a, b):
low = min(a, b)
high = max(a, b)
if low == 0:
return high
elif low == 1:
return 1
else:
return gcd(low, high%low)

print(gcd(12,14))

Python Lambda
✓ A lambda function is a small anonymous (without name) function.
✓ A lambda function can take any number of arguments, but can only have one expression.
✓ Syntax: (Definition)
variable_name = Lambda arguments: expression
The expression is executed and the result is returned.

✓ Call:
print(variable_name(with/without lambda parameters))

Why Use Lambda Functions?


The power of lambda is better shown when you use them as an anonymous function inside another
function.
✓ Syntax: (Definition)
def myfunc(formal parameter list OR without parameters):
return lambda arguments: expression

✓ Call:
variable_name = myfunc(actual parameter list OR without parameters)
print(variable_name(with/without lambda parameters))

Prepared By: Enas Abu Samra


Examples of Lambda Function:
Example1: Write a lambda function that add 10 to argument a, and return the result
Sol:
x =lambda a : a +10
print(x(5))

Example2: Write a lambda function that multiply argument a with argument b and return the
result.
Sol:
x = lambda a, b : a * b
print(x(5, 6))

Example3: Write a lambda function that summarize argument a, b, and c and return the result.
Sol:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

Example4: Write a lambda function that doubles the number you send in.
Sol:
def myfunc(n):
return lambda a : a * n

mydoubler= myfunc(2)
print(mydoubler(11))

Example5: Write a lambda function that triples the number you send in.
Sol:
def myfunc(n):
return lambda a : a * n

mydoubler= myfunc(3)
print(mydoubler(11))

Prepared By: Enas Abu Samra


Important Examples:

Ex1:
def func(num1,num2):
num1 += 3
num2 -= 6
print("inside function num1= ", num1) #num1 = 8
print("inside function num2= ", num2) #num2 = 4

num1 = 5
num2= 10
func(num1,num2)
print("outside function num1= ", num1) # num1 = 5
print("outside function num2= ", num2) # num2 = 10

Ex2:
def process(x, y):
return x #just return this statement
y -= 1
return y
x, y = 3, 10
print(process(x, y))

Ex3:
def process(x, y):
x += 1
y -= 1
return x, y #return (4, 9)

x, y = 3, 10
print(process(x, y))

*********************************

Prepared By: Enas Abu Samra

You might also like