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

Python PPT

Python is a versatile, high-level programming language that supports various applications including web development and automation testing. It features a simple syntax, extensive libraries, and supports multiple programming paradigms such as object-oriented programming. The document also covers fundamental concepts like data types, control flow, operators, and data structures including lists, tuples, sets, and dictionaries.

Uploaded by

na22b020
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)
8 views

Python PPT

Python is a versatile, high-level programming language that supports various applications including web development and automation testing. It features a simple syntax, extensive libraries, and supports multiple programming paradigms such as object-oriented programming. The document also covers fundamental concepts like data types, control flow, operators, and data structures including lists, tuples, sets, and dictionaries.

Uploaded by

na22b020
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/ 163

Python is a general purpose, high level, and interpreted programming language.

It supports Object
Oriented programming approach to develop applications.

Applications

 It is used in web development.

 Software development.

 Mathematics.

 System scripting.

 Automation testing.
Advantages of Python

 Python works on different platforms windows, Mac, Linux, Raspberry pi.

 Python has a simple syntax similar to the English language.

 Python has syntax that allows developers to write code in fewer lines compared to other
programming languages.

 Python is open source and easily portable.

 Python has massive library and easy to integrate.


Statement - A statement is an instruction that a Python interpreter can execute. Anything
written in Python is a statement.

Comments – It describes what is happening inside a program. Types of comments are –


 Single - line comment
 Multi – line comment
 Add sensible comment
 Inline comment
 Block comment
 Docstring comment

Keywords - Python keywords are reserved words that have a special meaning associated
with them and can’t be used for anything but those specific purposes.
Escape Sequence - An escape sequence is a sequence of characters that, when used inside a character or
string, does not represent itself but is converted into another character .

Escape Sequence Meaning


\’ Single quote
\” Double quote
\\ Backslash
\n Newline
\t Tab
\b Back space
Program 1

# ********** Print the following **********

# This is \\ double backslash

# This are /\/\/\/\/\ mountains

# The book is awesome (use escape sequence)

# \" \n \t \' print this as an output


Python as Calculator

Operator Description Example


+ Addition 2+3=5
- Subtraction 2 - 3 = -1
* Multiplication 2*3=6
/ Float Division 4 / 2 = 2.0
// Integer Division 4 // 2 = 2
% Modulo 6%2=0
** Exponent 2 ** 3 = 8

Program 2 - Python as Calculator


Precedence Rule
Program 3 – Precedence rule

print(round(2 ** 0.5,5)) Sqrt of 2 up to 5 decimal place

print(2 ** 3 ** 2) a = 20
L b = 10
R
c = 15
d=5
e=0

e = (a + b) * c / d #( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ", e) # 90.0

e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e) # 90.0

e = (a + b) * (c / d); # (30) * (15/5)


print ("Value of (a + b) * (c / d) is ", e) # 90.0

e = a + (b * c) / d; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e) # 50.0
Python Data types - Data types specify the different sizes and values that can be stored in the variable.
Type Casting – Converting variables declared in specific data type to the different data type is called
type casting.
Python performs two types of casting
• Implicit – The python interpreter automatically performs an implicit type conversion, which avoids loss
of data.
• Explicit – The explicit type conversion is performed by the user, using built – in function.
• To do type casting following built – in function are used.
 Int – Convert any type variable to the integer type.
 Float – Convert any type variable to the float type.
 Complex – Convert any type variable to the complex type.
 Bool – Convert any type variable to the bool type.
 Str – Convert any type variable to the string type.
Program 4

# Converting float data type to integer data type

pi = 3.14
print(pi)
print(type(pi))

num = int(pi)
print(num)
print(type(num))

# Integer to float data type

num = 314
print(num)
print(type(num))

num1 = float(num)
print(num1)
print(type(num1))
Variables - A variable is a reserved memory area (memory address) to store value.

• Rules for naming a variable

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)
 A variable name cannot be any of the Python keywords.

• Multi Words Variable Names


 Camel Case - Each word, except the first, starts with a capital letter eg: myVariableName = "John"
 Pascal Case - Each word starts with a capital letter eg: MyVariableName = "John"
 Snake Case - Each word is separated by an underscore character eg: my_variable_name = "John"
Python allows you to assign values to multiple variables in one line
x, y, z = "Orange", "Banana", "Cherry"
print(x) = Orange
print(y) = Banana
print(z) = Cherry

# Assigning same value to multiple variable

