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

Python Lecture 4(Function)

Uploaded by

egilhani981
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python Lecture 4(Function)

Uploaded by

egilhani981
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

PYTHON PROGRAMMING

FUNCTIONS
Unit 4: FUNCTIONS

Python Programming : Lecture Four


Dr. Khalil Alawdi 2

Outline of This Lecture


• 4.0 Objectives
• 4.1 Introduction
• 4.2 Function Calls
• 4.3 Type Conversion Functions
• 4.4 Math Functions
• 4.5 Adding New Functions
• 4.6 Definitions and Uses
• 4.6.1 Flow of Execution
• 4.6.2 Parameters and Arguments
• 4.6.3 Variables and Parameters Are Local
• 4.6.4 Stack Diagrams 4.7 Fruitful Functions and Void Functions
• 4.7 Fruitful Functions and Void Functions
• 4.8 Why Functions?
• 4.9 Importing with from, Return Values, Incremental Development
• 4.10 Boolean Functions
• 4.11 More Recursion, Leap of Faith, Checking Types
• 4.12 Summary
• 4.13 References
• 4.14 Unit End Exercise

Python Programming : Lecture Four


Dr. Khalil Alawdi 3

Lecture Objectives
After reading through this chapter, you will be able to :

• To understand and use the function calls.

• To understand the type conversion functions.

• To understand the math function.

• To adding new function.

• To understand the Parameters and Arguments.

• To understand the fruitful functions and void functions.

• To understand the boolean functions, Recursion, checking types etc.

Python Programming : Lecture Four


Dr. Khalil Alawdi 4

INTRODUCTION
• One of the core principles of any programming language is, "Don't Repeat

Yourself". If you have an action that should occur many times, you can
define that action once and then call that code whenever you need to carry
out that action.

• We are already repeating ourselves in our code, so this is a good time to

introduce simple functions. Functions mean less work for us as


programmers, and effective use of functions results in code that is less error.

Python Programming : Lecture Four


Dr. Khalil Alawdi 5

FUNCTION CALLS
• What is a function in Python?

• In Python, a function is a group of related statements that performs a specific task.

• Functions help break our program into smaller and modular chunks. As our program grows

larger and larger, functions make it more organized and manageable.

• Furthermore, it avoids repetition and makes the code reusable.

• Syntax of Function

• def function_name(parameters):

• """docstring"""

• statement(s)

• Above shown is a function definition that consists of the following components. (Next Slide)

Python Programming : Lecture Four


Dr. Khalil Alawdi 6

FUNCTION CALLS
1. Keyword def that marks the start of the function header.

2. A function name to uniquely identify the function. Function naming follows the same
rules of writing identifiers in Python.

3. Parameters (arguments) through which we pass values to a function. They are optional.

4. A colon (:) to mark the end of the function header.

5. Optional documentation string (docstring) to describe what the function does.

6. One or more valid python statements that make up the function body. Statements must
have the same indentation level (usually 4 spaces).

7. An optional return statement to return a value from the function

Python Programming : Lecture Four


Dr. Khalil Alawdi 7

FUNCTION CALLS
• Example:
• def greeting(name):

• """ This function greets to the person passed in as a parameter """

• print ("Hello, " + name + ". Good morning!")

• How to call a function in python?


• Once we have defined a function, we can call it from another function, program or even the Python

prompt.

• To call a function we simply type the function name with appropriate parameters.

