The document discusses control structures, functions, modules, and Python's standard library. It covers topics like conditional branching, looping, functions, modules, packages, exceptions, strings, and more. Custom functions in Python include global functions, local functions, lambda functions, and methods. Modules allow packaging functionality and importing it into other code.
High Class Call Girls Noida Sector 39 Aarushi 🔝8264348440🔝 Independent Escort...
Control structures functions and modules in python programming
1. Control Structures,
Functions and Modules
in Python Programming
Presented By
Dr. Srinivas Narasegouda,
Assistant Professor,
Jyoti Nivas College Autonomous,
Bangalore -95.
2. Control Structures, Functions and Modules:-
Control Structures: Conditional branching, Looping,
Custom functions : Names and Docstrings, Argument
and parameter unpacking, Accessing Variables in
global scope, Lambda functions.
Modules and packages, Packages, Overview of
Python‘s Standard library: String Handling, Command
Line Programming, Mathematics and Numbers,
Algorithms and Collection Data Types, Files, Directory
and Process Handling.
3. Control Structures, Functions
Control Structures
Python provides conditional branching with if statements and
looping with while and for …in statements. Python also has a
conditional expression—this is a kind of if statement that is
Python’s answer to the ternary operator (?:) used in C-style
languages.
Conditional Branching
if expression:
statement(s)
else:
statement(s)
4. Control Structures, Functions
Control Structures
Conditional Branching
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
5. Control Structures, Functions
Control Structures
Python supports the usual logical conditions from mathematics:
Equals: a = = b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in
"if statements" and loops.
An "if statement" is written by using the if keyword.
6. Control Structures, Functions
Exceptional Handling
What is Exception?
An exception is an event, which occurs during the execution of a
program that disrupts the normal flow of the program's instructions. In
general, when a Python script encounters a situation that it cannot cope
with, it raises an exception. An exception is a Python object that
represents an error.
When a Python script raises an exception, it must either handle the
exception immediately otherwise it terminates and quits.
Handling an exception
If you have some suspicious code that may raise an exception, you can
defend your program by placing the suspicious code in a try: block.
After the try: block, include an except: statement, followed by a
block of code which handles the problem as elegantly as possible.
9. Control Structures, Functions
Exceptional Handling
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
10. Control Structures, Functions
Exceptional Handling
The except Clause with Multiple Exceptions : You can also use the same except
statement to handle multiple exceptions as follows −
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
11. Control Structures, Functions
Exceptional Handling
The except Clause with No Exceptions : You can also use the except statement with
no exceptions defined as follows
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
12. Control Structures, Functions
Exceptional Handling
The try-finally Clause
You can use a finally: block along with a try: block. The finally block is a place to
put any code that must execute, whether the try-block raised an exception or not.
The syntax of the try-finally statement is this −
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
13. Control Structures, Functions
Exceptional Handling
Argument of an Exception
An exception can have an argument, which is a value that gives additional information
about the problem. The contents of the argument vary by exception. You capture an
exception's argument by supplying a variable in the except clause as follows −
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...
14. Control Structures, Functions
Exceptional Handling
Raising an Exceptions
You can raise exceptions in several ways by using the raise statement. The general
syntax for the raise statement is as follows.
Syntax
raise [Exception [, args [, traceback] ] ]
Here, Exception is the type of exception (for example, NameError) and argument is a
value for the exception argument. The argument is optional; if not supplied, the
exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if
present, is the traceback object used for the exception.
15. Control Structures, Functions
Exceptional Handling
User-Defined Exceptions
Python also allows you to create your own exceptions by deriving classes from the
standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed
from RuntimeError. This is useful when you need to display more specific information
when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The
variable e is used to create an instance of the class Networkerror.
Creating Custom Exceptions
In Python, users can define custom exceptions by creating a new class. This exception
class has to be derived, either directly or indirectly, from the built-in Exception class.
Most of the built-in exceptions are also derived from this class.
16. Control Structures, Functions, and Modules
Custom Functions
Functions are a means by which we can package up and parameterize functionality.
Four kinds of functions can be created in Python:
1. Global functions
2. Local functions
3. Lambda functions
4. Methods.
Every function in Python returns a value, although it is perfectly acceptable (and
common) to ignore the return value.
The return value is either a single value or a tuple of values, and the values returned
can be collections, so there are no practical limitations on what we can return. We
can leave a function at any point by using the return statement.
If we use return with no arguments, or if we don’t have a return statement at all, the
function will return None.
17. Control Structures, Functions, and Modules
Custom Functions
Global Functions:
Global objects (including functions) are accessible to any code in the
same module (i.e., the same .py file) in which the object is created.
Global objects can also be accessed from other modules.
The general syntax for creating a (global or local) function is:
def functionName(parameters):
suite
The parameters are optional, and if there is more than one they are
written as a sequence of comma-separated identifiers, or as a sequence
of identifier = value pairs.
18. Control Structures, Functions, and Modules
Custom Functions
Local functions
Local functions (also called nested functions) are functions that are
defined inside other functions.
These functions are visible only to the function where they are defined;
they are especially useful for creating small helper functions that have
no use elsewhere.
19. Control Structures, Functions, and Modules
Custom Functions
Lambda Functions:
Lambda functions are expressions, so they can be created at their point
of use; however, they are much more limited than normal functions.
lambda arguments : expression
add_one = lambda x: x + 1
print(add_one(2))
The power of lambda is better shown when you use them as an
anonymous function inside another function.
Example: Say you have a function definition that takes one argument,
and that argument will be multiplied with an unknown number:
20. Control Structures, Functions, and Modules
Custom Functions
Methods
A method in python is somewhat similar to a function, except it is
associated with object/classes. Methods in python are very similar to
functions except for two major differences.
1. The method is implicitly used for an object for which it is called.
2. The method is accessible to data that is contained within the class.
General Syntax:
class ClassName:
def method_name():
…………..
# Method_body
………………
**Note** Before writing any function, check if that function is already written or included in the python
21. Control Structures, Functions, and Modules
Names and Docstrings
Names
Using good names for a function and its parameters goes a long way
toward making the purpose and use of the function clear to other
programmers—and to ourselves some time after we have created the
function. Here are a few rules of thumb that you might like to consider.
22. Control Structures, Functions, and Modules
Names
Use a naming scheme, and use it consistently.
UPPERCASE for constants, TitleCase for classes (including exceptions),
camelCase for GUI (graphical User Interface) functions and methods, and
lowercase or lowercase_with_underscores for everything else.
For all names, avoid abbreviations, unless they are both standardized and
widely used.
Be proportional with variable and parameter names: x is a perfectly good
name for an x-coordinate and i is fine for a loop counter, but in general the
name should be long enough to be descriptive. The name should describe
the data’s meaning rather than its type (e.g., amount_due rather than
money).
Functions and methods should have names that say what they do or what
they return (depending on their emphasis), but never how they do it—
since that might change.
23. Control Structures, Functions, and Modules
Names
Use a naming scheme, and use it consistently.
Here are a few naming examples:
def find(l, s, i=0): # BAD
def linear_search(l, s, i=0): # BAD
def first_index_of(sorted_name_list, name, start=0): # GOOD
All three functions return the index position of the first occurrence
of a name in a list of names, starting from the given starting index
and using an algorithm that assumes the list is already sorted.
24. Control Structures, Functions, and Modules
Docstrings
We can add documentation to any function by using a docstring—
this is simply a string that comes immediately after the def line, and
before the function’s code proper begins.
25. Control Structures, Functions, and Modules
Argument and Parameter Unpacking
Note: We use two operators * (for tuples) and ** (for dictionaries).
Background
Consider a situation where we have a function that receives four
arguments. We want to make call to this function and we have a list of
size 4 with us that has all arguments for the function. If we simply pass
list to the function, the call doesn’t work.
Unpacking
We can use * to unpack the list so that all elements of it can be passed
as different parameters.
Packing
When we don’t know how many arguments need to be passed to a
python function, we can use Packing to pack all arguments in a tuple.
26. Control Structures, Functions, and Modules
Accessing Variables in the Global Scope
In Python, a variable declared outside of the function or in global scope
is known as a global variable. This means that a global variable can be
accessed inside or outside of the function.
27. Control Structures, Functions, and Modules
Modules and packages
In programming, a module is a piece of software that has a specific
functionality.
Modules in Python are simply Python files with a .py extension. The
name of the module will be the name of the file. A Python module can
have a set of functions, classes or variables defined and
implemented.
The key difference between program and module is that programs
are designed to be run, whereas modules are designed to be imported
and used by programs.
28. Control Structures, Functions, and Modules
Modules and packages
Not all modules have associated .py files—for example, the sys
module is built into Python, and some modules are written in other
languages (most commonly, C).
It makes no difference to our programs what language a module is
written in, since all modules are imported and used in the same way.
29. Control Structures, Functions, and Modules
Modules and packages
Several syntaxes can be used when importing. For example:
Syntax: import <module_name>
import module1
import module1, module2, ..., moduleN
import module as preferred_name
Here are some other import syntaxes:
Syntax: from <module_name> import <name> as <alt_name>
Syntax: from <module_name> import <name>
from x import object as preferred_name
from x import object1, object2, ..., object
from x import *
30. Control Structures, Functions, and Modules
Modules and packages
Here are a few import examples:
import os
print(os.path.basename(filename)) # safe fully qualified access
import os.path as path
print(path.basename(filename)) # risk of name collision with path
from os import path
print(path.basename(filename)) # risk of name collision with path
from os.path import basename
print(basename(filename)) # risk of name collision with basename
from os.path import *
print(basename(filename)) # risk of many name collisions
31. Control Structures, Functions, and Modules
Packages
A package is simply a directory that contains a set of modules and a file called
__init__.py.
The file __init__.py is invoked when the package or a module in the package
is imported. This can be used for execution of package initialization code,
such as initialization of package-level data.
32. Control Structures, Functions, and Modules
Overview of Python‘s Standard library:
String Handling:
A string is a sequence of characters.
How to create a string in Python?
Strings can be created by enclosing characters inside a single quote or double-quotes. Even
triple quotes can be used in Python but generally used to represent multiline strings and
docstrings.
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
# triple quotes string can extend multiple lines
my_string = """Hello, welcome to
the world of Python"""
print(my_string)
33. Control Structures, Functions, and Modules
Overview of Python‘s Standard library:
String Handling:
How to access characters in a string?
We can access individual characters using indexing and a range of characters
using slicing. Index starts from 0. Trying to access a character out of index range
will raise an IndexError. The index must be an integer.
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. We can
access a range of items in a string by using the slicing operator :(colon).
34. Control Structures, Functions, and Modules
Overview of Python‘s Standard library:
String Handling:
How to access characters in a string?
str = 'Hello World'
print('str = ', str) # Output: Hello World
#first character
print('str[0] = ', str[0]) # Output: H
#last character
print('str[-1] = ', str[-1]) # Output: d
#slicing 2nd to 5th character
print('str[1:7] = ', str[1:7]) # Output: ello W
#slicing 6th to 2nd last character
print('str[4:-2] = ', str[4:-2]) # Output: o Wor
35. Control Structures, Functions, and Modules
Overview of Python‘s Standard library:
String Handling:
How to change or delete a string?
Strings are immutable.
This means that elements of a string cannot be changed once they have
been assigned.
We can simply reassign different strings to the same name.
We can iterate through a string using a for loop. Here is an example to count
the number of 'l's in a string.
# Iterating through a string
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count, 'letters found') # 3 letters found
36. Control Structures, Functions, and Modules
Overview of Python‘s Standard library:
String Handling:
String Special Operators
Assume string variable a holds 'Hello' and variable b holds 'Python', then −
Operator Description Example
+ Concatenation - Adds values on either side of the operator a + b will give HelloPython
* Repetition - Creates new strings, concatenating multiple copies
of the same string
a*2 will give -HelloHello
[ ] Slice - Gives the character from the given index a[1] will give e
[ : ] Range Slice - Gives the characters from the given range a[1:4] will give ell
in Membership - Returns true if a character exists in the given
string
H in a will give 1
not in Membership - Returns true if a character does not exist in the
given string
M not in a will give 1
37. Control Structures, Functions, and Modules
Overview of Python‘s Standard library: String Handling:
Built-in String Methods
Python includes the following built-in methods to manipulate strings −
Sr.
No
Methods with Description How to use it?
1 capitalize( ) Capitalizes first letter of string sample_string.capitalize( )
2 center(width, fillchar) Returns a space-padded string with the
original string centered to a total of width columns.
sample_string.center(40, 'a')
3 count(str, beg= 0,end=len(string)) Counts how many times str
occurs in string or in a substring of string if starting index beg and
ending index end are given.
sample_string.count(str2, beg_idx, end_idx)
4. find(str, beg=0 end=len(string)) Determine if str occurs in string or
in a substring of string if starting index start_idx and ending index
end_idx are given returns index if found and -1 otherwise.
sample_string.find(str2, start_idx, end_idx)
5. isspace( ) checks whether the string consists of only whitespace.
Returns true if only whitespaces otherwise returns false.
sample_string.isspace( )
38. Control Structures, Functions, and Modules
Overview of Python‘s Standard library:
https://www.tutorialspoint.com/built-in-string-methods-in-python
Sr.No Methods with Description How to use it?
6 islower( ) This method returns true if all cased characters in the string are
lowercase and there is at least one cased character, false otherwise.
sample_string.islower( )
7 lower( ) returns a copy of the string in which all case-based characters
have been lowercased.
upper( ) returns a copy of the string in which all case-based characters
have been uppercased.
sample_string2.lower( )
sample_string.upper( )
str4="7869584" ### numeric, alphanumeric, digit
str5="ⅠⅧ" ### numeric (roman), alphanumeric, but not digit
8 isnumeric( ) checks whether the string consists of only numeric characters.
This method is present only on unicode objects.
str4.isnumeric( ) # True
str5.isnumeric( ) # True
9 isalnum( ) checks whether the string consists of alphanumeric characters.
(Only alphabets or numbers or both. But no spaces or special character)
str4.isnumeric( ) # True
str5.isnumeric( ) # True
10 isdigit( ) This method returns true if all characters in the string are digits
and there is at least one character, false otherwise.
str4.isnumeric( ) # True
str5.isnumeric( ) # False
39. Control Structures, Functions, and Modules
Command Line Programming
The arguments that are given after the name of the program in the command
line shell of the operating system are known as Command Line Arguments.
Command line using sys.argv
The sys module provides functions and variables used to manipulate different
parts of the Python runtime environment.
This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
One such variable is sys.argv which is a simple list structure.
1. It is a list of command line arguments.
2. len(sys.argv) provides the number of command line arguments.
3. sys.argv[0] is the name of the current Python script.
40. Control Structures, Functions, and Modules
Command Line Programming
1. file_name=sys.argv[0] // commandline_sys_args.py
2. choice=int(sys.argv[1]) // 2
3. x = int(sys.argv[2]) // 6
4. y = int(sys.argv[3]) // 4
41. Control Structures, Functions, and Modules
Mathematics and Numbers
In addition to the built-in int, float, and complex numbers, the library provides
the decimal.Decimal and fractions.Fraction numbers.
Three numeric libraries are available: math for the standard mathematical
functions, cmath for complex number mathematical functions, and random
which provides many functions for random number generation;
Those involved in scientific and engineering programming will find the third
party NumPy package to be useful. This module provides highly efficient n-
dimensional arrays, basic linear algebra functions and Fourier transforms, and
tools for integration with C, C++, and Fortran code.
The SciPy package incorporates NumPy and extends it to include modules for
statistical computations, signal and image processing, genetic algorithms, and
a great deal more. Both are freely available from www.scipy.org.
42. Control Structures, Functions, and Modules
Mathematics and Numbers
We can use the type( ) function to know which class a variable or a value
belongs to and isinstance( ) function to check if it belongs to a particular
class.
a=5 # integer number
b=5.0 # float number
print(type(a))
print(type(b))
print(isinstance(a, complex))
print(isinstance(a, int))
print(isinstance(b, float))
c = 5 + 3j # complex number
print(isinstance(c, complex))
43. Control Structures, Functions, and Modules
Mathematics and Numbers
Type Conversion
We can convert one type of number into another. This is also known as
coercion.
Operations like addition, subtraction coerce integer to float implicitly
(automatically), if one of the operands is float. (1+2.0=3.0)
Python Decimal
print(1.1 + 2.2)
if ( (1.1 + 2.2) = = 3.3) :
print("True")
else:
print("False")
44. Control Structures, Functions, and Modules
Mathematics and Numbers
Python Decimal
When to use Decimal instead of float?
We generally use Decimal in the following cases.
1. When we are making financial applications that need exact decimal
representation.
2. When we want to control the level of precision required.
3. When we want to implement the notion of significant decimal places.
45. Control Structures, Functions, and Modules
Mathematics and Numbers
Python Fractions
Python provides operations involving fractional numbers through its fractions
module.
A fraction has a numerator and a denominator, both of which are integers. This
module has support for rational number arithmetic.
We can create Fraction objects in various ways.
1.5 3/2
1,3 1/3
46. Control Structures, Functions, and Modules
Mathematics and Numbers
Python Mathematics
Python offers modules like math and random to carry out different
mathematics like trigonometry, logarithms, probability and statistics, etc.
import math
print("Value of pi",math.pi)
print("Factorial of a number 6 is ",math.factorial(6))
import random
47. Control Structures, Functions, and Modules
Times and Dates
In Python, date and time are not a data type of its own, but a module named
datetime can be imported to work with the date as well as time. Datetime
module comes built into Python, so there is no need to install it externally.
The time module handles timestamps. These are simply numbers that hold the
number of seconds since the epoch (1970-01-01T00:00:00 on Unix). This
module can be used to get a timestamp of the machine’s current time in UTC
(Coordinated Universal Time), or as a local time that accounts for daylight
saving time, and to create date, time, and date/time strings formatted in
variousways. It can also parse strings that have dates and times.
import time
print(time.time()) ## Output 1603079605.4022589
import datetime
48. Control Structures, Functions, and Modules
Algorithms and Collection Data Types
The bisect module provides functions for searching sorted sequences such
as sorted lists, and for inserting items while preserving the sort order.
The bisect module’s functions use the binary search algorithm, so they are
very fast.
nums = [45,21,34,87,56,12,5,98,30,63]
nums.sort( )
print(nums)
import bisect
p = bisect.bisect_left(nums,50)
print("insert 50 at position ",p)
nums.insert(p,50)
print(nums)
49. Control Structures, Functions, and Modules
Algorithms and Collection Data Types
The heapq module provides functions for turning a sequence such as a list into a
heap—a collection data type where the first item (at index position 0) is always the
smallest item (Min Heap), and for inserting and removing items while keeping the
sequence as a heap.
import heapq
a = [3, 5, 1, 2, 6, 8, 7]
heapq.heapify(a)
print("Heapq model ",a)
# Add element
heapq.heappush(a,4)
print("After insertion a= ",a)
50. Control Structures, Functions, and Modules
File, Directory, and Process Handling
The shutil module provides high-level functions for file and directory
handling, including shutil.copy( ) and shutil.copytree( ) for copying files
and entire directory trees, shutil.move( ) for moving directory trees, and
shutil.rmtree( ) for removing entire directory trees, including nonempty
ones.
Temporary files and directories should be created using the tempfile module
which provides the necessary functions, for example, tempfile.mkstemp(), and
creates the temporaries in the most secure manner possible.
The filecmp module can be used to compare files with the filecmp.cmp( )
function and to compare entire directories with the filecmp.cmpfiles( )
function.
51. Control Structures, Functions, and Modules
File, Directory, and Process Handling
The os module provides platform-independent access to operating system
functionality. The os.environ variable holds a mapping object whose items are
environment variable names and their values.
The program’s working directory is provided by os.getcwd( ) and can be
changed using os.chdir( ). The module also provides functions for low-level
file-descriptor-based file handling.
The os.access( ) function can be used to determine whether a file exists or
whether it is readable or writable, and the os.listdir( ) function returns a
list of the entries (e.g., the files and directories, but excluding the . and ..
entries), in the directory it is given. The os.stat( ) function returns various
items of information about a file or directory, such as its mode, access
time, and size.