Python Revision
Python Revision
2
UNIT-1
Basic Introduction
Introduction to Python
History
Features
Command interpreter and development environment-IDLE
Application of Python
Python 2/3 differences
Basic program structure - quotation and indentation
Operator
Basic data types
In-built objects
3
INTRODUCTION TO PYTHON
Python is an easy-to-learn yet powerful object oriented programming language.
It is a very high level programming language.
It is used for:
● Web development (server-side)
● Software development
● Mathematics
● System scripting
HISTORY
Python programming language was developed by Guido Van Rossum in
February 1991. Python was named after famous BBC comedy show namely
Monty Python’s Flying Circus.
FEATURES
● Python works on different platforms (Windows, Mac, Linux, Raspberry
Pi, etc).
● Python has a simple syntax similar to the English language.
● Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
● Python runs on an interpreter system, meaning that code can be executed
as soon as it is written. This means that prototyping can be very quick.
● Python can be treated in a procedural way, an object-oriented way or a
functional way.
APPLICATIONS OF PYTHON
1. Scripting
2. Rapid prototyping
3. Web applications
4. GUI programs
5. Game development
6. Database applications
7. System administrations
4
COMMAND INTERPRETER AND DEVELOPMENT
ENVIRONMENT-IDLE
A command interpreter allows the user to interact with a program using
commands in the form of text lines.
Many command interpreters are replaced by graphical user interfaces and
menu-driven interfaces.
Command interpreters have a large range of commands and queries available
for different operations.
5
Python Indentation:
Indentation refers to the spaces at the beginning of a code line.
Python uses indentation to indicate a block of code.
Eg-
OPERATORS
1. UNARY OPERATORS
+ Unary plus
- Unary minus
~ Bitwise complement
not Logical negation
2. BINARY OPERATORS
a. Arithmetic operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder/ Modulus
** exponent (raise to power)
// Floor division
6
b. Bitwise operators
c. Shift operators
d. Identity operators
e. Relational operators
f. Logical operators
g. Assignment operators
= Assignment
/= Assign quotient
+= Assign sum
*= Assign product
%= Assign remainder
7
-= Assign difference
**= Assign exponent
//= Assign floor division
h. Membership operators
8
BASIC DATA TYPES
1. Numbers
a. Integers
● Integers (signed)
● Booleans
b. Floating-Point Numbers
c. Complex Numbers
2. String
3. List
4. Tuples
5. Dictionary
IN-BUILT OBJECTS
This Python module provides direct access to all ‘built-in’ identifiers of Python.
For example, builtins.open is the full name for the built-in function open().
In a module that wants to implement an open() function that wraps the built-in
open(), this module can be used directly:
open(path, 'r')
9
UNIT-2
FUNCTION AND SEQUENCE
10
Functions: definition and use
Types of Function:
1. Library Function:
The Python language includes built-in functions such as dir, len, and abs. The
def keyword is used to create functions that are user specified.
2. User-defined Function:
Creating a function:
Using the def keyword
Eg-
Calling a function:
Eg-
>>
11
There are two ways to call user defined functions:
1. Call By Reference: Variables initialized are stored somewhere in the
computer's memory. Each variable has a particular address of the location
where it is stored. Call by reference refers to the calling of function by
passing arguments as the address of these locations of the variables rather
than their value.
2. Call By Value: Calling functions refers to the request of performing the
statements within a function named to be called whenever, we call a
function, generally we pass some arguments to it these arguments passed
are generally the value of variables. This process of calling a function is
referred to as call by value.
Arguments
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
Eg-
>>
Block structure
Using the group of statements, we can achieve a complete task.
Python uses an indentation mechanism to group the statements.
12
All statements with the same distance from the left side are considered as a
group or a block.
Eg-
>>
Scope
A variable is only available from inside the region it is created. This is called
scope.There are two types of scope:
>> 300
13
2. Global scope- A variable created in the main body of the Python code is
a global variable and belongs to the global scope. Global variables are
available from within any scope, global and local.
Eg-
>> 300
300
Recursion
Recursion is a common mathematical and programming concept. It means that a
function calls itself. This has the benefit of meaning that you can loop through
data to reach a result.
Eg-
tri_recursion() is a function that we have defined to call itself ("recurse").
We use the k variable as the data, which decrements (-1) every time we recurse.
The recursion ends when the condition is not greater than 0 (i.e. when it is 0).
14
>>
Conditionals:
Booleans are most useful when combined with conditional statements, using the
keywords if, elif, and else.
Eg-
15
>>
Lambda Function
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one
expression.
Syntax:
Eg-
1.
16
>> 15
2.
>> 30
Inbuilt functions
1. str():
The str() function converts the specified value into a string.
Eg-
>> 3.5
2. globals():
The globals() function returns the global symbol table as a dictionary.
A symbol table contains necessary information about the current
program.
Eg-
3. vars():
The vars() function returns the __dict__ attribute of an object.
The __dict__ attribute is a dictionary containing the object's changeable
attributes.
17
Eg-
4. eval():
The eval() function evaluates the specified expression, if the expression
is a legal Python statement, it will be executed.
Eg-
>> 55
5. exec():
The exec() function executes the specified Python code.
The exec() function accepts large blocks of code, unlike the eval()
function which only accepts a single expression.
Eg-
>> John
6. execfile():
Evaluates contents of a file.
7. repr():
Returns a readable version of an object.
18
8. ascii():
The ascii() function returns a readable version of any object (Strings,
Tuples, Lists, etc).
The ascii() function will replace any non-ascii characters with escape
characters.
Eg-
>>
Sequences: Strings
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
'hello' is the same as "hello"
>> 13
19
20
21
Lists iteration
List in python language is used to store multiple elements in a single variable.
Lists are one of the 4 data types in python language along with tuple, set, and
dictionary. List in Python is created by putting elements inside the square
brackets, separated by commas. A list can have any number of elements and it
can be of multiple data types. Also, all the operation of the string is similarly
applied on list data type such as slicing, concatenation, etc. Also, we can create
the nested list i.e list containing another list. They are mutable.
22
23
24
25
26
27
Tuples
Tuples are used to store multiple items in a single variable.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
28
29
30
31
32
NIT-3
U
File Operation
eading config files in python
R
Writing log files in python
Understanding read functions: read(), readline() and readlines()
Understanding write functions: write() and writelines()
Manipulating file pointer using seek
33
Reading config files in Python
parser = configparser.ConfigParser()
import configparser
parser = configparser.ConfigParser()
parser.add_section('Manager')
p=open('test.ini','w')
parser.write(fp)
fp.close()
34
Writing log files in Python
1. Create and configure the logger. It can have several parameters. But
importantly, pass the name of the file in which you want to record the
events.
2. Here the format of the logger can also be set. By default, the file works in
append mode but we can change that to write mode if required.
3. Also, the level of the logger can be set which acts as the threshold for
tracking based on the numeric values assigned to each level. There are
several attributes that can be passed as parameters.
4. The list of all those parameters is given in Python Library. The user can
choose the required attribute according to the requirement.
fter that, create an object and use the various methods like:
A
#importing module
import logging
Creating an object
#
logger = logging.getLogger()
Test messages
#
logger.debug("Harmless debug Message")
logger.info("Just an information")
logger.warning("Its a Warning")
logger.error("Did you try to divide by zero")
logger.critical("Internet is down")
35
nderstanding read functions: read(), readline() and
U
readlines()
ython provides inbuilt functions for creating, writing and reading files. There
P
are two types of files that can be handled in python, normal text files and binary
files.
● T
ext files:In this type of file, Each line of text is terminated with a
special character called EOL (End of Line), which is the new line
character (‘\n’) in python by default.
● B
inary files:In this type of file, there is no terminator for a line and the
data is stored after converting it into machine-understandable binary
language.
ython seek() method is used for changing the current location of the file
P
handle. The file handle is like a cursor, which is used for defining the location
of the data which has to be read or written in the file.
● 0 : The 0 value is used for setting the whence argument at the beginning of
the file.
● 1: The 1 value is used for setting the whence argument at the current
position of the file.
● 2: The 2 value is used for setting the whence argument at the end of the
file.
36
37
38
NIT-4
U
OOPS Concepts
1.Class
class is a blueprint for creating objects.
A
It defines the attributes and methods that all objects of that class will
have.
Suppose a class is a prototype of a building. A building contains all the
details about the floor, rooms, doors, windows, etc. We can make as many
buildings as we want, based on these details. Hence, the building can be
seen as a class, and we can create as many objects of this class.
C
● lasses are created by keyword class.
● Attributes are the variables that belong to a class.
2.Object
class instance is an object created from a class.
A
Each instance has its own set of properties and can execute methods
defined in the class.
Instances are created using the class name followed by parentheses.
39
onstructor:
C
Aconstructoris a special method that is called when a new class
instance is created.
It is used to initialize the attributes of the new class instance.
In Python, the constructor method is named '__init__'.
It is called automatically when an instance of the class is created.
estructor:
D
A destructor is a special method that is called when a class instance is
deleted.
It is used to clean up any resources that were used by the class instance.
40
3.Encapsulation
ncapsulation is used to restrict access to methods and variables. In
E
encapsulation, code and data are wrapped together within a single unit
from being modified by accident.
Encapsulation is a mechanism of wrapping the data (variables) and code
acting on the data (methods) together as a single unit. In encapsulation,
the variables of a class will be hidden from other classes and can be
accessed only through the methods of their current class.
Access Modifiers
1. public Access Modifier:The public member is accessible from inside or
outside the class.
2. private Access Modifier:The private member is accessible only inside the
class. Define a private member by prefixing the member name with two
underscores.
41
3. protected Access Modifier:The protected member is accessible. from
inside the class and its sub-class. Define a protected member by prefixing
the member name with an underscore.
42
4. Polymorphism
he word polymorphism means having many forms. In programming,
T
polymorphism means the same function name (but different signatures)
being used for different types. The key difference is the data types and
number of arguments used in the function.
43
ifferent behaviour for objects of different classes, this is called Operator
d
Overloading.
44
45
46
47
48
49