0% found this document useful (0 votes)
2 views68 pages

Python Notes

The document provides an extensive overview of Python programming, covering its history, significance in B.Tech careers, advantages, and various applications across multiple domains. It includes detailed explanations of Python's features, data types, operators, and differences between Python 2 and Python 3. Additionally, it highlights the importance of learning Python for students in engineering fields due to its versatility and demand in the job market.

Uploaded by

sksusilkumar8280
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)
2 views68 pages

Python Notes

The document provides an extensive overview of Python programming, covering its history, significance in B.Tech careers, advantages, and various applications across multiple domains. It includes detailed explanations of Python's features, data types, operators, and differences between Python 2 and Python 3. Additionally, it highlights the importance of learning Python for students in engineering fields due to its versatility and demand in the job market.

Uploaded by

sksusilkumar8280
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

“No matter which field of work you want to go in, it is of

great importance to learn at least one programming


language.”

PYTHON

If debugging is the process of removing bugs,


then programming must be the process of putting them in.

SUSIL KUAMR SAHOO


Core Python

Table of contents
Chapter 1

Introduction ………………………………………………………………. 03

Chapter 2

Operators

(Assignment, logical, relational etc.) ………………………………………………………………. 06


Chapter 3

Data Types
(List, Tuple, Dictionary etc.) ………………………………………………………………. 10

Chapter 4

Control structure and

Control statements

(if, if-else, loop etc.) ………………………………………………………………. 32

Chapter 5

Function
(User define, built-in function etc.) ………………………………………………………………. 40

Chapter 6

Exception Handling
(All types of exception) ………………………………………………………………. 50

Chapter 7

File Handling

(text, binary, csv, zip files) ………………………………………………………………. 52

2|Page
Introduction

History of python

Python is a high-level, interpreted, and general-purpose programming language that emphasizes code readability and
simplicity. It was created by Guido van Rossum in the late 1980s while he was working at the Centrum Wiskunde &
Informatica (CWI) in the Netherlands. Van Rossum wanted to develop a language that combined the capabilities of the ABC
language with access to system calls and file systems, making it suitable for scripting and automation. He officially released
Python to the public in 1991 as version 0.9.0. The language was named "Python" after the British comedy group Monty
Python, not the snake, reflecting van Rossum's desire to make programming fun. Python quickly gained popularity due to its
clear syntax and dynamic typing, which made it easier to learn and use compared to other programming languages. Over the
years, it has evolved significantly, with major versions such as Python 2.0 (released in 2000) introducing features like garbage
collection and list comprehensions, and Python 3.0 (released in 2008) improving language consistency and Unicode support.
Today, Python is maintained by the Python Software Foundation and is widely used in web development, data science,
machine learning, automation, and many other fields, making it one of the most popular programming languages in the
world.

Role of Python in a [Link] Career

Python plays a crucial role in shaping the career of [Link] students across various branches, especially in Computer Science,
IT, Electronics, and even Mechanical and Civil engineering. Its simple syntax and readability make it an ideal first programming
language, helping students build a strong foundation in coding. Python is extensively used in data science, machine learning,
artificial intelligence, web development, cyber security, and automation, which are high-demand areas in the current job
market. With libraries like NumPy, Pandas, TensorFlow, and Django, students can develop real-world applications ranging from
data analysis to full-stack web applications. For electronics and robotics students, Python is used with Raspberry Pi and
Arduino to control hardware. In core engineering branches, Python helps in tasks like simulation, data visualization, and
automating repetitive calculations. Python is also widely used in academic projects, internships, and research work due to its
versatility and strong community support. Knowing Python increases job opportunities, aids in cracking technical interviews,
and makes students industry-ready. Additionally, it is a preferred language in competitive coding and hackathons. Thus,
learning Python not only enhances technical skills but also opens up multiple career paths, making it an essential asset in any
[Link] student’s career journey.

Advantages of Python in real world

Python offers numerous advantages in real-world applications, making it one of the most widely used and preferred
programming languages globally. Its biggest strength lies in its simplicity and readability, which allows both beginners and
professionals to write clean and efficient code quickly. Python is platform-independent, meaning code written in Python can
run on Windows, macOS, or Linux without modification. One of Python’s greatest assets is its vast collection of libraries and
frameworks like NumPy for scientific computing, Pandas for data analysis, Django and Flask for web development, and
TensorFlow and PyTorch for machine learning. These tools reduce development time and effort significantly.

Python is heavily used in data science, artificial intelligence, machine learning, automation, web development, cyber
security, game development, and even robotics. It is also useful in automation scripts, saving businesses time and reducing
errors in repetitive tasks. Due to its widespread industry adoption by companies like Google, NASA, Netflix, and Instagram,
Python skills are highly valued in the job market. Moreover, Python has a massive community that offers continuous support
and development. Whether it's building a quick prototype or managing a large-scale application, Python delivers speed,
flexibility, and scalability—making it ideal for real-world problem-solving across domains.

3|Page
Use Of C: - We Can Develop Any System Program (OS), Compiler, System Driver, Desktop App.

Use Of C++: - Game Development, System Program, Web App, Desktop App.

Use Of Java: - Web Application, Mobile Application, Desktop Application, Game.

Use Of Python: - Can Be Use Anywhere:

➔ Works With Array : Py + NumPy


➔ Works With Data Visualization : Py+ Matplotlib
➔ Make Some Data frame : Py +Pandas
➔ Image Processing : Py + Pillow
➔ Game : Py + Pygame
➔ Database (SQL) : Py + MySQL
No SQL : Py + Pymongo
➔ Web Application : Py + Flask/Django
➔ Mobile Application : Py + Ksvy
➔ Deep Learning : Py + Tensor Flow

Way to write python code

➢ Script Mode: It Is called IDLE/python shell.


We can’t save any file. this mode is only use to test some code or module.
➢ Interactive mode
Using this mode we can save using py .
In this mode we can save that code for used.

❖ NOTE: - CTRL+C/CTRL+Z IS USED TO DEACTIVE SCRIPT MODE.

Version of python

3.14.4

Two versions:

Py2x → python 2 → up to 2.6 all are py2.

Py3x → python3 → after 2.6 all are py3

Difference Between Python2 & Python3

features PYTHON 2 PYTHON3


For output print Print ()

Division 5/2 = 2 5/2 = 2.5


Predefine class bytes(),bytearray() bytes (), bytearray()
predefine class are not support predefine class are support
Range It supports xrange(stop) & range(stop). It supports only range ().
User input input () takes number type as user input. input () takes string type data as user input.
raw input () takes string type as user input. For other type it makes type casting.
Example #python2 user input #python3 user input
Rollno = input(“enter student rollno”) Rollno =int( input(“enter student rollno”))
Name=raw_input(“enter student name”) Name=input(“enter student name”)
Print “student rollno. =”,Rollno Print (“student rollno. =”,Rollno)
Print “student name =”,Name Print (“student name =”,Name)

4|Page
❖ In python3 everything is called as class. To represent any class, we make some object. For a class we can create n
numbers of object is used to access number of a class.

Syntax to make object in c++: -

Classname object_name;

Syntax to make object in java: -

Classname objectname = new classname;

Syntax to make object in python: -

Objectname = classname ()

type() → is used to check a object / variable is which type/class.

id() → is used to check reference value/address of any object/variable.

len() → is use to get length of any iterable object.

Top 5 Advantages of Python Over Other Languages

1. Simple and Easy to Learn

• Python uses clean, readable syntax similar to English.

• No need to write complex code blocks (e.g., no semicolons or curly braces).

2. Faster Development with Fewer Lines of Code

• Python requires less code to perform the same task.

• Great for rapid prototyping and startup projects.

3. Large Standard Library and Community Support

• Thousands of ready-to-use libraries for:

o Web development (Django, Flask)

o Data science (Pandas, NumPy)

o Machine learning (scikit-learn, TensorFlow)

4. Cross-Platform and Portable

• Python code runs on Windows, Linux, macOS without modification.

• Write once, run anywhere.

5. Perfect for AI, ML, and Data Science

• Most widely used language in AI, machine learning, data analysis, and automation.

• Supported by major tools like Jupyter, PyTorch, TensorFlow.

5|Page
OPERATORS
Expression: - Collection of both operator and operand is called expression.

E.g.: - res = 4 + 6

Operator → =, +

Operand → res,4,6

Operator: - Operator is a symbol which performs some task using operand.

Operand: - Operand may be variable or constant.

Constant: - Constant means value can’t be change/update.

Variable: - Value can be change.

Rules for making variable:

➢ Using A-Z, a-z, 0-9 but no space and symbol are allowed. One symbol can be allow i.e. _(underscore).
➢ Keyword can’t be used as any variable name.
➢ 1st character must be letter but not digit.

Keyword: - All predefine/reserve word is called as keyword.

E.g.:- False, None, True, and, break, if, else, in etc.

Types of Operators:

Using operand, operators are three types;

➢ Unary: work with one operand


e.g.: not, ~, +, -
➢ Binary: works with two operands
e.g.: +, -, /, *, **, >, <

➢ Ternary: works with more than 2 or 3 operands.


e.g.: conditional operators

Using operation

➢ Arithmetic : +, -, *, **, /, //, %


➢ Relational : >, <, >=, <=, ==, !=
➢ Conditional
➢ Logical : and, or, not
➢ Bitwise : &, |, ^, ~, >>, <<
➢ Assignment : =
➢ Compound assignment : +=, _=, *=, /=, **=, //=, %=, |=,^=, >>=, <<=
➢ Membership : in, not in
➢ Identity : is, is not
➢ Slicing : regular → [start : stop]
: extended → [start : stop : step]
➢ Extra : [ ], ( )

6|Page
Arithmetic operators

It refers to symbol or functions that perform mathematical operation such as addition, subtraction, multiplication, division
etc. These operators allow for numerical calculations and manipulation within computer programs.

Examples:

Conditional operators:

It is a simplified, single-line version of an if-else statement.

Syntax:

True_value if condition else false_value

Examples:

Logical operator

These operators are used to combine multiple conditions.

➢ Logical and & or return a expression & logical not return bool value.
➢ In logical and if all condition are true then It is true otherwise false.
➢ In logical or if anyone condition is true then it is true otherwise false.
➢ In logical not it alter the case.

Examples:

Bitwise operator

Bit: - It means binary digits(0,1).

It works in bit level.

~ - I’s compliment (unary operator)

Res = -n-1

>> (right shift) - no // 2**shift bit

<< (left shift) - no*2**shift bit

❖ I/P (dec value) → convert dec to bin → operation → bin to dec → O/P (dec).

7|Page
Bits & | ^
00 0 0 0
01 0 1 1
10 0 1 1
11 1 1 0
Examples:

Assignment operator

Examples:

Compound assignment

Example:

Membership operator

It check/search element is present in iterable object or not.

If present return true otherwise false but if object is not iterable then raise an error.

Syntax:

element in iterable object

8|Page
Examples:

Identity operator

It checks reference value of object. If two object reference are same then it return true otherwise false.

If two object values are same and both object are mutable then it return true otherwise false.

9|Page
PREDEFINE CLASS / DATA TYPES / DATA
STRUCTURE / LITERALS
In python everything is called as class and to represent class we make object.

Object is used to access member of any class (variable, function, methods).

Differences between function and methods

Function Method
Function is block of code which is called independently by Method is called dependently by its name associated with
its name. an object.

If any data (parameters) are passed, they are passed A method is implicitly passed the object on which it is
explicitly. invoked.

Function does not deal with class and its instance concept Method can operate on the data that is contained by the
corresponding class.

Examples: - int(), float(), max() Examples:- randint(), sqrt()

Python data types

➢ Numeric : int, float, complex


➢ Sequence: string, list, tuple
➢ Mapping: dictionary
➢ Boolean: bool
➢ Set type: set, frozen set
➢ Binary types: bytes, bytearray

List predefine class / data structure

Basic points:

➢ List is a predefine class.