x=y=z = "Orange"
print("The value of x:",x)
print("The value of y: “,y)
print("The value of z:",z)
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows to extract the values into variables. This is
called unpacking.
# Unpacking a collection

fruits = ["apple", "banana", "cherry"] # Unpacking a list


x, y, z = fruits
print(x)
print(y)
print(z)

Output Variables - The python print() function is used to output variables

Print() function outputs multiple variables using ‘+’ operator or ,


Operators - Operators are used to perform operations on variables and values.
Assignment Operators - Assignment operators are used to assign values to variables:
Comparison Operators - Comparison operators are used to compare two values:
Boolean Operator – Represents one of two values either True or False
 Comparing two values, the expression is evaluated and Python returns the Boolean answer.

 The bool() function allows to evaluate any value, and gives True or False in return.

 There are not many values that evaluate to False, except empty values, such as (), [ ], { }, “ “, the number 0,
and the value none, and the false value evaluates to False.
Logical Operators - Logical operators are used to combine conditional statements:
Identity Operators - Identity operators are used to compare the objects, not if they
are equal, but if they are actually the same object, with the
same memory location.
Membership Operators – It is used to check if a sequence is present in an object.
Bitwise Operators – Bitwise operators are used to compare binary numbers
Bitwise & - It performs logical AND operation on the integer value after converting an integer to a binary value
and gives the result as a decimal value. It returns True only if both operands are True. Otherwise
False.
Bitwise | - It performs logical OR operation on the integer value after converting an integer to a binary value
and gives the result as a decimal value. It returns False if one of the operand is False/ True.
Otherwise True.
Bitwise xor ^ - It performs logical XOR operation on the integer value after converting an integer to a binary
value and gives the result as a decimal value.

~ Not – Inverts all the bits


Bitwise 1’s complement - It performs 1’s complement operation. It invert each bit of binary value and returns

the bitwise negation of a value as a result.

Bitwise left – shift << - It shifts the bit by a given number of place towards left and fill’s zeros to new position.

Bitwise right – shift >> - It shifts the bit by a given number of place towards right and here some bits are lost.
Python Control Flow

Flow control is the order in which statements or blocks of code are


executed at runtime based on a condition.
If – Statement - The if statement is the simplest form. It takes a condition and evaluates to
either True or False.

Syntax : Flow chart of if statement :

Pass Statement – if – statement cannot be empty, if if-statement is


empty it shows an error, to avoid the error Pass
statement is used.
If – else statement - The if-else statement checks the condition and executes the if block of code when the
condition is True, and if the condition is False, it will execute the else block of code.

Syntax : Flow chart of if statement


If – elif - else statement - The if-elif - else condition statement has an elif blocks to chain multiple conditions
one after another. The elif statement checks multiple conditions one by one and if
the condition fulfills, then executes that code.

Syntax
Nested – if statement - The nested if – else statement is an if statement inside another if – else statement.
Indentation is the only way to differentiate the level of nesting.

Syntax :
For loop - A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

Syntax :

for variable in iterable:


statement

Range Function and For Loop in Python


The range() function is commonly used for for loops in Python. It creates a sequence of numbers that help
determine the number of times the loop iterates. The three arguments for the range() function are as
follows:
 Start
 Stop
 Step
Nested For Loop in Python

Python allows to nest one or more loops within another loop. This is known as a nested for loop.

Syntax :
Break and Continue statement

Note - The else block will not be executed if the loop is stopped by a break statement.
While Loop in Python – The while loop is an entry controlled loop, and for loop is a count controlled loop.

Syntax :

while condition:
statement

While statement is used for infinite number of iteration.

For statement is used for finite number of iteration.


Lists
 Lists are used to store multiple values in a single variable.

 Lists are one of the 4 built – in datatype in Python.

 Lists are created using [ ].

 Lists are ordered, changeable, allows duplicate value, heterogeneous.


Lists are created using two ways:

 Using list( ) constructor – Created a list by passing the , separated values inside the [ ].

 Using [ ] – Create a list simply by enclosing the items inside the square bracket.

Length of the list – It is determined by using len()

Access list items


Indexing

Negative indexing

Range of indexing / negative

Using in keyword
Change list items
Change a single item value

Change a range of item values

Syntax
Add list items
Append Variable name.append(value), it takes exactly one argument

Insert Variable name.insert(position, value), it takes two arguments

Extend Variable name1.extend(variable name2)

To append elements from another list to the current list


Remove list items
Remove Variable name.remove(“value”)

Remove specified position Variable name.pop(position)

Del del variable name[ ]

Clear
If position not given,
Index value Removes the last item

If index value not


It empties the list
given deletes the
entire list Syntax : del variable name

Variable name.clear( )
Loop list – Using for( ) and while( ) loop, we can loop through the list using range( ) & len( ) function

Looping Using List Comprehension

List Comprehension offers the shortest syntax for looping through lists:

Syntax :

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [expression for item in iterable if condition == True]

newlist = [x for x in fruits if "a" in x] The condition is like a filter that only accepts the items that valuate
to True
Python - Sort Lists

A sort( ) method will sort the list alphanumerically, ascending by default.

Variable name.sort( )  Ascending order

Variable name.sort(reverse = True)

Reverse() – This method reverses the current sorting order of the elements.
Syntax
Python copy list
Using copy( ) method newlist = variable name.copy()

Using list( ) method newlist = list(variable name)


Python join list
Concatenation ‘ + ‘ = Variable 1 + Variable 2

Append() = It uses for loop

Extend() = variable 1.extend(variable 2)


Tuple
 Tuples are used to store multiple values in a single variable.

 Tuples are one of the 4 built – in datatype in Python.

 Tuples are created using ( ).

 Tuples are ordered, unchangeable, allows duplicate value, heterogeneous.


Tuples are created using two ways:

 Using tuple( ) constructor – Creating a tuple by passing the , separated values inside the ().

 Using () – Create a tuple simply by enclosing the items inside the () bracket.

Length of the list – It is determined by using len()

Access list items


Indexing

Negative indexing

Range of indexing / negative

Using in keyword
Update a Tuple: Tuples cannot be changed as they are immutable, by converting a tuple to list the values
can be changed.

Add tuple items


Replace

Append

Adding to tuples

Remove tuple items Convert tuple to list and use remove() method,

Variable name.remove(“Value”)
Unpacking a tuple

In Python, the values can be extracted back into the variables. This is called "unpacking"

Note: The number of variables must match the number of values in the tuple, if not, you must use an
asterisk to collect the remaining values as a list.
If the number of variables is less than the number of values, add an * to the variable name and the values
Will be assigned to the variable as a list.

Loop tuple – Using for( ) and while( ) loop, we can loop through the list using range( ) & len( ) function

Join tuple – To join one or more tuple use “+” operator.

To multiply a tuple given number of times use “*” operator.

Tuple copy - Create a copy of a tuple using the assignment operator “ = “. This operation will create
only a reference copy and not a deep copy because tuples are immutable.
Sets
 Sets are used to store multiple values in a single variable.

 Sets are one of the 4 built – in datatype in Python.

 Sets are created using ().

 Sets are unordered, unchangeable, does not allow duplicate value, heterogeneous.
Sets are created using two ways:

 Using set{} constructor – Created a list by passing the , separated values inside the { }.

 Using () – Create a set simply by enclosing the items inside the { } bracket.

Length of the set – It is determined by using len()

Access set items


Cannot access a set item using index number.

Once a set is created, items cannot be changed, but new items can be
added.
Add set items
To add items from another set into the current set, use the update() method.

The object in the update() method does not have to be a set, it can be any iterable object
(tuples, lists, dictionaries etc.).
Remove set items
Remove Variable name.remove(“value”)

Discard Variable name.discard(value)

Del del variable name Syntax : del variable name

Clear It empties the set Variable name.clear( )

Pop It removes an item randomly. Variable name.pop()

Loop Set – Using for( ) and while( ) loop, we can loop through the list using range( ) & len( ) function
set1 = {"apple", "banana", "cherry"}

for x in set1:
print(x)
Stack
A Stack is a data structure that follows the LIFO(Last In First Out) principle.

Append

Queue works on the principle of “First-in, first-out”.


Dictionaries - Dictionaries are used to store data values in key:value pairs.

 Dictionaries are written with curly brackets, and have keys and values.

 Dictionary items are ordered, changeable, and do not allow duplicates.

 Dictionaries cannot have two items with the same key.

 Dictionary can be constructed also using dict( ) constructor.

Access dictionary items


Dictionary item can be accessed by using keys() and get().

Dictionary item can be accessed by using values().

Dictionary items can be accessed by using item() .


Change dictionary items
Change the value of a specific item by referring to its key name.

 The update() method will update the dictionary with the items from the given
argument.
 The argument must be a dictionary, or an iterable object with key:value pairs.
Add dictionary items

Adding an item to the dictionary is done by using a new index key and assigning a value to it.

Syntax : Variable name[“Key name”] = “Value”

The update() method will update the dictionary with the items from a given argument. If the
item does not exist, the item will be added.
Syntax : Variable name.update({“Key name": “Value"})
Remove dictionary items The pop() method removes the item with the specified key name
Pop Syntax : variable name.pop(“Key name”)

Popitem The popitem() method removes the last inserted item.


Syntax : variable name.popitem()
Del del variable name Syntax : del variable name
del variable name[“Key name”]
Clear
The del keyword removes the item with the specified key name

It empties the set

Variable name.clear( )

It removes an item randomly. Variable name.pop()


Loop dictionary – Using for( ) loop, when looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.

 Print all key names in the dictionary, one by one. Syntax : for i in variable name
print(i)

 Print all values in the dictionary, one by one.


Syntax : for i in variable name:
print(variable name[i])
 The values() method to return values of a dictionary: Syntax : for x in variable name.values():
print(x)
 The keys() method to return keys of a dictionary:
Syntax : for x in variable name.keys():
print(x)

 Loop through both key and value using item () method


Syntax : for x , y in variable name.items()
print(x , y)
Copy a Dictionary

Cannot copy a dictionary simply by typing dict2 = dict1, dict2 will only be a reference to dict1, and changes made in dict1 will
automatically also be made in dict2.

Copy() method dict() function

VN2 = VN1.copy() VN2 = dict(VN1)

Dictionary Unpack
Unpack any number of dictionary and add their contents to another dictionary using **kwargs. In this way, we can add
multiple length arguments to one dictionary in a single statement.
Syntax : New Variable name = {**Variable name1, **Variable name2, **Variable name3,…………}
Functions

 In Python, the function is a block of code defined with a name.

 Functions are used whenever we need to perform the same task multiple times without writing the same code again.

 Types of Functions

Python support two types of functions


1) Built-in function - The functions which come along with Python itself are called as built – in - function or predefined
function. Some of them are range(), id(), type(), input(), eval() etc.
2) User-defined function - Functions which are created by programmer explicitly according to the requirement are called a
user-defined function.
Creating a function
Use the following steps to define a function in Python.
 Use the def keyword with the function name to define a function.
 Pass the number of parameters as per the requirement.
 Define the function body with a block of code.

