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

Chapter 04 Python

Chapter 04 covers Python functions, modules, and packages, emphasizing the importance of functions for code reusability and organization. It explains built-in and user-defined functions, type conversion, function arguments, and the scope of variables. Additionally, it discusses modules as a way to structure Python code and how to create and import them for use in programs.

Uploaded by

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

Chapter 04 Python

Chapter 04 covers Python functions, modules, and packages, emphasizing the importance of functions for code reusability and organization. It explains built-in and user-defined functions, type conversion, function arguments, and the scope of variables. Additionally, it discusses modules as a way to structure Python code and how to create and import them for use in programs.

Uploaded by

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

CHAPTER 04

Python Functions,Modules,and Packages(14 Marks)


Course Outcome

Use Develop Write Write


Use the Python Develop relevant user Write python module for Write python package
standard functions for defined functions for the given problem. for the given problem.
the given problems. the given problem using
Python code.
Agenda
Introduction : Why use function?
Functions reduce lines of code in your main program by letting you avail predefined features
multiple times without having to repeat its set of codes again.
What are functions?

A function is a block of organized , reusable code that is used to perform some task.
• It is usually called by its name when its task need execution.
• You can also pass values to it or have it return results to you.

Functions are tasks that one wants to perform.


◦ Functions are the self-contained block of statements that acts like a
program that performs specific task.
◦ The python interpreter has a number of functions that are always
available for use. These functions are called built-in functions . 4.1 Use of Python
◦ For Example, print() function prints the given object to the standard
output device(screen) or to the text stream file.
Built-in Function
◦ Python built-in functions can be used to perform specific tasks. Some
of these functions comes in category of mathematical functions and
some are called type conversion functions and so on.
4.1.1
Type Data Conversion
Functions
◦ Python defines type conversion functions to
directly convert one data type to another.

◦ Data conversion in python can happen in


following two ways:

◦ Either we tell compiler to convert a data


type to some other type explicitly, and/or

◦ The compiler understands this by itself and


does it for us.
What is Typecasting in Python?

Convert one data type to another data type is called typecasting. Some situations, when
you want to convert the data type.

For example, you want to add two numbers in which one existing value of a variable is an
integer and the second is a string.

Then you need to use Python typecasting to convert string data type in integer before
adding.
Why and When to Use Type-casting in Python?
◦ Casting is when you convert a variable value from one type to another. That is, in Python, done with
functions like int() or float() or str(). A pattern is that you convert a number as a string into a number.

◦ The practice of converting the value of a single data type (integer, string, float, etc.) to a different data
type is known as type conversion.

◦ Python includes two types of type conversion:

• Explicit Conversion

• Implicit Conversion
Python Implicit Data
Type Conversion
Python Explicit Data Type Conversion
CHAPTER 04
Python Functions,Modules,and Packages(14 Marks)
◦ Built-In Mathematical Functions
◦ User Defined Functions
◦ Function definition
◦ Function calling
◦ Function arguments
Agenda
◦ Function parameters
◦ Return statement
◦ Scope of a variable
Built-In Mathematical Functions
◦ Function can be described as a piece of code that may or may not take some value(s) as input,
process it, and then finally may or may not return any value as output.
◦ Python’s math module is used to solve problems related to mathematical calculations.
◦ Some functions are directly executed for maths functions we need to import math module first.
◦ In python, there are two types of pre-defined functions:
• Inbuilt functions(Mathematical):
• These are the functions which doesn't require any other(external) code file (known
as, Modules or Library Files). These are a part of the python core and are just built within the
Python compiler hence there is no hassle of importing these modules/libraries in our code.
• Built-in Functions(Math Module):
• The second type of functions require some external files(modules) in order to be used. The process
of using these external files in our code is called importing. So all we have to do is import the file
into our code and use the functions which are already written in that file.
What Is A Function?
◦ A function is a group of Python statements that work together to perform a task.

◦ Examples : Input
◦ A function that calculates the gas mileage of a car
◦ A function that darkens the color of an image
◦ A function that counts the number of words in a text file
◦ A function that prints text to screen Function Name Statement 1
Statement 2
◦ Properties of a Function:
◦ Contains multiple statements …
◦ Has a name Statement N
◦ Can accept one or more input data
to work with them
◦ Can produce one output data Output
4.2 User Defined Functions
◦ Function Definition:
◦ Function definition is a block where the statements inside the function body are written.
◦ Functions allow us to define a reusable block of code that can be used repeatedly in a program.
Syntax:
def function_name(argument1, argument2, ...) :
“function_docstring”
function statements
return[expression]