➢ List element can be represented by ‘ [ ] ’.
➢ Each element of list class are separate by comma.
➢ List is a collection of both similar and dissimilar type of elements.
➢ Object name return all element present in list class.
➢ It support duplicates elements.
➢ It is linear / ordered data structure because it follow item insert order.
➢ It is iterable object, we can be get element from object.
➢ It is mutable object so we can be update / modify list element.
➢ Len() is used to count numbers of element present in list class.

Define using class name and type cast / conversion

Index:

➢ Index is used to get a single element from list class.


➢ Index is used to make read, write and update operation with list class.
➢ List support both +ve and –ve indexing.
➢ +ve valid index start from 0 to (len-1).
➢ -ve index valid index start from (– len) to -1.
10 | P a g e
List class operators:

List class doesn’t support all operator.

It support some operators like:

➢ Arithmetic :
“+“- merge element
“*” – replicate elements
➢ Relational :
“>, <” – only check 1st index and return result.
“>=, <=, ==, !=” – check each element or length of object.
➢ Assignment :
“=” – make a copy.
➢ Membership : in, not in
➢ Identity : is, is not
➢ Slicing: It returns a sublist or group of elements.
Slicing is two types:
• Regular: [start : stop]
• Extended:[start : stop : step]

Regular: [start : stop]: -

[ : ] → start from 0 index , stop till end of index.

[start : ]→ start from given index, stop till end of index.

[: stop]→ start from 0 index, stop index value is not include.

It include stop index previous value.

[Start: stop]→ start from given index number till the previous of given stop index no.

11 | P a g e
OUTPUT

12 | P a g e
Predefine list class function

➢ len() → to get the length of list


➢ sum() → sum of all list elements
➢ max() → to get max value among element
➢ min() → to get minimum value among elements
➢ sorted(reverse = false/true) → make ascending or descending order
(Default value is false)
➢ del () → delete object.
➢ shuffle() → present in random module

OUTPUT

13 | P a g e
List class predefine method

❖ NOTE: help (list) IS USED TO GET MANUAL.

Method Description
append(x) Add item x to the end
insert(i, x) Insert item x at position i
extend(iterable) Extend list by appending elements from iterable
remove(x) Remove first occurrence of x
pop([i]) Remove and return item at index i (last if not specified)
index(x[, start[, end]]) Return index of first occurrence of x
count(x) Return number of times x appears
sort() Sort the list in ascending order
reverse() Reverse the list in place
copy() Return a shallow copy of the list
clear() Remove all elements from the list

14 | P a g e
OUTPUT

Nested list class

If we define a list within another list then that is called as nested list.

Tuple predefine class / data types

Basic point:

❖ tuple() is predefine class.


❖ tuple element is presented by () and each element separated by comma(,).
❖ Tuple is a collection of both similar and dissimilar types of elements.
❖ Tuple object return all element present in tuple class.
❖ Tuple support duplicate elements.
❖ Tuple is linear / order data structure because it follow item insert order.
❖ Tuple is a iterable object.

15 | P a g e
❖ It is a immutable object.
❖ To make tuple element minimum two element or more that 2 elements are required.
❖ Without () we make tuple object if more than one element are separated by comma.

Definition using calss name

Definition without using class name

Index: index is use to make read and write but not update operation because it is immutable object.

Tuple class operator

Operator Name Description Example

+ Concatenation Combines two tuples (1, 2) + (3, 4) → (1, 2, 3, 4)

* Repetition Repeats a tuple (1, 2) * 3 → (1, 2, 1, 2, 1, 2)

in Membership Checks if an element is in the tuple 2 in (1, 2, 3) → True

not in Membership Checks if an element is not in the tuple 4 not in (1, 2, 3) → True

== Equality Checks if tuples are equal (1, 2) == (1, 2) → True

!= Inequality Checks if tuples are not equal (1, 2) != (2, 1) → True

<, <=, >, >= Comparison Compares tuples lexicographically (1, 2) < (2, 1) → True

[] Indexing Access an element by index (1, 2, 3)[0] →1

[:] Slicing Get a slice of a tuple (1, 2, 3, 4)[1:3] → (2, 3)

len() Length Returns number of items len((1, 2, 3)) →3

min() / max() Minimum / Maximum Smallest or largest item min((2, 5, 1)) →1

sum() Sum Adds up numeric values sum((1, 2, 3)) →6

tuple() Type cast Converts iterable to tuple tuple([1, 2]) → (1, 2)

16 | P a g e
Tuple class predefine function

Same as list class.

Tuple predefine methods

➢ index () – to get index of given value present in tuple. It always give first occurence.
➢ count() – to count occurrence of given value

bytes() / bytearray()

➢ It is predefining class.
➢ It is iterable
➢ It supports int type value in range (0-255).
➢ To get single element we used index.

But one difference is bytes() is immutable object and bytearray() is mutable object.

Set predefine class

Basic points:

➢ Set() is predefine class.


➢ Set element can be represent within { } and each element must be separate by comma.
➢ Set is collection of both similar and dissimilar types of elements.
➢ Set doesn’t support duplicate elements.
➢ Object name return all unique element present in set class.
➢ Set is non-linear / under data structure because it doesn’t support element / item insert order.
➢ It is iterable object.
➢ It is mutable object so element update can be allowed.
➢ We can’t be single element from set class using index because it doesn’t support item insert order.

Definition using class name

Definition without using class name

17 | P a g e
Index: Set doesn’t support index because it is non-linear data structure.

Set class operator

➢ - : difference
➢ & : intersection
➢ | : union
➢ ^ : symmetric difference
➢ = : copy
➢ in,not in
➢ is, is not
➢ Slicing is not support because it doesn’t support index.

Output

18 | P a g e
Set class predefine function

➢ len()
➢ max()
➢ min()
➢ sum()
➢ sorted()
➢ del()

Output

Set class predefine methods

Method Description Example


add(elm) Adds elm to the set [Link](10)

pop()
Removes and returns a [Link]()
random element

remove(elm)
Removes elm from the set [Link](3)
(raises error if not found)

discard(elm)
Removes elm if it exists [Link](3)
(no error if not found)

clear()
Removes all elements [Link]()
from the set

