Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

Python Revision

This document provides an introduction and overview of the Python programming language. It discusses Python's history and features, basic program structure using indentation, built-in data types like integers and strings, operators, functions, conditional statements, and other core concepts. The document is intended to teach beginners the basic building blocks of Python.

Uploaded by

en21cs301471
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Python Revision

This document provides an introduction and overview of the Python programming language. It discusses Python's history and features, basic program structure using indentation, built-in data types like integers and strings, operators, functions, conditional statements, and other core concepts. The document is intended to teach beginners the basic building blocks of Python.

Uploaded by

en21cs301471
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

1

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.

IDLE (Integrated Dvelopment and Learning Environment)

IDLE has the following features:

● coded in 100% pure Python, using the tkinter GUI toolkit


● cross-platform: works mostly the same on Windows, Unix, and macOS
● Python shell window (interactive interpreter) with colorizing of code
input, output, and error messages
● multi-window text editor with multiple undo, Python colorizing, smart
indent, call tips, auto completion, and other features
● search within any window, replace within editor windows, and search
through multiple files (grep)
● debugger with persistent breakpoints, stepping, and viewing of global and
local namespaces
● configuration, browsers, and other dialogs

BASIC PROGRAM STRUCTURE-QUOTATION AND


INDENTATION
● Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
● Python relies on indentation, using whitespace, to define scope; such as
the scope of loops, functions and classes. Other programming languages
often use curly-brackets for this purpose.

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

& Bitwise AND


^ Bitwise exclusive OR (XOR)
| Bitwise OR

c. Shift operators

<< Shift left


>> Shift right

d. Identity operators

is is the identity same ?


is not is the identity not same ?

e. Relational operators

< Less than


> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

f. Logical operators

and Logical AND


or Logical OR

g. Assignment operators

= Assignment
/= Assign quotient
+= Assign sum
*= Assign product
%= Assign remainder

7
-= Assign difference
**= Assign exponent
//= Assign floor division

h. Membership operators

in whether variable in sequence


not in whether variable not in sequence

Python 2/3 di erences

8
BASIC DATA TYPES

Python offers following built-in core 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

Functions: definition and use


Arguments
Block structure
Scope
Recursion
Argument passing
Conditionals and Boolean expressions
Lambda Function
Inbuilt functions
Sequences: Strings
String methods and formatting
Lists iteration
Tuples

10
Functions: definition and use

A function is a block of code which only runs when it is called.


You can pass data, known as parameters, into a function.
A function can return data as a result.

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:

User-defined functions are the fundamental building block of any


programme and are essential for modularity and code reuse because they
allow programmers to write their own function with function name that
the computer can use.

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:

1. Local scope- A variable created inside a function belongs to the local


scope of that function, and can only be used inside that function.
Eg-

>> 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 and Boolean expressions


Boolean Expressions:
Python has a type of variable called bool. It has two possible values: True and
False.Rather than putting True or False directly in our code, we usually get
boolean values from boolean operators.

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.

Why use lambda functions?


The power of lambda is better shown when you use them as an anonymous
function inside another function.

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"

To get the length of a string, use the len() function.


Eg-

>> 13

String methods and formatting

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‬

‭ he configparser module from Python's standard library defines functionality‬


T
‭for reading and writing configuration files as used by Microsoft Windows OS.‬
‭Such files usually have .INI extension.‬
‭The configparser module has ConfigParser class. It is responsible for parsing a‬
‭list of configuration files, and managing the parsed database.‬
‭Object of ConfigParser is created by following statement −‬

‭parser = configparser.ConfigParser()‬

‭script to reads and parses the 'sampleconfig.ini' file:‬

‭ he write() method is used to create a configuration file. Following script‬


T
‭configures the parser object and writes it to a file object representing 'test.ini’‬

‭import configparser‬

‭parser = configparser.ConfigParser()‬

‭parser.add_section('Manager')‬

‭parser.set('Manager', 'Name', 'Ashok Kulkarni')‬

‭parser.set('Manager', 'email', 'ashok@gmail.com')‬

‭parser.set('Manager', 'password', 'secret') f‬

‭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‬

‭ Create and configure logger‬


#
‭logging.basicConfig(filename="newfile.log", format='%(asctime)s‬
‭%(message)s', filemode='w')‬

‭ Creating an object‬
#
‭logger = logging.getLogger()‬

‭ Setting the threshold of logger to DEBUG‬


#
‭logger.setLevel(logging.DEBUG)‬

‭ 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.‬

‭ ccess mode:‬‭Access modes govern the type of operations possible in the‬


A
‭opened file. It refers to how the file will be used once it’s opened. These modes‬
‭also define the location of the File Handle in the file. File handle is like a cursor,‬
‭which defines from where the data has to be read or written in the file.‬

‭Manipulating file pointer using seek‬

‭ 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.‬

‭ he from_where argument is set to 0 by default. Therefore, the reference point‬


T
‭cannot be set to the current position or end position, in the text mode, except‬
‭when the offset is equal to 0.‬

‭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
‭A‬‭constructor‬‭is 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.‬

‭Operator Overloading in Python‬


‭ perator Overloading‬‭means giving extended meaning beyond their‬
O
‭predefined operational meaning. For example operator + is used to add‬
‭two integers as well as join two strings and merge two lists. It is‬
‭achievable because ‘+’ operator is overloaded by int class and str class.‬
‭You might have noticed that the same built-in operator or function shows‬

‭43‬
‭ ifferent behaviour for objects of different classes, this is called Operator‬
d
‭Overloading.‬

‭ mulating built-in types:‬


E
‭Python includes built-in mathematical data structures like complex‬
‭numbers, floating-point numbers, and integers. But occasionally we‬
‭might want to develop our own custom-behaved number classes. Here,‬
‭the idea of imitating number classes is put into use. We can create objects‬
‭that can be used in the same way as native numeric classes by simulating‬
‭them.‬

‭44‬
‭45‬
‭46‬
‭47‬
‭48‬
‭49‬

You might also like