Let's understand the syntax of functions definition.


•The def keyword, along with the function name is used to define the function.
•The identifier rule must follow the function name.
•A function accepts the parameter (argument), and they can be optional.
•The function block is started with the colon (:), and block statements must be at the same indentation.
•The return statement is used to return the value. A function can have only one return
Example: Output:
FUNCTION DOCSTRING
◦ Python has a feature called documentation strings, usually referred as docstrings. DocStrings are an important tool
that you should make use of since it helps to document the program better and makes it easier to understand.

◦ Docstrings provide a convenient way of associating documentation with Python modules, functions, classes, and methods.

◦ It's specified in source code that is used, like a comment, to document a specific segment of code.

◦ This allows the program to inspect these comments at run time, for instance as an interactive help system, or as metadata

◦ The doc string line should begin with a capital letter and end with a period. The first line should be a short description.

def my_function(): >>> print my_function.__doc__


"""Do nothing, but document it. Do nothing, but document it.
No, really, it doesn't do anything. """ No, really, it doesn't do anything.
pass
Example: Output:
Functions that we define ourselves to do the certain specific task are
referred to as user-defined functions. The way in which we define and
call functions in Python are already discussed.

What Are User- Functions that readily come with Python are called built-in functions.
If we use functions written by others in the form of the library, it can
Defined Functions be termed as library functions.

In Python? All the other functions that we write on our own fall under user-
defined functions. So, our user-defined function could be a library
function to someone else.

v User defined functions are the functions that programmers create for their requirement and use.
v These functions can then be combined to form module which can be used in other programs by importing them.
1. User-defined functions help to decompose a large program into small
segments which makes the program easy to understand, maintain and
debug. Advantages of User-
2. If repeated code occurs in a program. The function can be used to
include those codes and execute when needed by calling that function.
Defined functions
3. Programmers working on a large project can divide the workload by
making different functions.
Function Calling
◦ The def statement only creates a function but does not call it. After
the def has run,

◦ We can call(run) the function by adding parentheses after the


functions name.

◦ In Python, after the function is created, we can call it from another


function.

◦ A function must be defined before the function call; otherwise, the


Python interpreter gives an error.

◦ To call the function, use the function name followed by the


parentheses.
Consider the following example of a simple example that prints the message
"Hello World".
Function Arguments And Parameter
Passing
◦ Parameters vs Arguments

◦ It is recommended to understand what are arguments and parameters


before proceeding further.

◦ Vocabulary parameters and arguments are not limited to python, but they
are same across different programming languages.

◦ Arguments are values that are passed into function(or method) when the
calling function
Parameters are variables(identifiers) specified in the (header of) function
definition.
Concept of Actual And Formal Parameters

Formal arguments are identifiers used in the function definition to represent corresponding actual arguments.

Actual arguments are values(or variables)/expressions that are used inside the parentheses of a function call.
Function Arguments
Types of formal Arguments are:
◼ Default Arguments
◼ Keyword Arguments
◼ Required Arguments
◼ Variable-length Arguments
◼ Keyword–only Parameters
Default Argument Values
◼ For some functions, you may want to make some parameters as optional and use default values if the
user does not want to provide values for such parameters.
◼ This is done with the help of default argument values.
◼ Note that the default argument value should be immutable.
◼ you cannot use mutable objects such as lists for default argument values.

Note : Only those parameters which are at the end


of the parameter list can be given as default
argument values.
For Eg. def fun (a,b=5)→valid
def fun (a=1,b) → Invalid
Keyword Arguments
◼ If you have some functions with many parameters and you want to specify only some parameters, then
you can give values for such parameters by naming them this is called keyword arguments.
◼ We use the name instead of the position which we have been using all along.
◼ This has two advantages - One, using the function is easier since we do not need to worry about the
order of the arguments.
◼ Two, we can give values to only those parameters which we want, provided that the other parameters
have default argument values.
Required Arguments
◼ Required arguments are the arguments passed to a function in correct positional order. Here the
number of arguments in the function call should match exactly with the function definition.
◼ To call the function printme() you definitely need to pass one argument otherwise it would give a
syntax error
Variable Length Arguments
◼ You may need to process a function for more arguments than you specified while defining the function.
◼ These arguments are called variable-length arguments and are not named in the function definition,
unlike required and default arguments.
◼ The syntax is