copy()
Returns a shallow copy of s2 = [Link]()
the set
Adds all elements from
update(other) other into the set (like [Link]({4, 5})
union in-place)

difference(other)
Returns elements in s but [Link](t)
not in other (new set)
Removes elements found
difference_update(other) in other from the set s.difference_update(t)
(modifies in-place)

intersection(other)
Returns a new set with [Link](t)
common elements

19 | P a g e
Method Description Example
Keeps only elements also
intersection_update(other) in other (modifies in- s.intersection_update(t)
place)

symmetric_difference(other)
Returns elements in either s.symmetric_difference(t)
set but not both (new set)
Updates set with
symmetric_difference_update(other) symmetric difference s.symmetric_difference_update(t)
elements

issubset(other)
Returns True if set is [Link](t)
subset of other

issuperset(other)
Returns True if set is [Link](t)
superset of other

isdisjoint(other)
Returns True if sets have [Link](t)
no elements in common

20 | P a g e
Output

Frozenset: same as set class but frozenset is immutable object.

Dictionary predefine class / data types

Basic points:

➢ dict is a predefine class.


➢ dict element are presented by {} and each pair of element are separated by comma.
➢ Dict is collection of pair of elements (key : value).
➢ Key can’t be duplicate if duplicate it overwrites with last value. But value may be duplicate or not.
➢ All key must be immutable type, nut value can be both.
21 | P a g e
➢ It is called map object.
➢ It is iterable.
➢ It is mutable so using keys we can be update value.
➢ In other language dict is called as json and each pair of element is called as bson.

Definition using class name

Definition without using class name

Definition using zip function

Key :

• Dict support key to get value from dict.


• By using key we can be update value.
• Invalid key raise an error (keyError).

Dict class operator

Operator Description Example


== Checks if two dictionaries are equal (same keys and values) d1 == d2

!= Checks if two dictionaries are not equal d1 != d2

in Checks if a key exists in the dictionary 'name' in d

not in Checks if a key does not exist in the dictionary 'age' not in d

[] Accesses or sets a value by key d['key'] or d['key'] = value


del Deletes a key-value pair del d['key']

22 | P a g e
Dict predefine functions

❖ NOTE: ALL FUNCTIONS ONLY WORK WITH KEY BUT NOT WITH VALUE.

➢ len()
➢ max()
➢ min()
➢ sorted()
➢ del()
➢ sum(): if all key in numeric type.

23 | P a g e
Output:

Predefine methods

Method Description Example


setdefault(key,
default) Returns the value of key. If key does not exist, inserts key with default value. [Link]('x', 100)

update(other_dict)
Updates dictionary with key-value pairs from another dictionary or iterable of [Link]({'a': 1, 'b':
pairs 2})

items() Returns a view object of all key-value pairs as tuples [Link]()

popitem() Removes and returns the last inserted key-value pair (LIFO order) [Link]()

pop(key[, default])
Removes the specified key and returns the value. If key not found, returns [Link]('a', 'not found')
default if given
keys() Returns a view object of all keys in the dictionary [Link]()

values() Returns a view object of all values in the dictionary [Link]()

clear() Removes all items from the dictionary [Link]()

copy() Returns a shallow copy of the dictionary d2 = [Link]()

24 | P a g e
Output:

String predefine class / data types

Basic points:

➢ str () is predefine class.


➢ C, c++, java support both char and string type but python only support string type.
➢ In c, c++, java every char can be represent by single quote(‘ ’) and string can be represent by double quotes(“ ”).but
in python both single and double quotes are used to represent string type.
➢ Collection of character is known as string.
➢ It is a linear / ordered data structure because it follow element insert order.
➢ It supports duplicate character.
➢ It is iterable object.
➢ It is immutable object. So modification is not allow.
➢ Triple single / double quote is used to represent multiline string.
➢ All key present in a keyboard is called char.
➢ Each char support int type value is called as ASCII value.

Definition using class name

Definition without classs name

Index: same as tuple class.

25 | P a g e
String class operator

Operator Description Example Result


+ (concatenation) Joins two strings together 'Hello' + ' World' 'Hello World'

* (repetition) Repeats the string a given number of times 'Hi' * 3 'HiHiHi'

[] (indexing) Accesses a character by index 'Python'[0] 'P'

[:] (slicing) Retrieves a substring using start:stop:step 'Python'[1:4] 'yth'

in Checks if a substring exists in the string 'on' in 'Python' True

not in Checks if a substring does not exist in the string 'java' not in 'Python' True

== Checks if two strings are equal 'abc' == 'abc' True

!= Checks if two strings are not equal 'abc' != 'def' True

<, <=, >, >= Lexicographically compares strings based on Unicode values 'apple' < 'banana' True

= It use to copy a string to another variable. 'Age: %d' % 25 'Age: 25'

f'' (f-strings) Modern formatting for embedding expressions f"Age: {25}" 'Age: 25'

Output

26 | P a g e
String class predefine function

➢ len()
➢ max()
➢ min()
➢ sorted()
➢ ord() → get char to its ascii value
➢ chr() → get ascii value to char

Set class predefine mehods

Method Description
capitalize() Capitalizes the first character of the string.
casefold() Converts string to lowercase, more aggressive than lower().
center(width) Centers the string within the given width, padding with spaces.
count(sub) Counts occurrences of a substring.
encode() Encodes the string into bytes using a specified encoding.
endswith(suffix) Checks if string ends with the specified suffix.
expandtabs(tabsize) Replaces tabs with spaces (default tab size = 8).
find(sub) Returns the lowest index of the substring (or -1 if not found).
format() Formats string using placeholders {}.
format_map(mapping) Similar to format(), but uses a dictionary-like object.
index(sub) Like find(), but raises ValueError if not found.
isalnum() Returns True if all characters are alphanumeric.
isalpha() Returns True if all characters are alphabetic.
isascii() Returns True if all characters are ASCII.
isdecimal() Returns True if all characters are decimal (0–9).
isdigit() Returns True if all characters are digits.
isidentifier() Returns True if string is a valid Python identifier.
islower() Returns True if all cased characters are lowercase.
isnumeric() Returns True if all characters are numeric (includes superscripts, etc.).
isprintable() Returns True if all characters are printable.
isspace() Returns True if all characters are whitespace.
istitle() Returns True if string is title-cased.

