0% found this document useful (0 votes)
46 views18 pages

Functionlec

Functions are blocks of code that perform specific tasks. There are two types of functions - built-in functions that are part of the Python language like len() and abs(), and user-defined functions. Functions allow for code reusability and modularization. Functions can accept parameters, return values, and have local and global scopes. Parameters are passed by value in Python.

Uploaded by

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

Functionlec

Functions are blocks of code that perform specific tasks. There are two types of functions - built-in functions that are part of the Python language like len() and abs(), and user-defined functions. Functions allow for code reusability and modularization. Functions can accept parameters, return values, and have local and global scopes. Parameters are passed by value in Python.

Uploaded by

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

Introduction to language - functions

What are functions


A function is a piece of code in a program. The function performs a specific task. The
advantages of using functions are:
•Reducing duplication of code
•Decomposing complex problems into simpler pieces
•Improving clarity of the code
•Reuse of code
•Information hiding

Functions in Python are first-class citizens. It means that functions have equal status
with other objects in Python. Functions can be assigned to variables, stored in
collections or passed as arguments. This brings additional flexibility to the language.

Function types
There are two basic types of functions. Built-in functions and user defined ones. The
built-in functions are part of the Python language. Examples are: dir(), len() or abs().
Using the Math Library
Using the Math Library: An Example
#To call a function from the math library, we can use the
#dot operator as follows:
s_root_val = math.sqrt(b*b - 4 * a * c)
root1 = (-b + s_root_val)/(2*a)
root2 = (-b - s_root_val)/(2*a)

print()
print("The solutions are: ", root1, root2)

#Call the function rootsQEq()


rootsQEq()
Functions
• Function: Equivalent to a static method in Java.

hello2.py
• Syntax:
# Prints a helpful message. 1
def name(): def hello(): 2
statement print("Hello, world!") 3
4
statement # main (calls hello twice) 5
... hello() 6
hello() 7
statement

 Must be declared above the 'main' code


 Statements inside the function must be indented
 Python uses indentation to indicate blocks, instead of {}
4
Defining Functions
Function definition begins with “def.” Function name and its arguments.

def get_final_answer(filename):
def my_function(): “““Documentation String”””
  print("Hello ") line1
line2 Colon.
return total_counter

The indentation matters…


First line with less
indentation is considered to be The keyword ‘return’ indicates the
outside of the function definition. value to be sent back to the caller.

No header file or declaration of types of function or arguments


Formal Definition of Functions
• Formally, a function can be defined as follows:
def <name>(<formal-parameters>):
<body>
• The <name> of a function should be an identifier and
<formal-parameters> is a (possibly empty) list of variable
names (also identifiers)

• <formal-parameters> and all local variables declared in a


function are only accessible in the <body> of this function

• Variables with identical names declared elsewhere in a


program are distinct from <formal-parameters> and local
variables inside a function’s <body>
def my_function(fname):
  print(fname )

my_function(“zana")
my_function(“ali")
my_function(“ ahmed")
Local Variables
• Consider the following code

def func1(x, y): 234


#local scope Traceback (most recent call last):
    z=4   File "func1.py", line 6, in
        print(x, y, z) <module>
    print(x, y, z)
Run
func1(2, 3) NameError: name 'x' is not
print(x, y, z) defined

x, y, and z belong solely to the scope of func1(...) and can only be


accessed inside func1(…); z is said to be local to func1(…), hence,
referred to as a local variable
Global Variables
• Consider the following code
#global scope
x = 100
  
def func2(): 100
Run
        print(x) 100

func2()
print(x)
x is said to be a global variable since it is defined within the
global scope of the program and can be, subsequently, accessed
inside and outside func2()
Local vs. Global Variables
• Consider the following code

x = 100
  
def func3():
        x = 20 20
Run
        print(x) 100

func3()
print(x)
The global variable x is distinct from the local variable x inside
func3()
Parameters vs. Global Variables
• Consider the following code

x = 100
  
def func4(x):
        print(x) 20
Run
100
func4(20)
print(x)

The global variable x is distinct from the parameter x of func4(…)


The global Keyword
• Consider the following code

def func5():
        global x
        x = 20
        print(x) 20
Run
20
func5()
print(x)

The global keyword binds variable x in the global scope; hence,


can be accessed inside and outside func5()
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))
Getting Results From Functions
• We can get information from a function by having it return
a value

>>> def square(x): >>> def cube(x): >>> def power(a, b):
...     return x * x ...     return x * x * x ...     return a ** b
...  ...  ... 
>>> square(3) >>> cube(3) >>> power(2, 3)
9 27 8
>>>  >>>  >>> 
Pass By Value
• Consider the following code
def addInterest(balance, rate):
    newBalance = balance * (1+rate)
    return newBalance

def test():
    amount = 1000
    rate = 0.05
  nb = addInterest(amount, rate)
    print(nb)

test()
1050.0
Pass By Value vs. Returning a Value
• Consider the following code
def increment_func(x):
def increment_func(x):     x=x+1
    x=x+1         return x

x=1 x=1
increment_func(x) x = increment_func(x)
print(x) print(x)

Run
Run

1 2
Passing a List as a Parameter
You can send any data types of parameter to a
function (string, number, list, dictionary etc.), and
it will be treated as the same data type inside the
.function

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

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

my_function(fruits)
Default Values for Arguments
 You can provide default values for a function’s arguments
 These arguments are optional when the function is called

>>> def myfun(b, c=3, d=“hello”):


return b + c
>>> myfun(5,4,”goodby”)
>>> myfun(5,6)
>>> myfun(5)
def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

You might also like