Syntax

 function_name: Function name is the name of the function.


 parameter: Parameter is the value passed to the function. Function body uses the parameter’s value to perform an action
 function_body: The function body is a block of code that performs some task.
 return value: Return value is the output of the function.

Note: While defining a function, we use two keywords, def (mandatory) and return (optional).
Q1 Creating a function without a parameter.

Q2 Creating a function with parameter and return value.

Calling a function
 Once a function is defined or finalized structure, call the function by using its name. We can also call that
function from another function or program by importing it.
 To call a function, use the name of the function with the parenthesis, and if the function accepts
parameters, then pass those parameters in the parenthesis.

Docstrings
 In Python, the documentation string is also called a docstring. It is a descriptive text (like a comment)
written by a programmer to let others know what block of code does.
 We write docstring in source code and define it immediately after module, class, function, or method
definition.
Difference between Docstring and Comment
Comment Docstring
Visibility in the code Comments are not visible while executing Doc string of certain method, class, function
the code, they are always ignored. can be viewed with the help of __doc__.
Eg. Print(len.__doc__)
print(max.__doc__)

Usage Comments are useful for explaining the Docstrings are only used to describe the
working of a code and can be used for functions and classes, show that what
excluding a bit of code without having the parameters they accept and what they return.
need to remove it.

Syntax Comments are preceded by a # for a single Docstrings in python are contained by the ‘’’ or
line and “ ”, ‘ ‘, for a multiline. “”” i.e the triple quotation symbol and should be
inside a function, package or module.
Return Value From a Function
In Python, to return value from the function, a return statement is used. It returns the value of the expression following the return keyword.
Syntax of return statement

The return value is the outcome of function.


 The return statement ends the function execution.
 For a function, it is not mandatory to return a value.
 If a return statement is used without any expression, then the None is returned.
 The return statement should be inside of the function block.
Return Multiple Values
Return multiple values from a function. Use the return statement by separating each expression by a comma (,).

Scope and Lifetime of Variables

 When a function is defined with variable, then those variables’ scope is limited to that function.
 In Python, the scope of a variable is an area where a variable is declared. It is called the variable’s local
scope.
 We cannot access the local variables from outside of the function. Because the scope is local, those
