You are on page 1of 92

Click icon to add picture

FUNCTIONS -9

Basimah Aljhne
11/05/2023
Click icon to add picture
1. An Introduction to Function in Python
2. User-defined Functions
3. Example
AN INTRODUCTION TO Click icon to add picture

FUNCTION IN PYTHON

1. What is function?
2. Why Using them?
3. Where do the functions come from?
What is Function?

When you want some data to be printed on the console print()

When you want to read the value of a variable input()

When you want to know the number of characters in string len()

4
What is Function?

Group of statements within a program that perform specific task.


 Usually one task of a large program

There are two kinds of functions in Python

Built-in functions

That are provided as part of Python.


For example: float(), int() ...

User-defined Functions

5
Why have them?

• Functions help divide a program into modules.


This makes the code easier to manage,
debug.
• Simplify code. More readable
• Reuse. Once written, use again
• Sharing. If tested, others can use

6
Program: Program:
Output:
def thing():
print('Hello’)
print ('Hello’)
print ('Fun’)
print ('Fun’)
Hello
Fun
print (‘python’) python
thing()
print (‘python’) Hello
print('Hello’)
thing() Fun
print ('Fun’)
thing() Hello
print('Hello’) Fun
print ('Fun’)

We call these Reuse. Once written, use again 7


Where do the functions come from?

In general, functions come from at least three places:


from Python itself – numerous
functions (like print()) are an integral part of Python, and are always available without
any additional effort on behalf of the programmer; we call these functions built-in
functions
from Python’s preinstalled modules
a lot of functions, very useful ones, but used significantly less often than built-in ones,
are available in a number of modules installed together with Python.
directly from your code
you can write your own functions, place them inside your code, and use them freely;

8
USER-DEFINED FUNCTIONS Click icon to add picture
1. Defining a Function in Python
2. Flow of Control With Functions
3. Rules for naming python function (identifier)
4. Python Function Parameters
5. Function Arguments
6. Python return Statement
7. Scope and Lifetime of Variables in Python
8. How to write a function
1. Defining a Function in Python

Function_Body.

execution.
function_name(parameter,parmater) 10
2. Flow of Control With Functions

Function

def area_square (side) :


area =side*side
Main Program return area

Statement
Statement
Var_Value Var_Name
result= area_square (2)
result
print(result)
Statement
Statement
11
2. Flow of Control With Functions

Function

def area_square (side) : 2


area =side*side
Main Program return area

Statement
Statement
Var_Value Var_Name
result= area_square (2)
result
print(result) side 2
Statement
Statement
12
2. Flow of Control With Functions

Function

def area_square (side) :


area =side*side
Main Program return area

Statement
Statement
Var_Value Var_Name
result= area_square (2)
result
print(result) side 2
Statement area 4
Statement
13
2. Flow of Control With Functions

Function

def area_square (side) :


area =side*side
Main Program return area

Statement
Statement 4
Var_Value Var_Name
result= area_square (2)
result 4
print(result) side 2
Statement area 4
Statement
14
3. Rules for naming python function (identifier)

• To define your own Python function, you use the ‘def’


keyword before its name. And its name is to be followed
by parentheses, before a colon(:)
• The contents inside the body of the function must be
equally indented.
• You may use a docstring right under the first line of a
function declaration. This is a documentation string, and it
explains what the function does.

15
3. Rules for naming python function (identifier)

• We follow the same rules when naming a function as we


do when naming a variable.
• It can begin with either of the following: A-Z, a-z, and
underscore(_).
• The rest of it can contain either of the following: A-Z, a-z,
digits(0-9), and underscore(_).
• A reserved keyword may not be chosen as an identifier.
• It is good practice to name a Python function according to
what it does. 16
USER-DEFINED FUNCTIONS Click icon to add picture
1. Defining a Function in Python
2. Flow of Control With Functions
3. Rules for naming python function (identifier)
4. Python Function Parameters
5. Function Arguments
6. Python return Statement
7. Scope and Lifetime of Variables in Python
8. How to write a function
2: What happens when you try to invoke a function before you define it?
Q3: Which of the following statement is true?
Functions are used to create objects in Python.

Functions make your program run faster.

A function is a piece of code that performs a specific task.

All of the above

19
Q4:what is the output?

20
Q5:What is the output of the following code? Explain why.

21
What is the output of the following code? Explain why.

22
What is the output of the following code? Explain why.

23
: What is the output of the following code? Explain why.
4. Python Function Parameters
A parameter is a variable , but there are two
important factors that make parameters different
and special:
 They exist only inside functions in which they
have been defined, and the only place where
the parameter can be defined is a space
between a pair of parentheses in
the def statement; Don’t forget:
parameters live inside functions
 Assigning a value to the parameter is done at (this is their natural environment)
the time of the function’s invocation, by arguments exist outside functions,
specifying the corresponding argument. and are carriers of values passed
to corresponding parameters.
26
4. Python Function Parameters

a=2 b=5

27
5. Function 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 parenthesis after the name of the function

Calling a Python function

• To call a Python function at a place in your


code, you simply need to name it, and pass
arguments, if any.
28
Value Symbol Name
Basimah
name

29
5. Function Parameters

Types of Python Function Parameters

 Default Parameters in Python


 Python Keyword Parameters
 Passing any number of parameters

30
1. Default Parameters in Python

• Python Program Parameters can have default values.


• We assign a default value to an Parameters using the assignment operator
in python(=).
• When we call a function without a value for an argument, its default value
(as mentioned) is used.

Default value

Calling function in
different way
31
Value Symbol Name
User name
Basimah

32
2. Python Keyword Parameters

• With keyword Parameters in python, we can change the order of passing the
arguments without any consequences.

Using argument name to pass the value.


b and c will have their defaults
33
3. Passing any number of parameters

• You may not always know how many arguments you’ll get.
• In that case, you use an asterisk(*) before an argument name.

Value Symbol Name


a ,b],c ,dname
[ *

34
Q6: What is the output of the following snippet?
Q7: What is the output of the following snippet?
USER-DEFINED FUNCTIONS Click icon to add picture
1. Defining a Function in Python
2. Flow of Control With Functions
3. Rules for naming python function (identifier)
4. Python Function Parameters
5. Function Arguments
6. Python return Statement
7. Scope and Lifetime of Variables in Python
8. How to write a function
What is the output of the following code?

5
Error
Value Symbol Name
7
n 2
8

38
Write a function that takes the final scores of two soccer
teams as arguments and prints either who won the game
or whether the game was tied.
Refer to the teams as “Team1” and “Team2.”
What is my
arguments?

39
USER-DEFINED FUNCTIONS Click icon to add picture
1. Defining a Function in Python
2. Flow of Control With Functions
3. Rules for naming python function (identifier)
4. Python Function Parameters
5. Function Arguments
6. Python return Statement
7. Scope and Lifetime of Variables in Python
8. How to write a function
USER-DEFINED FUNCTIONS Click icon to add picture
Don’t forget:
1. Defining a Function in Python
2. Flow of Control With Functions
parameters live inside functions
3. Rules for naming python function (identifier) (this is their natural environment)
4. Python Function Parameters arguments exist outside functions,
5. Function Arguments and are carriers of values passed
6. Python return Statement to corresponding parameters.
7. Scope and Lifetime of Variables in Python
8. How to write a function
Types of Python Function Parameters

Default Parameters in Python

Passing any number of parameters

Python Keyword Parameters


USER-DEFINED FUNCTIONS Click icon to add picture
1. Defining a Function in Python
2. Flow of Control With Functions
3. Rules for naming python function (identifier)
4. Python Function Parameters
5. Function Arguments
6. Python return Statement
7. Scope and Lifetime of Variables in Python
8. How to write a function
6. Python return Statement

 Return Effects and Results

 A value-returning function

 A void function
 Multiple returns in a function

44
6. Python return Statement

 A value-returning function

• Executes the statements it contains, and then it returns a value back to


the statement that called it.

45
6. Python return Statement

What If There Is No Return Statement?


Sometimes we write functions without a return statement. Functions that do not
return a value are often called procedures or a void function

In that case, what, if anything, is returned?


is that a special Python value None is returned by default if the programmer does
not provide a return statement.

46
6. Python return Statement

 A void function
• Simply executes the statements it contains and then it returns a None
value

This function not return


anything hence output is
None

47
python return Statement

• A Python function may optionally return a value.


• As soon as a return statement is reached in a
function, the function stops executing.
• Return means the task is done and now you need
to return from where you came with the specified
data
• You can return any type of data, you can even
return a function.
• If the function fails to execute the return statement
then it will return nothing and if there is data with
the return then it will also return none 48
python return Statement
• It is the last statement executed by a function.

49
python return Statement
• It is the last statement executed by a function.

print(func1())

50
python return Statement
• It is the last statement executed by a function.

print(func1())

51
6. Python return Statement

 Multiple returns in a function


• A function can have multiple return statements.
• Remember, the first return statement executed ends the function.
• Multiple returns can be confusing to the reader and should be used
judiciously.

52
0

53
0

54
55
USER-DEFINED FUNCTIONS Click icon to add picture
1. Defining a Function in Python
2. Flow of Control With Functions
3. Rules for naming python function (identifier)
4. Python Function Parameters
5. Function Arguments
6. Python return Statement
7. Scope and Lifetime of Variables in Python
8. How to write a function
If return statement is not used inside the function, the
function will return:

0
None object
Random integer

Error! Functions in Python must have a return statement.

57
Write a Function that takes as input unknown integers and
returns the average of the values.

What is my arguments?
How many return should I
have?

58
Write a Function that takes as input unknown integers and
returns the average of the values.

59
Write a Function that takes as input two words and return
True if both start with the same character, and False if
not.
Note that:
Case distinction is ignored
What is my arguments?
How many return should I
have?

60
61
8. Scope and Lifetime of Variables in Python

• A variable isn’t visible everywhere and alive every time.


• We study this in functions because the scope and lifetime for a variable depend on
whether it is inside a function.

62
8. Scope and Lifetime of Variables in Python
1. Scope
The scope of a variable refers to the places that you can see or access a variable.
A variable may have local or global scope.

 Local Scope

 Global Scope

63
8. Scope and Lifetime of Variables in Python

Local Scope
A variable that’s declared inside a function has a local scope.
In other words, it is local to that function.
If you then try to access the variable x outside the function, you cannot.

I am a local variable
scope
No one outside this
function can see me

64
8. Scope and Lifetime of Variables in Python

Global Scope
• When you declare a variable outside python functions, or anything else, it has global
scope.
• It means that it is visible everywhere within the program.

Hi, I am visible
everywhere within
the program.

65
8. Scope and Lifetime of Variables in Python

Global Scope
• When you declare a variable outside python functions, or anything else, it has global
scope.
• It means that it is visible everywhere within the program.
• However, you can’t change its value from inside a local scope
(here, inside a function).
you can see me but
you can’t change me
from inside local
scope

66
8. Scope and Lifetime of Variables in Python

Python global Keyword

• In Python, global keyword allows you to modify the variable outside of the current
scope.
• It is used to create a global variable and make changes to the variable in a local
context.

you can change me


from inside local
scope

X=7
X=2
67
Rules of global Keyword

• The basic rules for global keyword in Python are:


• When we create a variable inside a function, it’s local by default.
• When we define a variable outside of a function, it’s global by default.
You don’t have to use global keyword.
• Use of global keyword outside a function has no effect
• We use global keyword to modify a global variable from a local Scope

68
8. Scope and Lifetime of Variables in Python

2. Lifetime

• The lifespan of a variable local to a function is from the time it is created in the
function’s run, until the function ends (and the memory allocated to the variable is
released) It’s the same for parameters to that function also.

69
8. Scope and Lifetime of Variables in Python

2. Lifetime

• The lifespan of a variable local to a function is from the time it is created in the
function’s run, until the function ends (and the memory allocated to the variable is
released) It’s the same for parameters to that function also.

x=cs111
70
8. Scope and Lifetime of Variables in Python

2. Lifetime

• The lifespan of a variable local to a function is from the time it is created in the
function’s run, until the function ends (and the memory allocated to the variable is
released) It’s the same for parameters to that function also.

x=cs111
71
8. Scope and Lifetime of Variables in Python

2. Lifetime

• The lifespan of a variable local to a function is from the time it is created in the
function’s run, until the function ends (and the memory allocated to the variable is
released) It’s the same for parameters to that function also.

X=“defult”

72
8. Scope and Lifetime of Variables in Python

2. Lifetime

• The lifespan of a variable local to a function is from the time it is created in the
function’s run, until the function ends (and the memory allocated to the variable is
released) It’s the same for parameters to that function also.

73
8. Scope and Lifetime of Variables in Python

2. Lifetime

• The lifespan of a variable local to a function is from the time it is created in the
function’s run, until the function ends (and the memory allocated to the variable is
released) It’s the same for parameters to that function also.
• If a function with locals is called several times, then those variables are created and
destroyed, created and destroyed, over and over for each call, their lifespan is
intermittent

74
8. Scope and Lifetime of Variables in Python

2. Lifetime

• The lifespan of a variable local to a function is from the time it is created in the
function’s run, until the function ends (and the memory allocated to the variable is
released) It’s the same for parameters to that function also.
• If a function with locals is called several times, then those variables are created and
destroyed, created and destroyed, over and over for each call, their lifespan is
intermittent
• The lifespan of a global variable is from the time its definition is encountered during
the execution of the whole program, until the program is finished 75
USER-DEFINED FUNCTIONS Click icon to add picture
1. Defining a Function in Python
2. Flow of Control With Functions
3. Rules for naming python function (identifier)
4. Python Function Parameters
5. Function Arguments
6. Python return Statement
7. Scope and Lifetime of Variables in Python
8. How to write a function
1

Value Symbol Name


n 1

77
USER-DEFINED FUNCTIONS Click icon to add picture
1. Defining a Function in Python
2. Flow of Control With Functions
3. Rules for naming python function (identifier)
4. Python Function Parameters
5. Function Arguments
6. Python return Statement
7. Scope and Lifetime of Variables in Python
8. How to write a function
9. How to write a function

• Does one thing. If it does too many things, it should be broken down into
multiple functions (refactored)
• Readable. How often should we say this? If you write it, it should be
readable
• Reusable .If it does one thing well, then when a similar situation (in another
program) occurs, use it there as well.
• Complete. A function should check for all the cases where it might be
invoked. Check for potential errors.
• Not too long. Kind of synonymous with do one thing. Use it as a measure of
doing too much.

79
Reminder, rules so far
1. Think before you program!
2. A program is a human-readable essay on problem solving that also happens to
execute on a computer.
3. The best way to improve your programming and problem solving skills is to
practice!
4. Test your code, often and thoroughly
5. If it was hard to write, it is probably hard to read. Add a comment.
6. A function should do one thing.

80
USER-DEFINED FUNCTIONS Click icon to add picture
1. Defining a Function in Python
2. Flow of Control With Functions
3. Rules for naming python function (identifier)
4. Python Function Parameters
5. Function Arguments
6. Python return Statement
7. Scope and Lifetime of Variables in Python
8. How to write a function
What is the output of the following code? Explain why.

82
What is the output of the following code? Explain why.

83
What is the output of the following code? Explain why.

84
What is the output of the following code? Explain why.

85
What is the output of the following code? Explain why.

86
Important to do at home :
Read chapter 6

87
Click icon to add picture
EXAMPLE
Exercises

Write a Function that takes as input an integer value and returns the sum
of all integers less than that value.
For example,
if the input is 6, the output is 5+4+3+2+1 = 15.
If the input is negative, the output should be -1.

What is my arguments?
How many return should I have?

89
Exercises

Write a Python function that take from the user the range limit and
then take test number and check whether a number is in a given
range

90
Exercises

Write a Python function that take from the user the range limit.
if start less than end the swab between them and then print the all
numbers between them

91
1) Write a Python function that take list
then return a copy from the list.

2) Write a Python function that takes


two lists and returns True if they
have at least one common member .

3) Write a Python program to print a specified list after removing the 0th,
4th and 5th elements.

You might also like