Chapter2(Functions)
Chapter2(Functions)
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.
➢ Types of functions:
1. Pre-Defined Functions.
2. User-Defined Functions:
✓ Void Functions.
✓ Value-Returning Functions.
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.
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.
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()
➢ 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.
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()
Example:
def full_name (f_name, l_name):
print ("Your full name is:")
print (f_name,l_name)
print("***************")
➢ Keyword Arguments
Example:
def full_name (f_name, l_name):
print ("Your full name is:")
print (f_name,l_name)
print("***************")
➢ 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)
Example:
Example:
def show(name,msg="good morning"):
print("Hello", name, msg)
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
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
Example:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(4))
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))
✓ Call:
variable_name = myfunc(actual parameter list OR without parameters)
print(variable_name(with/without lambda parameters))
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))
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))
*********************************