variables are not visible from the outside of the function.

Note: The inner function does have access to the outer function’s local scope.

When we are executing a function, the life of the variables is up to running time. Once we return from the
function, those variables get destroyed. (Code 8)
Local Variable in function
A local variable is a variable declared inside the function that is not accessible from outside of the function. The
scope of the local variable is limited to that function only where it is declared. If we try to access the local
variable from the outside of the function, will get the error as NameError. (Code 8)

Global Variable in function


A Global variable is a variable that declares outside of the function. The scope of a global variable is broad. It is
accessible in all functions of the same module.

In Python, global is the keyword used to access the actual global variable from outside the function. we use the
global keyword for two purposes:
 To declare a global variable inside the function.
 Declaring a variable as global, which makes it available to function to perform the modification.
Nonlocal Variable in Function
 In Python, nonlocal is the keyword used to declare a variable that acts as a global variable for a nested
function (i.e., function within another function).
 We can use a nonlocal keyword when we want to declare a variable in the local scope but act as a global
scope.
Python Function Arguments
The argument is a value, a variable, or an object that we pass to a function or method call. In Python,
there are four types of arguments allowed.
1.Positional arguments
2.keyword arguments
3.Default arguments
4.Variable-length arguments *arg
5. Arbitrary keyword arguments **kwarg
Positional Arguments
 Positional arguments are arguments that are pass to function in proper positional order. That is, the 1st
positional argument needs to be 1st when the function is called. The 2nd positional argument needs to be
2nd when the function is called, etc.
 In the positional argument number and position of arguments must be matched. If we change the order,
then the result may change. Also, If we change the number of arguments, then we will get an error.

Keyword Arguments
A keyword argument is an argument value, passed to function preceded by the variable name and an equals
sign.
 In keyword arguments order of argument is not matter, but the number of arguments must match. Otherwise,
we will get an error.
 While using keyword and positional argument simultaneously, we need to pass 1st arguments as positional
arguments and then keyword arguments. Otherwise, will get SyntaxError.
Default Arguments
Default arguments take the default value during the function call if we do not pass them. We can assign a
default value to an argument in function definition using the = assignment operator.
Variable-length Arguments * arg
In Python, sometimes, there is a situation where we need to pass multiple numbers of arguments to the function.
Such types of arguments are called variable-length arguments. We can declare a variable-length argument
with the * (asterisk) symbol.
Syntax def fun(*var):
function body
Arbitrary keyword arguments **kwarg – To pass multiple keyword arguments use **kwargs
Syntax def fun(**var):
function body
Recursive Function
A recursive function is a function that calls itself, again and again.
The advantages of the recursive function are:
1.By using recursive, we can reduce the length of the code.
2.The readability of code improves due to code reduction.
3.Useful for solving a complex problem
The disadvantage of the recursive function:
1.The recursive function takes more memory and time for execution.
2.Debugging is not easy for the recursive function.
Python Anonymous/Lambda Function
Sometimes we need to declare a function without any name. The nameless property function is called
an anonymous function or lambda function.
The reason behind using anonymous function is for instant use, that is, one-time usage. Normal function is
declared using the def function. Whereas the anonymous function is declared using the lambda keyword.
In opposite to a normal function, a Python lambda function is a single expression. But, in a lambda body, we
can expand with expressions over multiple lines using parentheses or a multiline string.
ex : lambda n:n+n
Syntax of lambda function:
lambda: argument_list:expression

When we define a function using the lambda keyword, the code is very concise so that there is more
readability in the code. A lambda function can have any number of arguments but return only one value after
expression evaluation.

It is not required to write explicitly return statements in the lambda function because the lambda internally
returns expression value.
Lambda functions are more useful when we pass a function as an argument to another function. We can also
use the lambda function with built-in functions such as filter, map, reduce because this function requires
another function as an argument
filter() function in Python
In Python, the filter() function is used to return the filtered value. We use this function to filter values based on
some conditions.
Syntax of filter() function:
filter(function, sequence)

 function – Function argument is responsible for performing condition checking.


 sequence – Sequence argument can be anything like list, tuple, string

map() function in Python


In Python, the map() function is used to apply some functionality for every element present in the given sequence
and generate a new series with a required modification.
Syntax of map() function:
map(function, sequence)
 function – Function argument responsible for applied on each element of the sequence.
 sequence – Sequence argument can be anything like list, tuple, string
reduce() function in Python
In Python, the reduce() function is used to minimize sequence elements into a single value by applying the
specified condition.
The reduce() function is present in the functools module; hence, need to import it using the import statement
before using it.
Syntax of reduce() function:
reduce(function, sequence)
Module
In Python, modules refer to the Python file, which contains Python code like Python statements, classes, functions, variables,
etc. A file with Python code is defined with extension.py .

In Python, large code is divided into small modules. The benefit of modules is, it provides a way to share reusable functions.

Two types of modules


A file containing a set of functions that
needed to include in the application.
Built - in User defined

Built-in modules come with default Python installation. One of The modules which the user defines or create are called a
Python’s most significant advantages is its rich library support user-defined module. We can create our own module,
that contains lots of built-in modules. Hence, it provides a lot of which contains classes, functions, variables, etc.,
reusable code. as per our requirements.
Some commonly used Python built-in modules
are datetime, os, math, sys, random, etc.
How to import modules?
In Python, the ”import” statement is used to import the whole module. Also, we can import specific classes and functions
from a module. With the help of the import keyword, both the built-in and user-defined modules are imported.
Syntax import module name

When the interpreter finds an import statement, it imports the module presented in a search path. The module is loaded only
once, even we import multiple times. Using import keyword multiple modules can be imported.

 randint(x , y) returns a number x<=n<=y where n is an integer value and x, y are user defined limits.

Import only specific classes or functions from a module


To import particular classes or functions, we can use the from...import statement. It is an alternate way to import. Using
this way, we can import individual attributes and methods directly into the program.