An asterisk (*) is placed before the variable name that will hold the values of all non-keyword
variable arguments. This tuple remains empty if no additional arguments are specified during the
function call.
Example For Variable Length Arguments
Note :
➢ When we declare a starred parameter
such as *param, then all the positional
arguments from that point till the end are
collected as a list called 'param'.
➢ When we declare a double-starred
parameter such as **param, then all the
keyword arguments from that point till
the end are collected as a dictionary
called 'param'.
Keyword-only Parameters
◼ If we want to specify certain keyword parameters to be available as keyword-only and not as positional
arguments, they can be declared after a starred parameter
Return Statement
◼ The return statement is used to return from a function i.e. break out of the function. We can optionally return a value from the
function as well.
◼ The return statement is followed by an expression which is evaluated.
◼ Every function implicitly contains a return None statement. You can see this by running print someFunction() where the function
someFunction does not use the return statement

Example:
Scope of Variable

Parameters and variables defined


Scope of a variable is the portion of a
inside a function is not visible from
program where the variable is
outside. Hence, they have a local
recognized
scope.

Lifetime of a variable is the period


They are destroyed once we return
throughout which the variable exits in
from the function. Hence, a function
the memory. The lifetime of variables
does not remember the value of a
inside a function is as long as the
variable from its previous calls.
function executes.
LOCAL VARIABLES : Whenever you define a variable within
a function, its scope lies ONLY within the function. It is
accessible from the point at which it is defined until the end
of the function and exists for as long as the function is
executing (Source). Which means its value cannot be
Global Variable changed or even accessed from outside the function.

And Local Variable


GLOBAL VARIABLES : Whenever a variable is defined
outside any function, it becomes a global variable, and its
scope is anywhere within the program. Which means it can
be used by any function.
Local & Global Variables
◼ Using of local variables ◼ Using of global variable ‘global’ key word is used to declare
global variable
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
◼ Advantages of Recursion
 Make the code look clean and elegant
 A complex task can be broken down into simpler sub-problems using recursion

◼ Disadvantages of Recursion
 Sometimes the logic behind recursion is hard to follow through
 Recursive calls are expensive (inefficient) as they take up a lot of memory and time
 Recursive functions are hard to debug
CHAPTER 04
Python Functions,Modules,and Packages(14 Marks)
➢ A module is a python file with a ‘.py’ extension
which consists of functions, statements and
variables. What are Modules in
➢The reason we use modules is to break down big Python?
programs into simpler and smaller ones.
➢We can reuse module files anytime as well.
What Is A Python Module
A module is simply a file containing python code .It may contain functions ,classes etc.
How To Create A Module In
Python?

◦ Creating a module in python is similar to


writing a simple python script using
the .py extension.
◦ For the above example let's try to make a
module for the various operations.
◦ Save the above code in a file Calc.py.
How To Create And Import A Module In Python?
IMPORTING OBJECTS FROM MODULE
How To Use & Call a Modules in python?

EXAMPLE 1: EXAMPLE 2:

✓ The import keyword to incorporate the ✓ from keyword is used to get only a few or specific
module into our program. methods or functions from a module.
✓ In the above code, we have created an alias ✓ In the above code, we have imported all the functions
using the as keyword. using the asterisk and we can simply mention the
function name to get the results.
◦ EXAMPLE 3: IMPORT INSIDE A MODULE(from x import a) ◦ EXAMPLE 4: IMPORT INSIDE A MODULE(from x import a,b,c)

from p1 import add from p1 import add, sub


print(“Addition=“,add(10,20)) print(“Addition=“,add(10,20))
print(“Subtraction=“,add(10,20))

We can access attributes/methods directly without dot notation


STEPS TO RUN IN COMMAND PROMPT
◦ Run:
➢pip install ipynb
➢and then import the other notebook as
➢from ipynb.fs.full.<notebook_name> import *
Or
➢from ipynb.fs.full.<notebook_name> import <function_name>
THANK YOU
◦ Example 3:
◦ from p1 import add
◦ Step1:conda install -c anaconda ipykernel
◦ Proceed ([y]/n)? Y press enter
◦ python -m ipykernel install --user --
name=MyEnvironment
◦ pip install ipynb

You might also like