Python Lecture 4(Function)
Python Lecture 4(Function)
FUNCTIONS
Unit 4: FUNCTIONS
Lecture Objectives
After reading through this chapter, you will be able to :
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.
FUNCTION CALLS
• What is a function in Python?
• Functions help break our program into smaller and modular chunks. As our program grows
• Syntax of Function
• def function_name(parameters):
• """docstring"""
• statement(s)
• Above shown is a function definition that consists of the following components. (Next Slide)
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.
6. One or more valid python statements that make up the function body. Statements must
have the same indentation level (usually 4 spaces).
FUNCTION CALLS
• Example:
• def greeting(name):
prompt.
• To call a function we simply type the function name with appropriate parameters.
• >>> greeting(‘Ahmed')
type is called type conversion. Python has two types of type conversion.
• In Implicit type conversion, Python automatically converts one data type to another data type. This
• Let's see an example where Python promotes the conversion of the lower data type (integer) to the
• num_int = 123
• num_float = 1.23
• Output:
• 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
• 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:
• num_int = 123
• num_str = "456"
• num_str = int(num_str)
• Type Conversion is the conversion of object from one data type to another data type.
• 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.
MATH FUNCTIONS
• The math module is a standard module in Python and is always available. To use mathematical functions under this
• For example
• # Square root calculation
• Functions in Python Math Module Pi is a well-known mathematical constant, which is defined as the ratio of the
• >>>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
• >>>math.e 2. 718281828459045
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
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()
• 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
• print_lyrics()
• print_lyrics()
• >>> repeat_lyrics()
• 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
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.
• 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.
• 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
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
• 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
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
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