27 | P a g e
Method Description
isupper() Returns True if all cased characters are uppercase.
join(iterable) Joins elements of an iterable with the string as a separator.
ljust(width) Left-justifies string in a field of given width.
lower() Converts all characters to lowercase.
lstrip() Removes leading whitespace or specified characters.
maketrans() Returns a translation table (used with translate()).
partition(sep) Splits the string at the first occurrence of sep.
removeprefix(prefix) Removes the specified prefix if present (Python 3.9+).
removesuffix(suffix) Removes the specified suffix if present (Python 3.9+).
replace(old, new) Replaces all occurrences of a substring with another.
rfind(sub) Returns the highest index of the substring (or -1 if not found).
rindex(sub) Like rfind(), but raises ValueError if not found.
rjust(width) Right-justifies string in a field of given width.
rpartition(sep) Splits the string at the last occurrence of sep.
rsplit(sep) Splits string from the right at sep.
rstrip() Removes trailing whitespace or specified characters.
split(sep) Splits string at separator into a list.
splitlines() Splits string at line boundaries (\n, \r\n, etc.).
startswith(prefix) Checks if string starts with the specified prefix.
strip() Removes leading and trailing whitespace or characters.
swapcase() Swaps case (upper <-> lower).
title() Capitalizes first letter of each word.
translate(map) Translates characters using translation table.
upper() Converts all characters to uppercase.
zfill(width) Pads string on the left with zeros to fill width.

28 | P a g e
29 | P a g e
Output

30 | P a g e
31 | P a g e
Control structure and control statements
Control structure

Python supports two types of control structure:

➢ branch / decision making


➢ iter / loop control structure
but c / c++ / java support four control structure
➢ Decision making control structure(if, if else, else if, nested if).
➢ Selected (switch, case, default).
➢ Jump (goto).
➢ Loop (for, while, do while).

Control statements

Python support three control statements:

➢ Pass
➢ Break
➢ Continue

But c, c++, java support three control statements

➢ Break
➢ Continue
➢ Return

Difference between c/ c++/ java and python

feature c/ c++/ java python

End char () :

For block {} Indent

Loop name Else if elif

supports Loop doesn’t supports Each loop supports else block


Else block

Branch / decision making control structure

It supports if, if else, elif, nested if.

1. If statement : If only one condition is given and for that condition only true value is given then used if statement.
And else block is not present.
Syntax: -
i. If condition: True/if block logic/expression

(if one line statement or expression is given)

ii. If condition:
True block/if block/expression
(if we use multiline expression)
2. If else statement: If only one condition is given and for that condition both True and False value is given then use if
else statement. Else block never check any condition.

32 | P a g e
Syntax: -

if condition:

expression / True value / if block

else:

expression / False value / else block

3. elif statement: if multiple conditions are given and for each condition true is given then used elif statement. Use up
to nth term condition.
Syntax: -
if condition:
True value / expression

elif condition:

True value / expression

else:
False value / expression

4. nested if statement: within if block if we define another if block then that is called as nested if.

Syntax:
if condition1:

# Outer if block

if condition2:

# Inner if block

# Do something

else:

# Inner else block

# Do something else

else:

# Outer else block

# Do something different

Output

33 | P a g e
OUTPUT

Example

34 | P a g e
OUTPUT:

Example

Output

35 | P a g e
Question

1) Find the largest among three no.


2) Check if year is leap year.
3) Check triangle type using sides.

Loop control structure

Python supports two loops

➢ While
➢ For

for, while is called entry loop whereas do while is called as exit control loop.

When we works with any loop we used some terms like:

➢ initialization
➢ Condition
➢ Logic / expression
➢ Update value

While loop

It allow only iterable object. In python while loop supports else block, If condition is false then else block will eexecute.

Syntax:(while) Syntax:(while else)


Initialization Initialization
while condition: while condition:
Logic / expression Logic / expression
Update value Update value
else:
false block

Examples:

36 | P a g e
Questions

5. Wap to find factors of any number.


6. Check a number is prime or not.
7. Wap to find factors of any number except 1.
8. Wap to find factors of any number except itself.
9. Wap to find factors of any number except both.

For loop: for each loop

For loop only works with iterable object and return each iter element. But if object is not iterable then it raise an error (object
is not iterable)in python list, tuple, bytes, bytearray, set, str, frozenset are iterable object.

Syntax:

For iter in iterable_object:

print(iter)

OR

For i in iterable_object:

print(i)

Example

Example

range() class

➢ range() is predefine class.


➢ It is iterable and mutable object.
➢ range(stop)→ start from 0,stop index is not include, it include up to previous, step 1.
➢ range(start, stop)→ start from given, stop index is not include, it include up to previous, step 1.
37 | P a g e
➢ range(start, stop, step)→ start from given, stop index is not include, it include up to previous, step is given.

Example

Control statements

Python support three control statements.

• pass
• break
• continue
exit()

Pass statement: To define empty definition we used pass ststement. To avoid logic / body of any definition we used pass
keyword. Pass is used to avoid the indentation error.

Uses of pass

break: Any loop can be terminating in two different ways:

• Normal termination: when head of program will be false.


• Abnormal termination: ctrl + c / ctrl + z.

By using break statement we terminate any loop abnormally.

break is used to terminate current iteration / loop and move the cursor outside of current loop.

Example

38 | P a g e
exit() It is used to terminate a program.

Continue: It is use to skip the current iteration and move the cursor head of loop to start again.

In while loop before continue we must update value but in for update.

Example (in while loop)

Example (in for loop)

Program

39 | P a g e
Function
Function is block of code to solve any given task. def keyword is used to define a function in python.

In c / c++ every program start execution from main() and in java it start execution from main() method. But in python main() is general
function / user define function.

Syntax to make empty function:

Syntax to make non empty function:

❖ NOTE: DOCSTRING IS OPTIONAL.