• >>> greeting(‘Ahmed')

• Hello, Ahmed. Good morning!

Python Programming : Lecture Four


Dr. Khalil Alawdi 8

TYPE CONVERSION FUNCTIONS


• The process of converting the value of one data type (integer, string, float, etc.) to another data

type is called type conversion. Python has two types of type conversion.

1. Implicit Type Conversion

2. Explicit Type Conversion

• (1) Implicit Type Conversion:

• In Implicit type conversion, Python automatically converts one data type to another data type. This

process doesn't need any user involvement.

• Let's see an example where Python promotes the conversion of the lower data type (integer) to the

higher data type (float) to avoid data loss.

Python Programming : Lecture Four


Dr. Khalil Alawdi 9

TYPE CONVERSION FUNCTIONS


• Example 1: Converting integer to float

• num_int = 123

• num_float = 1.23

• num_new = num_int + num_float

• print (“datatype of num_int:”, type(num_int))

• print (“datatype of num_float:” type(num_float))

• print (“Value of num_new:”, num_new)

• print (“datatype of num_new:”, type(num_new))

• Output:

• datatype of num_int: <class ‘int’>

• datatype of num_float: <class ‘float’>

• Value of num_new: 124.23

• datatype of num_new: <class ‘float’>

Python Programming : Lecture Four


Dr. Khalil Alawdi 10

TYPE CONVERSION FUNCTIONS


• Example 2: Addition of string(higher) data type and integer(lower) datatype
• num_int = 123
• num_str = "456"
• print ("Data type of num_int:”, type(num_int))
• print ("Data type of num_str:”, type(num_str))
• print(num_int+num_str)

• Output:
• Data type of num_int: <class ‘int’>
• Data type of num_str: <class ‘str’>
• Traceback (most recent call last):
• File "python", line 7, in

• TypeError: unsupported operand type(s) for +: 'int' and 'str'


• In the above program,
• We add two variables num_int and num_str.
• As we can see from the output, we got TypeError. Python is not able to use Implicit Conversion in such conditions.
• However, Python has a solution for these types of situations which is known as Explicit Conversion.

Python Programming : Lecture Four


Dr. Khalil Alawdi 11

TYPE CONVERSION FUNCTIONS


• (2) Explicit Type Conversion

• In Explicit Type Conversion, users convert the data type of an object to required data type. We use the

predefined functions like int(), float(), str(), etc to perform explicit type conversion.

• This type of conversion is also called typecasting because the user casts (changes) the data type of the

objects.

• Syntax:

• <Required data type(expression)

Python Programming : Lecture Four


Dr. Khalil Alawdi 12

TYPE CONVERSION FUNCTIONS


• Example 3: Addition of string and integer using explicit conversion

• num_int = 123

• num_str = "456"

• print ("Data type of num_int:”, type(num_int))

• print ("Data type of num_str before Type Casting:”, type(num_str))

• num_str = int(num_str)

• print ("Data type of num_str after Type Casting:”, type(num_str))

• num_sum = num_int + num_str

• print ("Sum of num_int and num_str:”, num_sum)

• print ("Data type of the sum:”, type(num_sum))

Python Programming : Lecture Four


Dr. Khalil Alawdi 13

TYPE CONVERSION FUNCTIONS


• Output:

• Data type of num_int: <class ‘int’>

• Data type of num_str before Type Casting: <class ‘str’>

• Data type of num_str after Type Casting: <class ‘int’>

• Sum of num_int and num_str: 579

• Data type of the sum: <class ‘int’>

• Type Conversion is the conversion of object from one data type to another data type.

• Implicit Type Conversion is automatically performed by the Python interpreter.

• Python avoids the loss of data in Implicit Type Conversion.

• Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions

by the user.

• In Type Casting, loss of data may occur as we enforce the object to a specific data type.

Python Programming : Lecture Four


Dr. Khalil Alawdi 14

MATH FUNCTIONS
• The math module is a standard module in Python and is always available. To use mathematical functions under this

module, you have to import the module using import math.

• For example
• # Square root calculation

• import math math.sqrt(4)

• Functions in Python Math Module Pi is a well-known mathematical constant, which is defined as the ratio of the

circumference to the diameter of a circle and its value is 3.141592653589793.


• >>> import math

• >>>math.pi 3.141592653589793

• Another well-known mathematical constant defined in the math module is e. It is called Euler's number and it is a base

of the natural logarithm. Its value is 2.718281828459045.


• >>> import math

• >>>math.e 2. 718281828459045

Python Programming : Lecture Four


Dr. Khalil Alawdi 15

MATH FUNCTIONS
• The math module contains functions for calculating various trigonometric ratios for a given angle. The

functions (sin, cos, tan, etc.) need the angle in radians as an argument. We, on the other hand, are used to
express the angle in degrees. The math module presents two angle conversion functions: degrees () and
radians (), to convert the angle from degrees to radians and vice versa.
• >>> import math

• >>>math.radians(30) 0.5235987755982988

• >>>math.degrees(math.pi/6) 29.999999999999996

• math.log()

• The math.log() method returns the natural logarithm of a given number. The natural logarithm is calculated to the

base e.
• >>> import math

• >>>math.log(10) 2.302585092994046

Python Programming : Lecture Four


Dr. Khalil Alawdi 16

MATH FUNCTIONS
• math.exp()
• The math.exp() method returns a float number after raising e to the power of the given number. In other words,
exp(x) gives e**x.
• >>> import math
• >>>math.exp(10) 22026.465794806718

• math.pow()
• The math.pow() method receives two float arguments, raises the first to the second and returns the result. In other
words, pow(4,4) is equivalent to 4**4.
• >>> import math
• >>>math.pow(2,4) 16.0
• >>> 2**4 16

• math.sqrt()

• The math.sqrt() method returns the square root of a given number.


• >>> import math
• >>>math.sqrt(100) 10.0
• >>>math.sqrt(3) 1.7320508075688772
Python Programming : Lecture Four
Dr. Khalil Alawdi 17

ADDING NEW FUNCTIONS


• So far, we have only been using the functions that come with Python, but it is
also possible to add new functions.
• A function definition specifies the name of a new function and the sequence of
statements that execute when the function is called.
• Example:
• def print_lyrics():
• print ("I'm a lumberjack, and I'm okay.")
• print ("I sleep all night and I work all day.")

• def is a keyword that indicates that this is a function definition. The name of the
function is print_lyrics. The rules for function names are the same as for
variable names: letters, numbers and some punctuation marks are legal, but the
first character can’t be a number. You can’t use a keyword as the name of a
function, and you should avoid having a variable and a function with the same
name.
Python Programming : Lecture Four
Dr. Khalil Alawdi 18

ADDING NEW FUNCTIONS


• The empty parentheses after the name indicate that this function doesn’t take
any arguments.
• The first line of the function definition is called the header; the rest is called the
body. The header has to end with a colon and the body has to be indented.
• By convention, the indentation is always four spaces .The body can contain any
number of statements.
• The strings in the print statements are enclosed in double quotes. Single quotes
and double quotes do the same thing; most people use single quotes except in
cases like this where a single quote appears in the string.
• Once you have defined a function, you can use it inside another function. For
example, to repeat the previous refrain we could write a function called
repeat_lyrics:

Python Programming : Lecture Four


Dr. Khalil Alawdi 19

ADDING NEW FUNCTIONS


• def repeat_lyrics():

• print_lyrics()

• print_lyrics()

• And then call repeat_lyrics:

• >>> repeat_lyrics()

• I'm a lumberjack, and I'm okay.

• I sleep all night and I work all day.

• I'm a lumberjack, and I'm okay.

• I sleep all night and I work all day.

Python Programming : Lecture Four


Dr. Khalil Alawdi 20

DEFINITIONS AND USES


• Pulling together the code fragments from the previous section, the whole
program looks like this:
• def print_lyrics ():
• print ("I'm a lumberjack, and I'm okay.")
• print ("I sleep all night and I work all day.")
• def repeat_lyrics ():
• print_lyrics () print_lyrics ()
• repeat_lyrics ()
• This program contains two function definitions: print_lyrics and repeat_lyrics.
Function definitions get executed just like other statements, but the effect is to
create function objects.
• The statements inside the function do not get executed until the function is
called, and the function definition generates no output.
Python Programming : Lecture Four
Dr. Khalil Alawdi 21

DEFINITIONS AND USES


• Pulling together the code fragments from the previous section, the whole
program looks like this:
• def print_lyrics ():
• print ("I'm a lumberjack, and I'm okay.")
• print ("I sleep all night and I work all day.")
• def repeat_lyrics ():
• print_lyrics () print_lyrics ()
• repeat_lyrics ()
• This program contains two function definitions: print_lyrics and repeat_lyrics.
Function definitions get executed just like other statements, but the effect is to
create function objects.
• The statements inside the function do not get executed until the function is
called, and the function definition generates no output.
Python Programming : Lecture Four
Dr. Khalil Alawdi 22

DEFINITIONS AND USES


• 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.
• Execution always begins at the first statement of the program. Statements are
executed one at a time, in order from top to bottom.
• Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the function
is called.
• A function call is like a detour in the flow of execution. Instead of going to the next
statement, the flow jumps to the body of the function, executes all the statements
there, and then comes back to pick up where it left off.
• When you read a program, you don’t always want to read from top to bottom.
Sometimes it makes more sense if you follow the flow of execution.
Python Programming : Lecture Four
Dr. Khalil Alawdi 23

DEFINITIONS AND USES


• Parameters and Arguments
• Some of the built-in functions we have seen require arguments. For example, when you call math.sin
you pass a number as an argument. Some functions take more than one argument: math.pow takes
two, the base and the exponent.
• Inside the function, the arguments are assigned to variables called parameters. Here is an example of a
user-defined function that takes an argument.
• def print_twice(bruce):
• print(bruce)
• print(bruce)
• This function assigns the argument to a parameter named bruce. When the function is called, it prints
the value of the parameter twice.
• >>> print_twice('Spam')
• Spam Spam
• >>> print_twice (17)
• 17 17
• >>> print_twice(math.pi)
• 3.14159265359 3.14159265359
Python Programming : Lecture Four
Dr. Khalil Alawdi 24

DEFINITIONS AND USES


• Parameters and Arguments
• The same rules of composition that apply to built-in functions also apply to
user-defined functions, so we can use any kind of expression as an argument
for print_twice.
• >>> print_twice ('Spam '*4)
• Spam SpamSpamSpam
• Spam SpamSpamSpam
• >>> print_twice(math.cos(math.pi))
• -1.0 -1.0
• The argument is evaluated before the function is called, so in the examples
the expressions 'Spam '*4 and math.cos(math.pi) are only evaluated once.

Python Programming : Lecture Four


Dr. Khalil Alawdi 25

DEFINITIONS AND USES


• Variables and Parameters Are Local
• When you create a variable inside a function, it is local, which means that it only
exists inside the function.
• For example
• def cat_twice(part1, part2):
• cat = part1 + part2
• print_twice(cat)
• This function takes two arguments, concatenates them, and prints the result twice.
Here is an example that uses it: >>> line1 = 'Bing tiddle ' >>> line2 = 'tiddle bang.'
>>> cat_twice(line1, line2) Bing tiddle tiddle bang. Bing tiddle tiddle bang.
• When cat_twice terminates, the variable cat is destroyed. If we try to print it, we get
an exception: >>> print cat NameError: name 'cat' is not defined
• Parameters are also local. For example, outside print_twice, there is no such thing
as bruce.
Python Programming : Lecture Four
Dr. Khalil Alawdi 26

DEFINITIONS AND USES


• Stack Diagrams
• To keep track of which variables can be used where, it is sometimes useful to draw a stack diagram.
Like state diagrams, stack diagrams show the value of each variable, but they also show the function
each variable belongs to.
• 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. The stack diagram for the previous example is shown
in Figure.

Python Programming : Lecture Four


Dr. Khalil Alawdi 27

DEFINITIONS AND USES


• Stack Diagrams
• The frames are arranged in a stack that indicates which function called which,
and so on. In this example, print_twice was called by cat_twice, and cat_twice
was called by __main__, which is a special name for the topmost frame.
When you create a variable outside of any function, it belongs to __main__.

• Each parameter refers to the same value as its corresponding argument. So,
part1 has the same value as line1, part2 has the same value as line2, and
bruce has the same value as cat.

• If an error occurs during a function call, Python prints the name of the
function, and the name of the function that called it, and the name of the
function that called that, all the way back to __main__.
Python Programming : Lecture Four
Dr. Khalil Alawdi 28

FRUITFUL FUNCTIONS AND VOID FUNCTIONS


• Some of the functions we are using, such as the math functions, yield results;
for lack of a better name, I call them fruitful functions. Other functions, like
print_twice, perform an action but don’t return a value. They are called void
functions.
• When you call a fruitful function, you almost always want to do something with
the result; for example, you might assign it to a variable or use it as part of an
expression:
• x = math.cos(radians)
• golden = (math.sqrt(5) + 1) / 2
• When you call a function in interactive mode, Python displays the result:
• >>>math.sqrt(5) 2.2360679774997898
• But in a script, if you call a fruitful function all by itself, the return value is lost
forever math.sqrt(5) This script computes the square root of 5, but since it
doesn’t store or display the result, it is not very useful.
Python Programming : Lecture Four
Dr. Khalil Alawdi 29

FRUITFUL FUNCTIONS AND VOID FUNCTIONS


• Void functions might display something on the screen or have some
other effect, but they don’t have a return value. If you try to assign
the result to a variable, you get a special value called None.
• >>> result = print_twice('Bing') Bing Bing
• >>> print(result) None
• The value None is not the same as the string 'None'. It is a special
value that has its own type:
• >>> print type(None)
• The functions we have written so far are all void.

Python Programming : Lecture Four


Dr. Khalil Alawdi 30

WHY FUNCTIONS?
• It may not be clear why it is worth the trouble to divide a program into functions.
There are several reasons:
• Creating a new function gives you an opportunity to name a group of
statements, which makes your program easier to read and debug.

• Functions can make a program smaller by eliminating repetitive code. Later, if


you make a change, you only have to make it in one place.

• Dividing a long program into functions allows you to debug the parts one at a
time and then assemble them into a working whole.
• Well-designed functions are often useful for many programs. Once you write
and debug one, you can reuse it.

Python Programming : Lecture Four


Dr. Khalil Alawdi 31

IMPORTING WITH FROM, RETURN VALUES,


INCREMENTAL DEVELOPMENT
• Importing with from: Python provides two ways to import modules,
we have already seen one:
• >>> import math
• >>> print math
• >>> print math.pi 3.14159265359

• If you import math, you get a module object named math. The
module object contains constants like pi and functions like sin and
exp. But if you try to access pi directly, you get an error.
• >>> print pi
• Traceback (most recent call last):
• File "", line 1, in <module>
• NameError: name 'pi' is not defined
Python Programming : Lecture Four
Dr. Khalil Alawdi 32

IMPORTING WITH FROM, RETURN VALUES,


INCREMENTAL DEVELOPMENT
• As an alternative, you can import an object from a module like this:
• >>> from math import pi
• Now you can access pi directly, without dot notation.
• >>> print pi 3.14159265359
• Or you can use the star operator to import everything from the module:
• >>> from math import *
• >>> cos(pi) -1.0
• The advantage of importing everything from the math module is that your
code can be more concise.
• The disadvantage is that there might be conflicts between names defined
in different modules, or between a name from a module and one of your
variables
Python Programming : Lecture Four
Dr. Khalil Alawdi 33

BOOLEAN FUNCTIONS
• Syntax for boolean function is as follows Bool([value])
• As we seen in the syntax that the bool() function can take a single parameter (value
that needs to be converted). It converts the given value to True or False.
• If we don’t pass any value to bool() function, it returns False.
• bool() function returns a boolean value and this function returns False for all the
following values
• 1. None

• 2. False

• 3. Zero number of any type such as int, float and complex. For example: 0, 0.0, 0j

• 4. Empty list [], Empty tuple (), Empty String ”.

• 5. Empty dictionary {}.

• 6. objects of Classes that implements __bool__() or __len()__ method, which returns 0 or False
Python Programming : Lecture Four
Dr. Khalil Alawdi 34

BOOLEAN FUNCTIONS
• Example: bool() function
• In the following example, we will check the output of bool() function for the given values. We
have different values of different data types and we are printing the return value of bool()
function in the output.
• # empty list
• lis = [] • Output:
• print(lis,'is',bool(lis))
• [] is False
• # empty tuple t = ()
• print(t,'is',bool(t)) • () is False
• # zero complex number
• c = 0 + 0j • 0j is False
• print(c,'is',bool(c))
• 99 is True
• num = 99
• print(num, 'is', bool(num)) • None is False
• val = None
• print(val,'is',bool(val)) • True is True
• val = True print(val,'is',bool(val))
• is False
• # empty string
• str = '' print(str,'is',bool(str)) • Hello is True
• str = 'Hello'
• print(str,'is',bool(str))
Python Programming : Lecture Four
Dr. Khalil Alawdi 35

MORE RECURSION, CHECKING TYPES


• What is recursion? Recursion is the process of defining something in terms of
itself. A physical world example would be to place two parallel mirrors facing
each other. Any object in between them would be reflected recursively.
• In Python, we know that a function can call other functions. It is even possible
for the function to call itself. These types of construct are termed as recursive
functions.

Python Programming : Lecture Four


Dr. Khalil Alawdi 36

MORE RECURSION, CHECKING TYPES


• Following is an example of a recursive function to find the factorial of an integer.
• Factorial of a number is the product of all the integers from 1 to that number.
• For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
• Example of a recursive function def factorial(x):
• """This is a recursive function to find the factorial of an integer"""
• if x == 1:
• return 1
• else:
• return (x * factorial(x-1))
• num = 3
• print("The factorial of", num, "is", factorial(num))

Python Programming : Lecture Four


Dr. Khalil Alawdi 37

MORE RECURSION, CHECKING TYPES


• Output:
• The factorial of 3 is 6
• In the above example, factorial () is a recursive function as it calls itself.
• When we call this function with a positive integer, it will recursively call itself by decreasing
the number.
• Each function multiplies the number with the factorial of the number below it until it is equal to
one.
• This recursive call can be explained in the following steps.
• factorial (3) # 1st call with 3
• 3 * factorial (2) # 2nd call with 2
• 3 * 2 * factorial (1) # 3rd call with 1 3 * 2 * 1 # return from 3rd call as number=1
• 3 * 2 # return from 2nd call
• 6 # return from 1st call

Python Programming : Lecture Four


Dr. Khalil Alawdi 38

SUMMARY
• In this chapter we studied function call, type conversion
functions in Python Programming Language.
• In this chapter we are more focused on math function and
adding new function in python.
• Elaborating on definitions and uses of function, parameters
and arguments in python.
• Also studied fruitful functions and void functions, importing
with from, boolean functions and recursion in python.
Python Programming : Lecture Four
Dr. Khalil Alawdi 39

UNIT END EXERCISE

Python Programming : Lecture Four


Dr. Khalil Alawdi 40

REFERENCES
• https://www.tutorialsteacher.com/python/math-module

• https://greenteapress.com/thinkpython/html/thinkpython004.html

• https://beginnersbook.com/

• https://www.programiz.com/python-programming/recursion

• www.journaldev.com

• www.edureka.com

• www.tutorialdeep.com

• www.xspdf.com

• Think Python by Allen Downey 1st edition.

Python Programming : Lecture Four

You might also like