Syntax of from...import statement:

from <module_name> import <name(s)>


Import with renaming a module

To use the module with a different name, use from..import…as statement.


It is also possible to import a particular method and use that method with a different name. It is called aliasing. Afterward,
use that name in the entire program.

Syntax of from..import ..as keyword:


from <module_name> import <name> as <alternative_name>

Import all names


To import all functions and attributes of a specific module, then instead of writing all function names and attribute names,
can import all using an asterisk *.

Syntax of import * statement: import *


User defined module

In Python, to create a module, write Python code in the file, and save that file with the .py extension.

Variables in Module

In Python, the module contains Python code like classes, functions, methods, but it also has variables. A variable
can list, tuple, dict, etc.

Reloading a module
In Python, when we import a module in the program using the import statement, the module is loaded. By default, the
module loaded only once, even if we import it multiple times. Sometimes we update the loaded module with new
changes, then an updated version of the module is not available to the program. In such case, use the reload() function
to reload a module again.
The main difference between a module and a function is that a module is a collection of functions
that are imported in multiple programs and can do various tasks. A function is a small block of code
and separates itself from the entire code and have a fixed functionality.

What is Package in Python?


The package is a simple directory having collections of modules. This directory contains Python
modules and also having __init__.py file by which the interpreter interprets it as a Package. The
package is simply a namespace. The package also contains sub-packages inside it.

sys.path
sys.path is a built-in variable within the sys module. It contains a list of directories that the interpreter will
search in for the required module.
When a module(a module is a python file) is imported within a Python file, the interpreter first searches for
the specified module among its built-in modules. If not found it looks through the list of directories(a
directory is a folder that contains related modules) defined by sys.path.
dir() Function
 There is a built-in function to list all the function names (or variable names) in a module.

 dir() is a built-in function. This function is used to list all members of the current module. When we use this function
with any object (an object can be sequence like list, tuple, set, dict or can be class, function, module, etc. ), it returns
properties, attributes, and method.

 For Class Objects, it returns a list of names of all the valid attributes and base attributes.

Return value from dir()


 When we use dir() with an object, it returns the list of the object’s attributes.
 When we use the __dir__() The object’s method, if that object has this method, it returns all attributes of that object. And
if that object does not has __dir__() method, it returns all information about that object.
 If we do not pass an object to dir() it returns a list of currently available functions, methods, properties, attributes, names
in the local scope.
Closures
Examples of Nested function1 under closure
Why nested functions are used ?
 Data Encapsulation : It is hiding information about attributes and methods in programming to prevent other
developers from writing scripts.
 Closure : A Closure in Python is a function object that remember values in enclosing scopes even if they
are not present in memory.
The outer function returns the inner function itself, rather than invoking it.
 The conditions that must be met in order to build a closure in Python are as follows.
• A nested function is required.
• The inner function must refer to a value that is defined in the enclosing scope.
• The nested function must be returned by the enclosing function.
Decorators – Enhance the functionality of other function

In Python, a decorator is a design pattern that allows to modify the functionality of a function by wrapping it in
another function.
The outer function is called the decorator, which takes the original function as an argument and returns a
modified version of it.
@ syntactic sugar is syntax within a programming language that is designed to make things easier
to read or to express.
Iterable and Iterators

Map in Python is a function that works as an iterator to return a result after applying a function to every
item of an iterable (tuple, list etc.). It is used when you want to apply a single transformation function to all the
iterable elements. The iterable and function are passed as arguments to the map in Python.

Python Generators
In Python, a generator is a function that returns an iterator that produces a sequence of values when iterated over.
.
Generators are useful when we want to produce a large sequence of values, but we don't want to store all of them in
memory at once.

Create Python Generator


In Python, similar to defining a normal function, we can define a generator function using the def keyword, but instead of
the return statement we use the yield statement
A classmethod()
A classmethod() is a built-in function in Python that is used to define a method that is bound to the class
and not the instance of the class. It is denoted by the @classmethod decorator and can be accessed
directly from the class itself, without the need for creating an instance of the class.

Static Methods in Python

A static method is a general utility method that performs a task in isolation.


A static method is bound to the class and not the object of the class. Therefore, we can call it using the class name.
A static method doesn’t have access to the class and instance variables because it does not receive an implicit first
argument like self and cls.
What is Encapsulation in Python?

Encapsulation in Python describes the concept of bundling data and methods within a single unit. When a class is
created, it means encapsulation is implemented. A class is an example of encapsulation as it binds all the data members
(instance variables) and methods into a single unit.
Using encapsulation, hide an object’s internal representation from the outside. This is called information hiding.
Also, encapsulation allows restrict accessing variables and methods directly and prevent data modification by creating
private data members and methods within a class.
Encapsulation is a way to restrict access to methods and variables from outside of class. Whenever working with the
class and dealing with sensitive data, providing access to all variables used within the class is not a good choice.

What is abstraction in Python?


In Python, an abstraction is used to hide the irrelevant data/class in order to reduce the complexity.
Sort() used in python is based on Tim algorithm, when sort() function is used, the user cannot know the
process running at the back, hiding that process is known as abstraction.
Access Modifiers in Python
Encapsulation can be achieved by declaring the data members and methods of a class either as private or
protected. But In Python, we don’t have direct access modifiers like public, private, and protected. We can achieve
this by using single underscore and double underscores.
Access modifiers limit access to the variables and methods of a class. Python provides three types of access
modifiers private, public, and protected.
• Public Member: Accessible anywhere from outside class.
• Private Member: Accessible within the class
• Protected Member: Accessible within the class and its sub-classes (inheritance), prefix with single underscore.
Getters and Setters in Python

To implement proper encapsulation in Python, we need to use setters and getters. The primary purpose of
using getters and setters in object-oriented programs is to ensure data encapsulation. Use the getter
method to access data members and the setter methods to modify the data members.
In Python, private variables are not hidden fields like in other programming languages. The getters and
setters methods are often used when:
• When we want to avoid direct access to private variables.
Polymorphism
Polymorphism in Python is the ability of an object to take many forms. In simple words, polymorphism allows us
to perform the same action in many different ways.