To execute any function both function definition and calling are used. Without definition if we call a function ten it raise an
Error (NameError).But with function definition without call program will be execute but not output and no error.

❖ NOTE: IN PYTHON 1ST WE DEFINE A FUNCTION THEN CALL THAT FUNCTION OTHERWISE ERROR.

Execution control flow

Example

Types of variable

According to function variable are two types:

➢ Global variable
➢ Local variable

Global variable

If a variable is not belongs to any function then that variable is called as global variable.

If a variable is not define within any function then such types of variables is called as global variable.

Global variable value can be access by any function directly.

Python doesn’t allow modification / update.

If we doesn’t allow modify we get an error (unboundedLocalError).

So to avoid that error we used global keyword.

40 | P a g e
Local variable

If a variable is belongs to any function then that variable is called as local variable in that function.

If we define any variable within a function then such types of variable are called as local variable.

If local var and global var name is same then function will give priority to local var but not global var.

Local variable can be access where it is local but for other function that will be not accessible.

If we access local variable in other function it raise an error.

To access local var in other function we used:

• Using global keyword


• Using nonlocal keyword

Using global keyword

Using nonlocal keyword

Parameter / argument

To access local variable in other function we used parameter / argument cncept.

Parameters are two types:

• Actual parameter: - If a parameter is used at the time of function definition then such types of variable is called as
formal parameters.
• Formal parameter: - if a variable is used at the time of function call then such type of variable is called as actual
parameters.

41 | P a g e
❖ NOTE: ACTUAL PARAMETER CAN’T BE CHANGE BUT FORMAL PARAMETER NAME MAY BE SAME AS ACTUAL
PARAMETER OR DIFFERENT.
❖ NOTE: NUMBER OF PARAMETER PASS IN CALLING TIMES AND CATCH IN DEFINITION TIME MUST BE SAME.

Example

Example

Example

Nested function

If a function is define with in another function then such type of function is called as nested function.

Nested function can be access all attribute where it is nested but modification / update is not allow.

Nested function is also called as local function.

If we try to update then it raise an error(unboundedLocalError). To avoid that error we use nonlocal keyword.

Example

42 | P a g e
First class object : (without class)

If we pass a function definition as actual argument then that concept is called as first class object and that function name is
first class object.

Example

Types of function calling

Python support only call by reference.

Call by reference is two types:

• Reference as value type (reference + value type)


• Reference as reference type(reference + reference)

Call by value (not supported by python): - Any modification / update in formal parameter can’t be update with atual
parameter. Because both actual and formal parameter allocates different memory.

Call by address (not supported by python): - Any modification / update in formal parameter can be update with atual
parameter. Because both actual and formal parameter allocates single memory.

Call by reference: - reference type doesn’t allocate memory, it use which memory allocate previously.

➢ In python all immutable object works like reference as value type int, float, complex, None, bytes, string, frozenset
are immutable object in python.
➢ In python all mutable object work like reference as reference type list, bytearray, set, range, dictionary are mutable
object in python.

Example (reference as value type)

43 | P a g e
Example (reference as reference type)

Return statement

Return statement is used to terminate a function abnormally.

Return statement can’t be used outside function.

Return statement by default return none type of value

Return statement return a value to caller function (from where call function).

Example

Example

In c, c++ return statement by default return only one value , but In python we can be return multiple value using pack and
unpack.

If we return multiple value that value must be tuple type of object.

44 | P a g e
Function overloading

Python doesn’t support function overloading.

Multiple functions having same name with different signature (number of parameters of types of parameter) is called as
function overloading.

Lambda function

If a object have no name then that object is called as anonymous object.

If a function has no name then that function is called as anonymous function. So lambda function is called as anonymous
function.

Difference between general function and lambda function

General function Lamda function


it use def keyword. It use lambda keyword.
Return is required in general function. Return is not require in lambda function.
Return element will be python data types. Return element will be function object.
Execution time is slower. Execution time is faster.

Example

Predefine function

Python supports some predefine functions like map(), filter(), reduce().

All predefine functions works with iterable object.

map() function

it works with each element of iterable object and return result.

Syntax: map (Expression / logic ,iterable / sequence object)

Example

Example

45 | P a g e
filter() function

filter function works with each element of iterable object and return only true value according to given condition.

It always returns value. filter function return filter type of object.

Syntax: filter(expression / logic, iterable / sequence)

Example

reduce() function

reduce function works with each element of iterable object and return only int type of object. Reduce function present in
functools module so before works with reduce function we must import sys module return type is int type.

Syntax: reduce(expression / logic, iterable, sequence object)

Example

Example

generator() function

without return statement if we want return a sequence / list of element we used generator function.

The return type of generator function is generator object. From that generator object to set single element we used next()
within a function in place of return . if we used yield function

46 | P a g e
Recursion function

If a function is called itself then that function is called as recursion function.

If we solve any task in recursion that can be solve using loop and vice versa.

Maximum recursion is raise an error (Recursionerror) . Loop is better than recursion because loop doesn’t allocate memory
where as each recursion allocate memory inside stack management.

To set recursion limit we used sys module. Inside sys module setrecursionlimit() attribute is used to set value.

Example

Types of arguments

There are 5 types of arguments:

• Positional as argument / required position as arguments.


• Keyword as argument / name as arguments.
• Default as argument.
• Variable length as arguments (*args).
• Keyword variable length as arguments (**kwargs).

Positional as argument

At the time of function definition which arguments are used is called as positional / required positional as arguments.

Numbers of argument pass and catch must be same otherwise it raise an error.

If we change the order of arguments then program will be execute but we get invalid input.

Keyword as argument

Number of argument pass and catch must be same otherwise it raise an error.

But if we change the order of arguments then also we get valid output due to keyword as argument.

47 | P a g e
If we take both positional and keyword as argument then 1st we write all positional argument then write keyword as
argument otherwise we get SyntaxError.

Default as argument

Number of argument pass and catch may be same or not, if same then which argument is pass that argument is catch
otherwise at time of definition which argument value we set that value will be execute.

Variable length as argument

If user passes n number of arguments to catch all argument with one parameter we used variable length as argument.

