Python Unit - III
Python Unit - III
UNIT - III
Functions:
A function is a block of organized, reusable code that is used to perform a single,
related action. Functions provide better modularity for your application and a high degree of
code reusing.
Python gives you many built-in functions like print(), etc. but you can also create your
own functions. These functions are called user-defined functions.
Defining a Function
Define functions to provide the required functionality. Here are simple rules to define
a function in Python.
Function blocks begin with the keyword def followed by the function name and
parentheses ( ) .
Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
Syntax:
def functionname( parameters ):
function_statements
return [expression]
Example:
def printme( str ):
#This prints a passed string into this function
print (str)
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it
from another function or directly from the Python prompt.
Example:
# Function definition is here
def printme( str ):
#This prints a passed string into this function
print (str)
return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
The parameter mylist is local to the function changeme. Changing mylist within the
function does not affect mylist.
Function Arguments
Call a function by using the following types of formal arguments −
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
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
gives a syntax error.
Example:
def printme( str ):
print str
return;
printme() #This will Gives Syntax Error
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters. You can
also make keyword calls to the printme() function
Example:
def printme( str ):
print (str)
return;
printme( str = "My string")
def printinfo( name, age ):
print ("Name: ", name)
print ("Age ", age)
return;
printinfo( age=50, name="miki" )
Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument.
Example:
def printinfo( name, age = 35 ):
print ("Name: ", name)
print ("Age ", age)
return;
printinfo( age=50, name="miki" )
printinfo( name="miki" ) #Returns age as 35
Variable-length arguments
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.
Syntax:
def functionname([formal_args,] *var_args_tuple):
function statements
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional arguments are
specified during the function call.
Example:
def printinfo( arg1, *vartuple ):
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return;
printinfo( 10 )
printinfo( 70, 60, 50 )
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python.
Global variables
Local variables
Type Conversion
Type conversion, also known as type casting, refers to the process of converting a
value from one data type to another. This process is necessary when you want to perform
operations or manipulations that involve different types of data.
Implicit Conversion
Explicit Conversion
Implicit Conversion
Implicit type conversion, also known as automatic type conversion, occurs when the
programming language automatically converts data from one type to another without
requiring explicit instructions from the programmer. This process typically happens when
performing operations involving operands of different types.
Example:
num_int = 10
num_float = 3.5
result = num_int + num_float # Implicit conversion: num_int is
converted to float
print(result) # Output: 13.5
Explicit Conversion
Explicit type conversion, also known as manual type conversion or casting, involves
the programmer explicitly specifying the conversion from one type to another using
language-provided functions or syntax.
Example:
num_str = "123"
num_int = int(num_str) # Explicit conversion: string "123" is
converted to integer
print(num_int) # Output: 123
Common Conversions
Type conversion is commonly used in various scenarios:
Numeric Conversion:
Convert from float to integer.
Convert from integer to float.
String Conversion:
Convert from integer/float to string.
Convert from string to integer/float.
Boolean Conversion:
Convert from integer/float/string to boolean.
Convert from boolean to integer/float/string.
Handling Errors
Type conversion can sometimes lead to errors, especially when converting between
incompatible types or when converting to a type that cannot represent the original value.
Example:
try:
num = int("abc") # Raises ValueError: invalid literal for int() with
base 10
except ValueError:
print("Conversion failed: Invalid input")
Advantages:
Flexibility: Type conversion enhances the flexibility of programming languages by
allowing operations between different data types. This flexibility enables developers
to write more versatile and expressive code.
Simplicity: Type conversion simplifies code by reducing the need for explicit type
conversions. By automatically handling conversions when necessary, it makes code
more concise and readable.
Compatibility: Type conversion promotes compatibility between different parts of a
program or between libraries and frameworks. It allows functions and modules to
accept a wider range of input data types, improving interoperability.
Efficiency: In some cases, type conversion can improve code efficiency by allowing
operations to be performed directly on data of different types, without the need for
intermediate steps or data restructuring.
Disadvantages:
Loss of Precision: Type conversion can lead to loss of precision or information,
especially when converting between numeric data types. For example, converting
from a floating-point number to an integer truncates the decimal part, potentially
leading to loss of accuracy.
Unexpected Behavior: Type conversion may sometimes result in unexpected
behavior if not used carefully. Implicit conversions, in particular, can lead to subtle
bugs or errors if the programmer is not aware of the coercion rules defined by the
language.
Debugging Complexity: Issues related to type conversion can be challenging to
debug due to their implicit nature. Tracking down errors resulting from incorrect or
unintended conversions may require careful examination of code execution flow.
Performance Overhead: In performance-critical applications, frequent type
conversions may introduce a performance overhead. Converting data between
different types repeatedly can impact the overall execution speed of the program.
Potential Errors: Type conversion can sometimes lead to errors, especially when
converting between incompatible types or when converting to a type that cannot
represent the original value. Proper error handling mechanisms, such as exception
handling, are essential to handle errors that may occur during type conversion.
Type Coercion
Type coercion, also known as implicit type conversion, is a fundamental concept in
programming languages where the language automatically converts one data type to another
during operations or assignments. This automatic conversion enables operations between
different data types without requiring explicit conversion by the programmer.
Type coercion serves as a mechanism for enabling operations between values of
different types without requiring explicit conversions by the programmer. Its primary
purposes include:
Conversion vs Coercion
Conversion Coercion
Explicit process of changing a value Implicit process of automatically converting a
from one type to another, typically value from one type to another, typically
performed by the programmer using performed by the language during operations or
language-provided functions or syntax. assignments.
Can be either explicit or implicit. Primarily implicit, though explicit conversions
are also possible.
Allows the programmer to change the Enables operations between values of different
data type of a value as needed for types without requiring explicit conversions,
specific operations or requirements. simplifying code and enhancing flexibility.
Requires explicit instructions from the May occur without explicit instructions, based
programmer, providing full control on predefined rules and language behavior,
over the conversion process. reducing direct control by the programmer.
Involves language-provided functions Coercion occurs automatically, without the
or syntax for converting values need for explicit syntax or instructions in most
between different data types. cases.
Converting a string to an integer using Adding an integer and a string, where the
the int() function. <br> - Converting a integer is coerced to a string for concatenation.
float to a string using the str() function. <br> - Comparing a number and a string, where
the string is coerced to a number for
comparison.
Errors are explicitly handled by the Errors may occur due to unexpected or
programmer, allowing for custom unintended coercion, potentially leading to
error messages or error handling logic. unexpected behavior or bugs in the code.
Generally improves code readability May reduce code readability, especially for
by making the conversion process developers who are not familiar with the
explicit and transparent. language's coercion rules, as it relies on
implicit conversions that may not be
immediately obvious.
Definition
Passing functions to a function involves providing a function as an argument when
calling another function. This allows the receiving function to execute the passed function
within its own execution context.
Example:
def function1(arg1, arg2, func):
# Function1 code
result = func(arg1, arg2) # Call the passed function with arguments
# More code
return result
In this example:
function1 is a function that takes three arguments: arg1, arg2, and func.
Inside function1, func is called with arg1 and arg2.
function2 is defined separately and passed as an argument to function1.
When function1 is called with 3, 4, and function2, it executes function2(3, 4)
and returns the result.
Advantages:
Modularity and Reusability: Passing functions as arguments promotes modularity
by allowing functions to be defined independently and reused in different contexts.
This enhances code reusability, as functions can be easily applied to multiple
scenarios without modification.
Dynamic Behavior: It enables dynamic behavior in programs by allowing functions
to be parameterized with different behaviors. This flexibility allows algorithms to
adapt to different use cases or requirements dynamically, enhancing the versatility of
the code.
Abstraction and Encapsulation: Functions passed as arguments can encapsulate
complex behavior, abstracting away implementation details and promoting a higher
level of abstraction. This enhances code readability and maintainability by focusing
on the intent of the code rather than low-level details.
Expressiveness and Conciseness: Using higher-order functions leads to more
expressive and concise code. It allows complex operations to be expressed in a
compact and elegant manner, leading to cleaner and more readable code.
Functional Programming Paradigm: Passing functions to other functions is a core
concept in functional programming, enabling the use of higher-order functions,
function composition, and other functional programming techniques. Functional
programming promotes immutability, declarative programming, and side-effect-free
functions, leading to more predictable and maintainable code.
Disadvantages:
Complexity and Indirection: While passing functions as arguments increases
flexibility, it can also introduce complexity and indirection, making the code harder to
understand for developers who are not familiar with functional programming concepts.
Overuse of higher-order functions may lead to code that is difficult to reason about.
Performance Overhead: In some cases, passing functions as arguments may
introduce a performance overhead, especially in languages where function calls are
expensive. This overhead may be negligible in most cases but can become significant
in performance-critical applications or hotspots.
Debugging and Error Handling: Debugging code that heavily relies on passing
functions to other functions can be challenging, especially when dealing with complex
control flows or higher-order functions. Errors may occur due to incorrect usage of
function arguments or unexpected behavior of callback functions.
Readability: While higher-order functions can lead to more expressive code, they
may also reduce code readability for developers who are not familiar with functional
programming paradigms. Functions passed as arguments may be defined elsewhere in
the codebase, leading to difficulties in understanding the flow of execution.
Potential for Abstraction Leakage: In some cases, passing functions as arguments
may lead to abstraction leakage, where implementation details of the passed function
are exposed to the calling code. This violates the principle of encapsulation and may
lead to tighter coupling between components.
Mapping Functions
A mapping function typically refers to a function that applies a specified operation to
each element in a sequence (e.g., a list, tuple, or dictionary) and returns a new sequence
containing the results. This operation could be anything from applying a mathematical
function to transforming the elements in some way.
Transforming Data:
Mapping functions are commonly used to transform data by applying a transformation
or operation to each element in a sequence.
This transformation can involve mathematical operations, string manipulation, data
type conversions, or any other operation that modifies the elements.
In this example:
Four functions (add, subtract, multiply, divide) are defined to perform
different arithmetic operations.
A dictionary operation_dict is created where operation names ('add', 'subtract',
etc.) are mapped to their corresponding function objects.
You can access and call a function from the dictionary using its key. For
example, operation_dict['add'] returns the add function, which can then be
called with arguments as usual.
This approach allows for dynamic selection and execution of functions based
on keys or names, which can be useful in scenarios where different functions
need to be called based on runtime conditions or user input.
Modules
A module allows you to logically organize your Python code. Grouping related code
into a module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions,
classes and variables. A module can also include runnable code.
def greeting(name):
print("Hello, " + name)
Save the code as file in any name with .py extension to create the module. Just save
this code as myModule.py.
Variables in Module
The module can contain functions, like that variable of all types (arrays, dictionaries,
objects etc) also can be written inside the file to create module.
#myModule.py
person = {
"name": "John",
"age": 36,
"country": "Norway"
}
#mainFile.py
import myModule
a = myModule.person["name"]
print (a)
#mainFile.py
from myModule import person
print (person["age"])
Standard Modules
There are several built-in modules in Python, which you can import whenever you
like.
sys module
The sys module in Python provides access to system-specific parameters and
functions. It is part of Python's standard library, meaning it comes pre-installed with Python
and does not require any additional installation.
sys.stdin, sys.stdout, sys.stderr: These attributes represent the standard input, output,
and error streams, respectively.
Example:
import sys
math module
The math module in Python provides access to mathematical functions and constants,
allowing you to perform mathematical operations beyond the basic arithmetic operations
provided by the core Python language.
Use Cases
Scientific and Engineering Applications: The math module is commonly used in
scientific and engineering applications where precise mathematical calculations are
required.
Geometry and Trigonometry: It is useful for calculating geometric properties, angles,
distances, and trigonometric functions.
Financial Calculations: It can be used for financial calculations, such as compound
interest or present value calculations.
Use Cases
Delaying Execution: time.sleep() can be used to introduce delays or wait periods in
scripts or programs.
Measuring Time: time.time() is commonly used for measuring execution time or
benchmarking.
Formatting Time: time.strftime() allows for custom formatting of time strings, useful
for logging, displaying timestamps, or generating file names.
Converting Time Zones: time.gmtime() and time.localtime() are used for converting
timestamps between UTC and local time zones.
The dir() built-in function returns a sorted list of strings containing the names defined
by a module.
The list contains the names of all the modules, variables and functions that are defined
in a module.
import platform
x = dir(platform)
print(x)
help Function
The help() function in Python is a built-in function that provides interactive help for
objects, modules, functions, classes, methods, keywords, and other Python entities. It displays
documentation strings (docstrings) associated with these objects, which describe their
purpose, usage, parameters, and return values.
Syntax:
help([object])
object (optional): The object for which you want to retrieve help information. If no
object is provided, it starts an interactive help session.
Example:
help(abs)
Plotting
Plotting refers to the process of creating graphical representations of data using charts,
graphs, or plots. Python provides several libraries for data visualization, such as Matplotlib,
Seaborn, Plotly, and Pandas, which offer a wide range of plotting capabilities. These libraries
provide functions and classes to create various types of plots, including line plots, bar plots,
scatter plots, histograms, pie charts, and more. Plots are useful for visualizing data patterns,
relationships, and trends, making them a powerful tool for data analysis, reporting, and
presentation.
Matplotlib
Matplotlib is a popular data visualization library for Python. It provides a wide range
of tools to create different types of plots and graphs, including line plots, scatter plots, bar
plots, histograms, and many others. Matplotlib allows users to create publication-quality
figures with just a few lines of code.