XYZ

Employee
Sports Player
Student

Polymorphism in Built-in function len()


The built-in function len() calculates the length of an object depending upon its type.
If an object is a string, it returns the count of characters, and if an object is a list, it returns the count of items in a list.

The len() method treats an object as per its class type.


Inheritance in Python

The process of inheriting the properties of the parent class into a child class is called inheritance. The existing
class is called a base class or parent class and the new class is called a subclass or child class or derived class.

The main purpose of inheritance is the reusability of code because we can use the existing class to create a new class
instead of creating it from scratch.

In inheritance, the child class acquires all the data members, properties, and functions from the parent class. Also, a
child class can also provide its specific implementation to the methods of the parent class.

Car is a sub-class of a Vehicle class. We can create a Car by inheriting the properties of a Vehicle such as Wheels,
Colors, Fuel tank, engine, and add extra properties in Car as required.
Types Of Inheritance

In Python, based upon the number of child and parent classes involved, there are five types of inheritance.

The type of inheritance are listed below:

1. Single inheritance

2. Multiple Inheritance

3. Multilevel inheritance

4. Hierarchical Inheritance

5. Hybrid Inheritance
Single Inheritance
In single inheritance, a child class inherits from a single-parent class. Here is one child class and one parent
class.

Multiple Inheritance
In multiple inheritance, one child class can inherit from multiple parent classes. So here is one child class and
multiple parent classes.
Multilevel inheritance
In multilevel inheritance, a class inherits from a child class or derived class. Suppose three classes A, B, C. A
is the superclass, B is the child class of A, C is the child class of B. In other words, we can say a chain of
classes is called multilevel inheritance.
Hierarchical Inheritance
In Hierarchical inheritance, more than one child class is derived from a single parent class. In other words, we
can say one parent class and multiple child classes.
Hybrid Inheritance
When inheritance is consists of multiple types or a combination of different inheritance is called hybrid
inheritance.

Note: In the above example, hierarchical and multiple inheritance exists. Here we created, parent class Vehicle and two
child classes named Car and Truck this is hierarchical inheritance.
Another is Sports Car inherit from two parent classes named Car and Vehicle. This is multiple inheritance.
Python super() function
When a class inherits all properties and behavior from the parent class is called inheritance. In such a case, the inherited
class is a subclass and the latter class is the parent class.
In child class, we can refer to parent class by using the super() function. The super function returns a temporary object of
the parent class that allows us to call a parent class method inside a child class method.

Benefits of using the super() function.


1.Not required to remember or specify the parent class name to access its methods.
2.We can use the super() function in both single and multiple inheritances.
3.The super() function support code reusability as there is no need to write the entire function

issubclass()
In Python, we can verify whether a particular class is a subclass of another class. For this purpose, we can use Python
built-in function issubclass(). This function returns True if the given class is the subclass of the specified class. Otherwise, it
returns False.
Syntax - issubclass(class, classinfo)
Where,
o class: class to be checked.
o classinfo: a class, type, or a tuple of classes or data types.

Method Overriding
In inheritance, all members available in the parent class are by default available in the child class. If the child
class does not satisfy with parent class implementation, then the child class is allowed to redefine that method
by extending additional functions in the child class. This concept is called method overriding.
When a child class method has the same name, same parameters, and same return type as a method in its
superclass, then the method in the child is said to override the method in the parent class.
 Read Only (‘r’)
 Read and Write (‘r+’)
 Write Only (‘w’)
 Write and Read (‘w+’)
 Append Only (‘a’)
 Append and Read (‘a+’)
n is an integer
Paths in file handling :

1) Relative path - Interpreted from the current working directory. Eg : fh = open('File 2.txt','r')

2) Absolute path - Accesses the given file using the path starting from the root of the file
system.

Eg fh = open(r'D:\EV Course\EV Class Content\Python\File handling\File 2.txt','r')

--------------------------------------------------------------------------------------------------------------------

To check whether the file existed in the current directory using relative path........ Use code
File handling 3_6

1) By checking the working directory manually to look for a new file.

2) Import os and check.

3) Use the os.listdir(directory_path) function to list all files from a folder before and after
creating a file.

4) Use the os.path.isfile(file_path) function to verify if a newly created file exists in a directory.
Q Why closing a file is important in file handling ?

Closing a file after use is important because it frees up system resources that are being used by the file.

When a file is open, the operating system allocates memory and other resources to the file,

which can potentially impact the performance of the system if too many files are open at the same time.

Note : Using the “with” statement a file is closed automatically it ensures that all the resources that are tied up with the file are
released.

-----------------------------------------------------------------------------------------------------------------------------
To create a text file with the current date as its name.

Use the datetime module to get the current date and time and assign it to the file name to create a file with the date and time in
its name.

Python provides a datetime module that has several classes to access and manipulate the date and timestamp value.

1) First, get the current datetime value.

2) Next, we need to format datetime into a string to use it as a file name.

3) At last, pass it to the open() function to create a file


Seek() method

1) The seek() method is used to move the file cursor ahead or backward from the current position.

2) To move the file pointer to that start or end of the file.

3) To move the file pointer backward from the end of the file.

4) Get the current position of the file handle

Q What is seek() in Python

The seek() function sets the position of a file pointer and the tell() function returns the current position of a
file pointer.
A file handle or pointer denotes the position from which the file contents will be read or written. File handle is also called as file pointer or cursor.

When a file is opened in write mode, the file pointer is placed at the 0th position, i.e., at the start of the file. However, it changes (increments) its
position as we start writing content into it.

Or, while reading a file line by line, the file pointer move one line at a time.

Sometimes it is required to read only a specific portion of the file, in such cases use the seek() method to move the file pointer to that position.

For example, use the seek() function to do the file operations like: –