To catch all argument we used *n(*means all n means arguments).

Keyword variable length as argument

To catch all argument we used *n(means all, n means argument)

Command line argument

At the time of program execution if we initialised any object / argument that is called as comment line argument .

Which we pass at the time of execution that must be store in argv(argument evctor). All argument must be string type.

By default we pass one argument is itself program (0 index).

In python argv present in sys module

48 | P a g e
Example

Example

49 | P a g e
Exception handling
In programming Error are two types:

• Compile time Error


• Runtime Error

Compile time Error

Before execution if we get some error or then that error is called as SyntaxError.

SyntaxError doesn’t allow to start execution process. At the time of compilation it raise an Error.

E. g: - IndentationError, TabError

Runtime Error

It allow to start the execution process but doesn’t stop the execution process normally. It stop abnormally then that process is
called as runtime error. Each runtime error is called as exception. Invalid input is responsible.

E. g: - NameError, valueError, KeyError

What is exception handling?

It is an alternate way to achieve / complete the given task. To complete / achieve the task we used some terms: try, except,
else, finally.

Exceptions are two types:

• Predefine exception
• User define exception

But for all predefine exception are derived from parent exception class.

List of predefine exception

Syntax to handle exception


try:

risk code/logic/input

except:

alternet key

else:

success code

finally:

final message

50 | P a g e
Types

1. SyntaxError: no block will be execute


2. Success code: else -> finally -> normal termination
3. Exception without handle: try -> finally -> abnormal termination
4. Exception with handle: try -> except -> finally -> normal termination

➢ NOTE: - else BLOCK IS OPTIONAL.

Example

User define exception / custom exception

We can define a custom exception by creating a new class from the derived built in exception parent class. To define user
define Exception we used raise keyword.

Syntax:

Class CustomException (Exception):

Pass

try:

------

except CustomException:

-------

Example

51 | P a g e
File handling
Each program allocates memory inside RAM segment when process will start but at the end of process which memory
allocate that memory is also deallocate.

To store any data we used variable. Inside variable if we store any data that can’t be reused, to reused that data we store that
data in secondary storage device permanently.

Files are two types:

➢ Text file: which file can be read and write by user. E.g.: pdf, xls, ppt,all programming files
➢ Binary file: Which file can’t be read and write by user but understand by user is called binary file. E.g.: video, audio

Types of all operation

• Read
• Write
• Update (read & write)

Before any operation we must open a file and after operation we must close that file.

Syntax to open a file:

• objectname = open(“filename”, “mode”)


• withopen(“filename”, “mode”) as objectname

Syntax to close a file

[Link] ()

Types of mode:

• Text File Modes


Mode Description

'r' Read-only mode (default). File must exist.

'w' Write mode. Creates a new file or overwrites if it exists.

'a' Append mode. Creates a file if it doesn't exist; writes at the end.

'x' Exclusive creation. Fails if the file already exists.

• Text + Read/Write Combined Modes


Mode Description

'r+' Read and write. File must exist.

'w+' Write and read. Overwrites file if it exists, creates new otherwise.

'a+' Append and read. Creates a file if it doesn't exist.

'x+' Create and read/write. Fails if file exists.

52 | P a g e
✅ Binary File Modes (Add 'b' to any of the above)
Mode Description

'rb' Read binary file.

'wb' Write binary file. Overwrites if exists.

'ab' Append in binary file.

'xb' Exclusive binary write. Fails if file exists.

'rb+' Read and write in binary file.

'wb+' Write and read in binary file.

'ab+' Append and read in binary file.

'xb+' Create binary file and read/write.

Example

For read operation

• read(): read string data from file up to end of file.


• readline(): read only one line data from line.
• read(n): read string data from file up to ‘n’ numbers of character.
• readlines(): read all string data in a list format up to end of file.

53 | P a g e
Example

For write operation

• write(): write data into a file (string).


• writelines(): write data in list format into a file.

Example

How to get file pointer position and how to set file pointer position

• tell(): it return file current pointer position.


• seek(pointer position): it set file pointer position.

Example

54 | P a g e
Binary file operation

CSV file (comma separated value)

In general we can make csv file in two ways:

• using notepad
• using excel

But by using programming language we make csv file or to work with csv file we used csv modules.

read operation: reader()

write operation(): writer()

Example

Difference between write and append mode

Feature 'w' (Write Mode) 'a' (Append Mode)


File creation Creates a new file if it doesn't exist Creates a new file if it doesn't exist
File existence Overwrites the existing file Keeps the existing content
Existing data Deleted Preserved
Writing starts at Beginning of the file End of the file
Pointer movement Moves to start before writing Moves to end before writing
Common usage For starting fresh with new data For adding logs, updates, or history
Risk of data loss Yes – overwrites all existing data No – appends without removing old content

55 | P a g e
Zip file

To work with zip file we work with zip file.

Operation with zip file

1. Creating a zip file

2. Adding Files in Append Mode

3. Extracting ZIP File

4. Reading Contents of a ZIP File

5. Creating a ZIP from a Folder (using shutil)

56 | P a g e
advance Python

Table of contents
Chapter 1

Module and Packages ………………………………………………………………. 58

Chapter 2

OOPS concept ………………………………………………………………. 61

57 | P a g e
Module and Package
Module

Any program save by using .py is called as module. Inside module who will present is known as attribute of that module.
Attribute can be any variable, any constant, any function or class.

By using module we can access one program attribute on another program. When we work with module it create link
between different program to module (_pyche_).

dir(module name): is used to get all attribute lies from module.

help(module name): is used to get manual about module.

Inside module only we can define any variable, function, method or class. But not access these attributes.

Modules are three types:

• Built-in module
• User-define module
• External module

Package

Multiple modules present in a single folder is called as package and inside package also we can write sub package.

❖ NOTE: MODULENAME AND PROGRAM AND PACKAGE NAME SHOULD NOT BE SAME.

Syntax: (how to get import module / how to access attribute using module)

Import modulename

[Link]

Syntax: (how to rename module)

Import modulename new name

[Link] ()