1) Read a file from the 10th character.

2) Directly jump to the 5th character from the end of the file.

3) Add new content to file after a particular position.

Syntax f.seek(offset, whence)

How many points the pointer will move is computed from adding offset to a reference point.

The reference point is given by the whence argument.

The allowed values for the whence argument are: –

1) A whence value of 0 means from the beginning of the file.

2) A whence value of 1 uses the current file position.

3) A whence value of 2 uses the end of the file as the reference point.
Rename file in Python

Steps to Rename File in Python

To rename a file

1) Find the path of a file to rename

To rename a file, we need its path. The path is the location of the file on the disk.

---> An absolute path contains the complete directory list required to locate the file.

---> A relative path contains the current directory and then the file name.

2) Decide a new name

Save an old name and a new name in two separate variables.

old_name = ‘ Name 1 '

new_name = ‘Name 2'

3) Use rename() method of an OS module

Use the os.rename() method to rename a file in a folder.

Pass both the old and new names to the os.rename(old_name, new_name) function to rename a file.
os.rename()
We can rename a file in Python using the rename() method available in the os module. The os module
provides functionalities for interacting with the operating systems. This module comes under Python’s
standard utility modules.

Rename a file after checking whether it exists

Use the isfile(‘path’) function before renaming a file. It returns true if the destination file name already exists.

Use os.path.isfile() in an if condition

Rename Multiple Files in Python


 To rename all files from a directory.
 We can rename multiple files in a folder using the os.listdir() and os.rename() method by following the below steps.
 Get the list of files in a directory using os.listdir(). It returns a list containing the names of the entries in the given
directory.
 Iter over the list using a for loop to access each file individually.
 Rename each file.
How to Delete a File in Python

Python provides strong support for file handling. We can delete files using different methods and the most commonly used
one is the os.remove() method. Below are the steps to delete a file.
1.Find the path of a file
We can delete a file using both relative path and absolute path. The path is the location of the file on the disk.
An absolute path contains the complete directory list required to locate the file. And a relative path includes the current
directory and then the file name.
2. Use os.remove() function to delete File
The OS module in Python provides methods to interact with the Operating System in Python. The remove() method in this
module is used to remove/delete a file path.
First, import the os module and Pass a file path to the os.remove('file_path') function to delete a file from a disk
3.Use the rmtree() function of shutil module to delete a directory
Import the shutil module and pass the directory path to shutil.rmtree('path') function to delete a directory and all files
contained in it.
Delete all Files from a Directory

 To delete all files from a directory without deleting a directory. Follow the below steps to delete all files from
a directory.
 Get the list of files in a folder using os.listdir(path) function. It returns a list containing the names of the files
and folders in the given directory.
 Iterate over the list using a for loop to access each file one by one
 Delete each file using the os.remove()

Delete an Empty Directory (Folder) using rmdir()

While it is always the case that a directory has some files, sometimes there are empty folders or directories that no longer
needed. We can delete them using the rmdir() method available in both the os module and the pathlib module.
Using os.rmdir() method
In order to delete empty folders, use the rmdir() function from the os module.
Use pathlib.Path.rmdir()
 The rmdir() method in the pathlib module is also used to remove or delete an empty directory.
 First set the path for the directory
 Next, call the rmdir() method on that path

One such module is Shutil, which stands for "shell utilities," providing a comprehensive set of functions for
file and directory operations. Whether you need to copy, move, rename, or delete files and directories, the
Shutil module in Python comes to the rescue with its user−friendly and efficient functionalities.

The Shutil module allows you to do high-level operations on a file, such as copy, create, and remote
operations. It falls within the umbrella of Python's basic utility modules. This module aids in the automation
of the copying and deleting of files and folders.
Multithread
A core is a physical component of the CPU that can execute instructions, while a thread is a virtual
sequence of instructions that can be executed by a core.
Cores can be visualized as the workers, while threads are the tasks they perform.

How Do CPU Cores Work Together With Threads?


In a multi-core CPU, each core can run a different thread. This allows the CPU to run multiple tasks
simultaneously, which typically improves multitasking performance. For example, if you are browsing the
web while downloading a file and streaming a video, the CPU can use one core to browse the web, one
core to download the file, and one core to stream the video.
Threads can also be used to improve the performance of single-threaded applications. For example, a
single-threaded application that is waiting for input from the user can create a thread to handle the input,
while the main thread continues to execute other instructions. This can greatly improve the
responsiveness of the application.
The goal of multithreading is to complete multiple tasks at the same time, which improves application
rendering and performance.

Working:
The thread is created by a process. Every time when an
application is open, it itself creates a thread which will handle all
the tasks of that specific application. Like-wise the more
application is open more threads will be created.
The threads are always created by the operating system for
performing a task of a specific application.
There is single thread (code of that core which performs the
computations also known as primary thread) on the core which
when gets the information from the user, creates another thread
and allocates the task to it. Similarly, if it gets another instruction
it forms second thread and allocates the task to it. Making a total
of two threads.
Example:
The smartphone application is an example of this, when you open a app it shows a circle which spins
continuously, this process is done by a thread created for this purpose only, and the second thread loads
the information and presents it in the Graphical User Interface.

The only fact that will limit the creation of the threads will be the number of the threads provided by the
physical CPU, and it varies from CPU to CPU. The 1st image is the loading spinner by the first thread and
the second one is the GUI loading by the second thread.

Threads have become a vital part of the computing as


they allow the processor to perform multiple tasks at the
same time making the tasks faster.
What is SQL?
Structured query language (SQL) is a programming language for storing and processing information in a
relational database. A relational database stores information in tabular form, with rows and columns
representing different data attributes and the various relationships between the data values. You can use
SQL statements to store, update, remove, search, and retrieve information from the database. You can also
use SQL to maintain and optimize database performance.

What is MySQL?
MySQL is an open-source relational database management system offered by Oracle. Structured query
language (SQL) is a standard language for database creation and manipulation. MySQL is a relational
database program that uses SQL queries.

A table is an organized set of data that is arranged into rows and columns in a Database Management System
(DBMS), while a database is a collection of related tables.
How to install MySQL
MySQL
Downloads
MySQL Community GPL Downloads

After installation, go to program files -------> MySQL -------> MySQL Server

Environment variable In the window, type Environment Go to bin folder, copy the path
variable

Double click on the path, select new, paste the bin path Open cmd, mysql – version (to check the version)

To connect mysql with database, type mysql –u root –p, and enter the password created during
installation, show databases;
MySQL Driver
MySQL driver creates connection between Python and MySQL.

Steps to install MySQL driver

1) In command prompt, check Python version python –version.

2) Check the MySQL version mysql – version.

3) MySQL driver installation Before installing MySQL driver, check the available drivers using pip list.

4) Go to PyCharm, create a new file MySQL.py, under MySQL.py create a new python file driver.py.

5) Connect Python and MySQL by using the command “pip install mysql-connector-python”. Before
pressing enter check for internet connectivity. Check the installed driver by typing pip list.

6) Under driver.py in PyCharm type import mysql.connector, print(“Installation successful……….”)


Create connection between MySQL and Python

• Import mysql.connector as myConn ---> mysql.connector is a driver which is called as myConn.

• Creating the object of the driver i.e mydb = myConn.connect(host, user, password, database are the parameters)

• connect() method. Connects to a MySQL server. connect() supports the following arguments: host , user ,
password , database , port , unix_socket , client_flags , ssl_ca , ssl_cert , ssl_key , ssl_verify_cert , compress .

• mysql.connector, myConn.connect A driver, or device driver, is a set of files that tells a piece
of hardware how to function by communicating with a
Package Method computer's operating system.

Class
Creating Database

Creating Database

MySQL Python
• Any changes in the database through front end can be done using any of the languages like Python

or Java, direct changes in the database through front end cannot be done.

• Cursor() method allows to perform SQL operations in Python programming language.

• Syntax – cursor object = connector object.cursor()

• Cursor () method is available in connector object and execute() method is available in cursor object

• To check the created database, type mysql –u root –p, and enter the password created during installation,
show databases;
Data Manipulation Language Transaction Control Language

Data Control Language Data Query Language


Data Definition Language
Values(%s %s) – the argument is treated as and presented as a string.
• Commit() – The inserted data to be available in the table, commit method is used. It is under mysql.connector or

main myConn object i.e mydb.

• To check the table select query is used in cmd prompt. Syntax – select * from database name.table name;
To insert multiple values

db_insert = ("insert into Student(Name, Roll_num) values(%s,%s)")


db_list = [("ABC",11),("QWE",12),("RTY",13),("ZXC",14),("FGH",15)]
db_cursor.executemany(db_insert, db_list)
Syntax
Insert_query= ("insert into table name(Name, Roll_num) values(%s,%s)")
Insert_value = [("ABC",11),("QWE",12),("RTY",13),("ZXC",14),("FGH",15)]
db_cursor.executemany(db_insert, db_list)
Python Socket Program
Checking the static IP address of a website
Finding open ports using command line “netstat –a –b –n”

https://en.wikipedia.org/wiki/Netstat ------ Netstat commands

Accessible only as a network


administrator
Network administrator
List of important modules in python network / internet programming
OSI MODEL
What Is Socket Programming?
Socket programming is a means of communication between nodes over a network. Nodes can refer to
clients and servers. A server is a software program that waits for client requests and serves the incoming
processes, while a client is a requester of the service. A client requests resources from the server, and
the server responds to the request.
To establish a connection between a client and a server, create a socket in each program and then
connect both sockets together. Once the socket connection is established, the nodes can exchange
data.

Socket() Module in Python


In Python, the socket module provides a way to work with sockets. Sockets allows to establish network
connections over various network protocols such as TCP or UDP to send and receive data. To use it in the code,
first import the socket module.
Once imported the module, use the socket() method to create a socket object.
Python Socket Server
Python socket server executes first and then waits for any request from clients. The server has the bind() method which
binds the IP address and Port number so that it can listen to incoming requests from the client on that IP and Port. In the
bind method, instead of IP, passing the empty string, then this makes the server listen to requests coming from other
computers on the network.
Next, the server has the listen() method, which puts the server in listening mode so that it can listen to incoming
connections. Lastly, the server has an accept() method that initiates a connection with the client, and lastly,
the close() method that closes the connection with the client.
So the sequence is: bind, listen, accept, communicate, close.

Python Socket Client


Python socket client program will initiate the conversation at first. This is very similar to the Python socket server. The only
difference is that in the server program, we use the bind() method to bind the host address and port address, but in the
client program we use the connect() method to connect the host address and port address so that it can connect to the
server easily and communicate with it.
The values passed to .bind() depend on the address family of the socket. socket.AF_INET is (IPv4). So it expects a two-
tuple: (host, port). Host can be a hostname, IP address, or empty string. If an IP address is used, host should be an IPv4-
formatted address string. The IP address 127.0.0.1 is the standard IPv4 address for the loopback interface, so only processes on
the host will be able to connect to the server. If passing an empty string, the server will accept connections on all available IPv4
interfaces.
Port represents the TCP Port number to accept connections on from clients. It should be an integer from 1 to 65535, as 0 is
reserved.

IPv4 network standards reserve the entire address block 127.0.0.0/8 (more than 16 million addresses) for
loopback purposes. That means any packet sent to any of those addresses is looped back. The
address 127.0.0.1 is the standard address for IPv4 loopback traffic; the rest are not supported by all
operating systems.
Exceptions and Error Handling

• Compile time error is detected during compilation or development of the software.

• Logical error is detected during testing the result.

• Run time error will not give syntax or logical errors, these are the errors generated
by the users while using the software.
Errors and exceptions come into play when the user enters

a wrong input but still the software should work by giving the

error/exception message.

You might also like