Syntax: (how to import attribute from module)

From modulename import attribute1, attribute2…….

attribute1

Syntax: (how to rename attribute)

From modulename import attribute1 as newname1, attribute2 as newname2…..

newname1

Syntax: (how to import all attribute from module)

From modulename import*

Attributename

58 | P a g e
User-define module

Creation of module

Using this module

Built-in module

In python built-in module are modules that are automatically installed and available as part of the python standard library.
You can use them without needing to install any external packages. They are written in c for performance and provide
standard functionality, such as file handling, math operation, system functions, and more.

Example of built-in function

Module Purpose
math Mathematical operation
sys Access to system-specific parameters
os Interact with the operating system
datetime Work with dates and times
random Generate random numbers
json Handle JSON data
re Regular expression
time Time-related function

Example

59 | P a g e
External module

An external module is a module or package that is not included In the python standard library. These must be installed
separately. Usually using a tool like pip.

Example of External module

Module Purpose
numpy Numerical computations and arrays.
pandas Data analysis and manipulation
matplotlib Data visualization(plots,graphs etc.)
requests Send HTTP requestes(API communication)
flask Web development framework
django High-level web framework
pygame Game development
Opencv-python Image and video processing

How to install module using pip

Open cmd >> type” pip install modulename”

Example

Example using numpy

How to see all installed modules

Open cmd >>> type ”pip list”

60 | P a g e
Oops(object oriented programming system)
Object-Oriented Programming (OOP) is a method of programming where software is designed using classes and
objects. It helps in organizing code by grouping related data and behaviour.

Key Goals of OOP:

• Structure the code better for reusability

• Make the code modular, maintainable, and scalable

• Reflect real-world entities in programming

Class: In python everything is an object. So to make or create any object we make some plans or blueprint or model is
nothing called as class.

• Class is a user defines data types.


• Class is collection of both attribute and behaviour. All attribute can be represent by variable and all behaviour can be
represent by methods (function).
• So, class is collection of both variables and methods (function).
• Class keyword is used to define any class.

Syntax to make empty class:

class classname:

‘’’doc string’’’

pass

Syntax to make empty class:

class classname:

‘’’doc string’’’

Attribute list

Behaviour list

What is doc string in python?

doc means document string. It describe details about the class. It is a optional but better use.

• To get doc string details we used:


Print (classname.__doc__)
• To get details about class we used:
help(classname)

Example

61 | P a g e
Object Object is nothing is variable of class type .

• object is used to represent the class.


• Object is used to access both attribute and behaviour of class.
• For a class we can create N number of object.

❖ NOTE: Object is also known as reference variable.

Difference between class and object:

Class allocates one time memory whereas objects allocate n times memory.

Example

self It means current instance / object of class.

self is used in 2 different way:

➢ Inside instance method: Self is a default parameter in instance method.


➢ Inside constructor: Self is default parameter inside a constructor.

62 | P a g e
Example

Encapsulation – “Data Hiding”

Encapsulation means bundling data and methods that operate on that data within one unit (i.e., class) and restricting access
to some components.

Private members: Use double underscore __ to declare a variable or method private.

Example

Benefits:

• Improves security

• Prevents accidental modification

• Encapsulation with getters and setters’ controls access

Abstraction – “Hide the Complexity”

Abstraction means showing only essential details and hiding the internal implementation.

Benefits:

• Focus on what object does, not how

• Encourages modular design

• Easier to maintain and modify code

63 | P a g e
Inheritance – “Reusability”

Inheritance allows a class (child) to inherit properties and methods from another class (parent).

Types:

• Single Inheritance

• Multilevel Inheritance

• Multiple Inheritance

• Hierarchical Inheritance

➔ Single Inheritance: One child class inherits from one parent class

➔ Multilevel Inheritance: One class inherits from another child class, forming a chain

➔ Multiple Inheritance: One class inherits from more than one parent class

64 | P a g e
➔ Hierarchical Inheritance: Multiple child classes inherit from a single parent class

➔ Hybrid Inheritance: Combination of more than one type of inheritance

Polymorphism – “One Name, Many Forms”

Polymorphism means the same function/method behaves differently for different classes or objects.

Types:

• Compile-time Polymorphism (Method Overloading) – Not directly supported in Python but simulated. Compile-time
polymorphism allows multiple methods in the same class to have the same name but different number or type of
parameters.

• Run-time Polymorphism (Method Overriding) – Supported using inheritance. If the child class has a method with the
same name and parameters as in the parent class, the child's method overrides the parent's method.

Example (Method Overloading):

65 | P a g e
Example (Method Overriding):

Constructor and Destructor

Constructor: – __init__()

• Automatically called when object is created.

• Used to initialize instance variables.

Destructor: – __del__()

• Called when object is deleted or goes out of scope.

self, cls, and Method Types

self

Refers to the current object (instance).

cls

Refers to the current class. Used in class methods.

Types of Methods:

Type Decorator Purpose

Instance Method None Access instance variables

Class Method @classmethod Access class variables

Static Method @staticmethod General utility method

66 | P a g e
Real-Life Analogy Summary

Concept Real-Life Example


Class Blueprint of a building

Object Actual building made from blueprint

Encapsulation Medicine capsule hiding internal contents

Abstraction TV remote hiding internal circuits

Inheritance Child inherits traits from parents

Polymorphism “Draw()” works differently for circle, rectangle, etc.

Advantages of OOPS :

1. Modularity

• Code is organized into separate classes.

• Each class handles its own logic, making the program cleaner and easier to manage.

2. Code Reusability

• Inheritance allows new classes to reuse methods and attributes from existing classes, reducing repetition.

3. Data Security (Encapsulation)

• Private data is protected using access modifiers.

• Access is controlled through getter and setter methods.

4. Real-World Mapping

• Classes and objects represent real-world entities, making the code more intuitive and easier to understand.

5. Polymorphism

• One method or function behaves differently depending on the object.

• Makes the code more flexible and extendable.

67 | P a g e
“Learning never exhausts the mind.”

Stay curious. Stay consistent. Keep building amazing things with Python!

You

68 | P a g e

You might also like