Introduction to Python
What is Python?
High-level, interpreted, general-purpose programming language.
Created by Guido van Rossum in 1991.
Known for readable syntax, large standard library, and versatility.
Key Features:
Interpreted – No compilation needed; code runs line-by-line.
Dynamically typed – Variable types are decided at runtime.
Cross-platform – Works on Windows, macOS, Linux.
Extensive Libraries – For web, AI, data science, automation, etc.
Open-source – Free to use and modify.
Getting started with Python:
Python is one of the most popular programming languages
in the world now a days.
Any type of application can be developed by python.
- Standalone application
- Web based application
- Mobile applications
- Games etc.
Python is preferred in the emerging areas like
Data
Science, Machine Learning, Artificial Intelligence
IOT (Internet Of Things) etc.
History Of Python:
Python was developed by Guido van Rossum in early 90’s at National Research Institute for Mathematics and Computer Science (Netherland). The first version of Python which is Python 1.0 was released in the year 1991. *Python 2.0 was released in 2000. Python 2.7 which is still used today will be supported until 2020. But there will be no Python 2.8. So Python 3 is the future. Currently, Python version 3.8 is available. The source code of python is available under the GNU general public license.
Why the name Python?
Guido van Rossum was a great fan of the famous actor Monty Python from the TV show Monty Python’s flying circus. According to his name, Guido named the language as Python. So don’t be confused. Python is no way related to snakes.
Features
of Python
- Simple
- Very high level
- Open source
- Dynamically typed
- Platform independent
- Procedure and object oriented
- Multithreaded
- Huge third party library
A
small comparison
|
C |
C++ |
Java |
Python |
|
Developed by Dennis Ritchie |
BjarneStroustrup |
James Gosling |
Guido Van Rossum |
|
1972 |
1980 |
1991 |
1991 |
|
POP |
OOP |
OOP |
POP and OOP |
|
Compiler |
Compiler |
Compiler and interpreter |
Interpreter(Internally compiled) |
|
Static Typing |
Static Typing |
Static Typing |
Dynamic Typing |
|
High level language |
High level language |
High level language |
Very High level language |
|
Not platform independent |
Not platform independent |
platform independent |
platform independent |
Installing
Python
- Go to www.python.org.
- Download the latest version (currently 3.8) according to your system specification (32 bit or 64 bit)
- Install the downloaded file on your system.
You can also download other versions like 3.6 or 3.7 or 3.8 series. But don’t go for python
2.X version.
Different
Ways to run python Program
- Interactive mode /python interpreter mode
- Script mode
- IDLE (Integrated Development Environment)
Writing
Your First python program
- Open python IDLE
- Create a new file
- Write a program
- Save the program as filename.py
- Run the program to get the out put
We can also use
some popular 3rd party
ides to develop python programs. Some popular ides are
- Jupyter Notebook
- Spyder
- pycharm
- Notepad++
- Emacs
Identifier
An identifier is the name given to a variable, function, class, module, or any other object in Python. It is how you identify something in your code so you can reference it later.Names assigned to variables, functions, classes etc known as identifier
- It can be a combination of alphabets, digits and only one special symbol underscore ( _ ).
- It must start with an alphabet or underscore.
- It should not be a keyword and It can be of any length.
- Python is case sensitive programming language. i.e. Age and age are 2 different identifiers.
- Use snake_case for variables and functions:
- Use PascalCase for classes:
- Use UPPER_CASE for constants:
Variable:
A variable is a memory location where some value can be stored. A variable is a named storage location in a program used to hold data.
It acts as a reference to a value stored in memory, allowing us to store, retrieve, and manipulate information in our code.
How Variables Work in Python
The variable name points (references) to that value.
Variables don’t store the value directly; they store a reference to the object.
Keywords
Reserved words having some specific meaning .Different version have
different keywords. Python 3.7.1 has 35 keywords.
>>> import keyword
>>>print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with',
'yield']
Statements
and comments
A statement is an instruction that can be understood by python
interpreter.
In simple terms:
A statement tells Python to do something.
Types of Statements in Python
- Assignment Statements Used to assign a value to a variable.
- Conditional Statements Used to make decisions based on conditions.
- Looping Statements Used to repeat a block of code.
- Import Statements Used to include external Python modules.
- Function Definition Statements Used to define functions.
- Class Definition Statements Used to define classes.
- Pass Statement
|
Multiline statements: X=10+20+30+\ 40+50+60
|
Assigning values to multiple variables X, Y, Z=10,
20, 30
|
Multiple statements in a single line: a=10 ; b=20 ;
c=a+b ; print(c)
|
Comments:
Comments are used to document a program or make a program more understandable. Statements inside comment lines will be ignored by the interpreter.
Why Use Comments?
- Explain code logic for others (and your future self).
- Make programs easier to maintain.
- Temporarily disable code during testing/debugging.
|
Single
comment line ( # ) # This is a single line comment |
Multi comment line (use triple single or double quotation) |
|
|
"""This
is an example of multi-line comments""" |
'''This is an example of multi-line comments''' |
|
Indentation
Indentation means adding spaces or tabs at the beginning of a line of code to define its block structure. In Python, indentation is not optional — it’s a core part of the syntax and determines which statements belong together.
In simple terms:
Indentation in Python tells the interpreter which lines of code are part of the same group.
Why Indentation is Important in Python
- Many programming languages (like C, Java) use braces { } to mark code blocks.
- Python uses indentation instead — this makes code more readable but also mandatory.
- If indentation is incorrect, Python will throw an IndentationError.
Indentation Rules
- All statements in the same block must have the same indentation.
- Indentation can be spaces or tabs (PEP 8 recommends 4 spaces).
- Mixing spaces and tabs is not allowed (can cause errors).
- The indentation level defines nested blocks.
C, C++ and Java uses curly brackets to define a block. But python uses
indentation to define a block.
|
C/C++/Java |
Python |
|
if (a>b) { Printf(“a is
greater”); Printf(”if
block”); } else { Printf(“b is
greater”); Printf(“else
block”); } |
if a>b: print("a is greater") print("if block") else: print("b is greater") print("else block") |
Static
typing vs dynamic typing
No need to use data type before
variable name to define a variable. According to value data type is determined.
>>>a,b,c=10,5.3,"Ganesh"
>>>print(type(a),type(b),type(c))
<class 'int'>, <class
'float'> ,<class 'str'>
What is Input and Output?
Input( ) → Getting data from the user or an external source into the program. input () function is used to take input from keyboard .
Output( ) → Sending data from the program to the user or an external destination (like a file or screen). print () function is used to display output .
In simple terms:
Input is how your program “hears” you.
Output is how your program “speaks” back to you.
Input in Python
input() Function
Used to take user input from the keyboard.
Always returns a string, so you may need to convert it to another type.
Example:
name = input("Enter your name: ")
print("Hello,", name)
Example with Type Conversion:
age = int(input("Enter your age: "))
print("You will be", age + 1, "next year")
Output in Python
print() Function
Used to display output to the screen.
Can print multiple values, separated by commas.
Example:
print("Hello, World!")
Example with Multiple Values:
name = "Shree"
age = 21
print("Name:", name, "Age:", age)
1.
Write a program to add 2 numbers without giving input from keyboard
|
a,b=10,20 c=a+b print("sum is",c) |
Output sum is 30 |
2.Write a program to add 2 numbers by giving input
from keyboard.
|
a=input("Enter first number") b=input("Enter second number") c=a+b print("sum is",c) |
Output Enter first number10 Enter second number20 sum is 1020 Here the output is 1020 instead of 30 because input() function takes the input as strings. Hence to get
the right output convert string to integer. |
|
a=int(input("Enter first number")) b=int(input("Enter second number")) c=a+b print("sum is",c) |
Output: Enter first number10 Enter second number20 sum is 30 |
Formatting Output
String Formatting with f-strings (Recommended)
name = "Shree"
score = 95
print(f"{name} scored {score} marks")
Using .format()
print("{} scored {} marks".format(name, score))
Old-style formatting
print("%s scored %d marks" % (name, score))
Input & Output Together
# Taking input
name = input("Enter your name: ")
age = int(input("Enter your age: "))
# Producing output
print(f"Hello {name}, you are {age} years old.")
Data Types:
A data type defines the kind of value a variable can store and what operations can be performed on it.
In simple terms: Data type tells Python “what kind of data is this?” — like numbers, text, lists, etc.
Data type refers to the type of data stored in memory or variable. Every value in Python has a data type. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.
Python has following data types.
- Number / Numeric Type (int, float, complex)
- Boolean
- Sequence Type (String, List, Tuple, Range)
- Dictionary
- Set
int → Integer numbersfloat → Decimal (floating-point) numberscomplex → Complex numbers (real + imaginary part)
a = 10b = -5c = 0print(type(a)) # <class 'int'>
x = 3.14y = -0.5z = 2e3 # 2000.0 (scientific notation)print(type(x)) # <class 'float'>
num = 2 + 3jprint(num.real) # 2.0print(num.imag) # 3.0print(type(num)) # <class 'complex'>
a = 5 # intb = float(a) # int → floatc = complex(a) # int → complex
abs(-7) # 7pow(2, 3) # 8round(3.1416, 2) # 3.14
# Working with numeric typesx = 10 # inty = 3.5 # floatz = 2 + 4j # complexprint("Sum:", x + y)print("Multiply:", x * y)print("Complex addition:", z + (1 + 2j))
Sum: 13.5Multiply: 35.0Complex addition: (3+6j)
Number :
|
A number can be of 3 types ·
integer ·
float ·
complex number
|
>>> a=10 >>> type (a) <class 'int'> >>> b=5.3 >>> type(b) <class 'float'> >>> c=5+3j >>> type(c) <class 'complex'> |
String:
String
is a sequence of Unicode characters. We can use single quotes or double quotes
to represent strings. Multi-line strings can be represented using triple
quotes, ' ' 'or " " ".
|
>>>
name = "Ganesh" >>>
type(name) <class
'str'> >>>name=’Ganesh’ >>>
type(name) <class
'str'>
|
>>>
name = ' ' ' Das' ' ' >>>name=”
” ” Das” ” ” >>>name ‘Ganesh\nDas’ >>>print(name) Ganesh Das
|
Accessing string elements:
- Indexing ( [ ] )
- Slicing ( [ : : ] )
|
H |
e |
l |
l |
o |
|
Indexing |
Slicing |
|
>>> s="hello" >>> s[0] 'h' >>> s='hello' >>> s[0] 'h' >>> s[-1] 'o' >>> s[10] Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
s[10] IndexError: string index out of range |
[start: stop : step] Default step is 1. >>> s='hello' >>> s [0 : 4] 'hell' >>> s [1 : 5 : 2] 'el' >>> s [ -5 : -1 ] 'hell' >>> s [ : : 2] 'hlo' >>> s [ 4 : : -1] 'olleh' |
Strings are immutable. We can’t make any
modification on the existing string object.
>>> s="hello"
>>>s[0]='y'
TypeError: 'str' object does not support item
assignment
The plus ( + ) sign is used as concatenation operator, and the
asterisk ( * ) is the repetition operator. For example:
>>> "hello"+"world"
'helloworld'
>>> "hello"*2
'hellohello'
List :
A list is a collection of elements separated by commas and enclosed within square
brackets ([] ).
>>> L1=[10,20,30,40,50]#list with homogeneous elements
>>>type(L1)
<class 'list'>
>>>L2=[ ] #Empty list
>>>L3=[10,5.3,'Ganesh'] #heterogeneous list
>>>L4=[10,20,30,[40,50]]
#nested list
Accession list
elements
List elements can
be accessed by index or slicing operator ([ ] and [ : : ]).Index starts from 0.
|
Indexing |
slicing |
|
>>> L=[10,20,30,40,50] >>>
L[1] 20 >>>
L[-1] 50 >>>
L=[10,20,[30,40]] >>>
L[2][0] 30 |
L=[10,20,30,40,50] >>>
L[1:5:1] [20, 30, 40,
50] >>>
L[1:5:2] [20, 40] >>>
L[4:1:-1] [50, 40, 30] |
The plus ( + ) sign is the list concatenation operator, and the
asterisk ( * ) is the repetition operator. For example:
|
>>>
a=[10,20] >>>
b=[30,40] >>>a+b [10, 20, 30,
40]
|
>>>
L=[10,20] >>>
L*5 [10, 20, 10,
20, 10, 20, 10, 20, 10, 20]
|
Lists are mutable .i.e. the elements of list can be modified.
For Example
>>> L=
[10, 20, 30]
>>> L
[2] =100
>>> L
[10, 20, 100]
List methods :
Method | Description |
append(item) | Add an item at end of list |
extend(sequence) | Add all the elements of a sequence to list |
clear() | Makes a list empty |
Index(item) | Returns index of first occurrence of an item |
Count(item) | Return the no of times an item is present in list |
copy() | Creates a shallow copy of a list |
insert(i, item) | Insert an item at index i |
pop() | Removes an element from last |
pop(index) | Removes an element from a specific index |
reverse() | Reverse a list |
sort() | Arranges element in ascending or descending order |
remove(item) | Removes the first occurrence of an element |
Functions used with list
Function | Meaning |
len() | Find length of a string |
sum() | Find sum of all element of list |
max() | Find largest element in list |
min() | Find smallest element in list |
any() | Return True if any on element is True |
all() | Return True if all elements are True |
List Comprehension:
Creating a list from another sequence called as list comprehension. For list comprehension we need a for in loop and square bracket.
>>> y = [2 ** x for x in range(5)]
>>>y
[1, 2, 4, 8, 16,]
We can add conditions in list comprehension .
[**64, 128, 256, 512]
>>> y = [x for x in range(10) if x % 2 == 0]
>>>y
[0, 2, 4, 6, 8]
Matrix operations using list:
A nested list can be used to represent a matrix
Tuple:
Tuple is a sequence of elements same as list with difference is that tuples are immutable. Tuples once created cannot be modified (no adding, removing, or modifying elements). Tuples are read-only. Tuple is defined within parentheses () where items are separated by commas. Faster than lists because of immutability.
|
>>> t1=(10,20,30,40) # tuple with
homogeneous elements >>> type(t1) <class 'tuple'> >>> t2=(
) #empty tuple >>> t3=(10,5.3,"hello") #heterogeneous tuple >>> t4=(10,20,(30,40,50)) #Nested tuple # Single-element tuple (must have a comma) single = (5,) # Correct not_tuple = (5) # Just an integer |
>>> t=10,20,30,40,50 #This is a tuple >>> t (10, 20, 30, 40, 50) >>> type(t) <class 'tuple'> >>> t=(10) # Not a tuple >>> t 10 >>> type(t) <class
'int'> |
Accessing tuple elements:
Same as list. indexing and slicing.
Modifying a tuple will produce error.
Hence tuples are immutable
>>> t=(10,20,30,40)
>>>t[0]=100
TypeError: 'tuple' object does not support item assignment
The plus ( + ) operator is used for concatenating tuple and the asterisk ( * ) is the repeating a tuple .
| Operation | Example | Result |
|---|---|---|
| Concatenation | (1,2) + (3,4) |
(1, 2, 3, 4) |
| Repetition | ("A",) * 3 |
('A', 'A', 'A') |
| Membership | 2 in (1,2,3) |
True |
| Length | len((1,2,3)) |
3 |
Why Use Tuples?
Safety → Data cannot be changed accidentally.
Performance → Tuples are faster than lists for fixed data.
Hashable → Tuples can be used as dictionary keys (if all elements are immutable).
Built-in Functions with Tuple
Function | Meaning |
len() | returns length of a tuple |
sum() | Returns sum of all elements of tuple |
max() | returns largest element in a tuple |
min() | Returns smallest element in a tuple. |
any() | Returns true if any element is true . |
all() | Returns true if all elements are true. |
Sorted | Return a sorted list. |
enumerate() | Return an enumerate object. It contains the index and value of all the items of tuple as pairs. |
Dictionary:
Dictionary is a collection of elements where each element is stored as key and value pair. A dictionary defined within braces {} with each item being a pair in the form key: value.
A dictionary in Python is:
- An unordered, mutable collection of key–value pairs.
- Keys must be unique and immutable (e.g., strings, numbers, tuples with immutable elements).
- Values can be of any type.
- A dictionary is mutable but keys are imutable.
Think of a dictionary like a real-life dictionary — a word (key) maps to its meaning (value).
|
Creating dictionary d1={101:'Ganesh',105:'Satya',202:'Jyoti'} >>>
type(d1) <class
'dict'> >>>
d2={} #Empty dictionary >>>
d3={10:'hello','python':5.3} # Using dict() constructor person = dict(name="Bob", age=25) |
Accessing dictionary elements Use keys to
access values >>>
d1[ 101 ] 'Ganesh' >>>
d3['python'] 5.3 print(d1.get("python")) # 5.3 (safe access) |
Using .get() is safer — it returns None instead of an error if the key does not exist.
>>>
d={1:10,2:20}
>>>d[3]=30
>>>d
{1: 10, 2: 20, 3:
30}
| Operation | Example | Result |
|---|---|---|
| Length | len(student) |
Number of key-value pairs |
| Keys | student.keys() |
List of keys |
| Values | student.values() |
List of values |
| Items | student.items() |
List of (key, value) pairs |
| Membership | "name" in student |
True |
# Store country capitals
capitals = {
"India": "New Delhi",
"Japan": "Tokyo",
"France": "Paris"
}
country = input("Enter a country: ")
print("Capital:", capitals.get(country, "Not found"))
**A dictionary is mutable. But keys are immutable
>>> d={1:10,2:20}
>>>d[3]=30
>>>d
{1: 10, 2: 20, 3: 30}
Dictionary methods:
Method | Meaning |
Clear() | Makes a dictionary empty |
Copy() | Creates a shallow copy of a dictionary |
Fromkeys() | Creates a dictionary from a sequency of keys |
Get() | Returns value if key is present |
Values() | Returns values of a dictionary |
Keys() | Returns keys of a dictionary |
Items() | Returns key value pair |
Pop() | Deletes an element if key is present |
Popitem() | Remove an element arbitrarily |
Setdefault() | Returns value if key is present otherwise add the key with None value . |
Update() | Updates a dictionary from another dictionary |
Dictionary Comprehension:
We can create a dictionary from a sequence. For that we need curly brackets and for in loop .
Example:
D={x :chr(x) for x in [65,66,67,68]}
Print( D )
Output:
{65:’A’,66:’B’,67:’C’,68:’D’}
Set
:
Set is an unordered collection of elements where duplicates
are not allowed. Set is defined by values separated by comma inside curly
braces { }.
>>> S= {10, 20, 30, 20, 20,
30}
>>> S
{10, 20, 30}
>>>type(S)
<class 'set'>
We can perform set operations like
union, intersection on two sets. Set have unique values. .Indexing and slicing
operator does not work with set.
>>>10 in [10,20,30,40] #Membership Test
True
|
>>>
s= {10, 20, 30} >>>
s[1] Type Error:
'set' object does not support indexing ** Set is mutable. >>> S={10,20,30} >>>S.add(40) >>> S {40, 10, 20, 30}
|
>>> A ={10,20,30,40} >>> B={30,40,50,60} >>>A | B #A union B {40, 10, 50, 20, 60, 30} >>>A & B # A intersection B {40, 30} >>> A – B #A difference B {10,20} >>>A ^ B #A symmetric difference B {10, 50, 20, 60} |
Set method:
Method | Meaning |
add | Add an element to set |
clear() | Makes a set empty |
Copy() | Creates a shallow copy |
discard() | Deletes an element from a set |
Remove() | Deletes an element from a set |
Pop() | Deletes an element randomly from a set |
union() | Find union of 2 sets. |
update() | Finds union and updates |
Intersection() | Find intersection of 2 sets |
Intersection_update() | Finds intersection and updates |
difference() | Find difference between sets |
difference_update() | Finds difference and upodates |
symmetric_difference() | Finds symmetric difference between 2 sets |
Symmetric_difference_update() | Finds symmetric difference between 2 sets and updates . |
Issuperset() | Checks a set is super set of another set or not |
Issubset() | Checks a set is sub set of another set or not |
Isdisjoint() | Returns True if both the sets have no common element |
Set comprehension:
We can create a set from another sequence .For that we need a curly brackets and for in loop.
S={ x for x in [10,20,10,10]} Print(S) | Output: {10,20} |
Operators
Operator is an
symbol which performs some operation on operands.
·
Arithmetic
Operators
·
Relational Operators
·
Assignment
Operators
·
Logical
Operators
·
Bitwise
Operators
·
Membership
Operators
·
Identity Operators
Arithmetic operators:
Arithmetic operators are used to perform
mathematical operations like addition, subtraction, multiplication, division
etc.
|
Operator |
Meaning |
A = 10 and B= 4 |
Result |
|
+ |
Addition |
A+B |
14 |
|
- |
Subtraction |
A-B |
4 |
|
* |
Multipication |
A * B |
40 |
|
/ |
Division |
A / B |
2.5 |
|
% |
Modulus |
A % B |
2 |
|
// |
Floor division |
A // B |
2 |
|
** |
Power |
A ** B |
10000 |
Priority:
** has
highest priority
/ *
// % has next highest priority
+ - have
lowest priority
Relational
operator:
Relational
operators are used for comparison. Result is
a Booleanvalue.
|
operator |
Meaning |
x=10 and y=15 |
Result |
|
< |
Less
than |
x < y |
True |
|
> |
Greater
than |
x
> y |
False |
|
<= |
Less
than or equal to |
x
<= y |
True |
|
>= |
Greater
than or equal to |
x
>= y |
False |
|
== |
Equal
to |
x
= = y |
False |
|
!= |
Not
equal to |
x
! = y |
True |
Assignment
Operators:
Assignment
operators are used in Python to assign values to variables.
a = 10
10 is assigned to a
Other forms of Assignment operator in
Python
+= , - = ,* = , / = , // = etc.
a += 10 is equivalent to a = a + 10.
Logical operators:
Logical
operators perform logical operations on operands. Result is Booleanvalue .
·
and
-------------logical AND
·
or ---------------logical OR
·
not
----------- logical NOT
|
A |
B |
A and B |
A or B |
|
T |
T |
T |
T |
|
T |
F |
F |
T |
|
F |
T |
F |
T |
|
F |
F |
F |
F |
|
A |
not A |
|
T |
F |
|
F |
T |
Bitwise Operators:
Bitwise operator works on bits and perform
bit-by-bit operation.
& bit wise AND
| bitwise OR
^ bitwise XOR
~ bitwise compliment
<<left
shift
>> Right shift
|
A |
B |
A & B |
A | B |
A ^B
|
|
0 |
0 |
0 |
0 |
0 |
|
0 |
1 |
0 |
1 |
1 |
|
1 |
0 |
0 |
1 |
1 |
|
1 |
1 |
1 |
1 |
0 |
|
A |
~A |
|
0 |
1 |
|
1 |
0 |
Find 5 & 3 5 | 3 5 ^ 3
5 = 00000101
5 & 3= 00000001
is 1
5 | 3 = 00000111
is 7
5 ^ 3 = 00000110
is 6
Representation of
negativenos:
Negative nos are represented
in 2’s compliment form
Represent -5
5 = 00000101
1’s compliment = 11111010
11111011 This is -5 in 2’s
Question
1:Find -5 & 3
-5 = 11111011
-5&3 = 00000011 which is equals to 3
Question 2:Find -5 | 3
-5 = 11111011
-5|3 = 11111011 it is a negative no as sign bit is 1
To get the value find 2’s
compliment keeping sign bit fixed
11111011
1’s 10000100
10000101
= -5
Question 3:Find ~ 5
5= 00000101
~5=11111010 is
a negative no so find 2’s
1’s=10000101
10000110
= -6
|
<< (Bitwise left shift) |
Shifts entire bit pattern towards left by specific number of
bits. |
5<< 2 |
20 |
|
>> (Bitwise Right shift) |
Shifts entire bit pattern towards right by specific number of
bits. |
5>>2 |
1 |
Membership operator:
Membership
operators are used to test membership in a sequence, such as strings, lists
,tuples, set and dictionary
·
in
·
not
in
Example:
|
>>>
name="Ganesh" >>>
'G' in name True
|
>>>L=[10,20,30,40,50] >>>10
not in L False |
Identity operators:
Identity operators are used to check weather both the operands
refers to same object or not.(i.e same memory location or not).Python provides
following identity operators.
·
is
·
is not
|
>>>a,b=10,10 >>> a
is b True
a is b will be True if id(a) == id(b) |
Python Operators Precedence:
Operator
|
Description
|
**
|
Power
(raise to the power)
|
~ + -
|
Complement,
unary plus and minus
|
* / %
//
|
Multiply,
divide, modulus and floor division
|
+ -
|
Addition
and subtraction
|
>><<
|
Bitwise
right and left shift operator
|
&
|
Bitwise
AND
|
^ |
|
Bitwise
exclusive `OR' and regular `OR'
|
<= >= , ==
!=
|
Comparison
operators
|
= %=
/= //= -= += *= **=
|
Assignment
operators
|
is , is not
|
Identity
operators
|
in ,
not in
|
Membership
operators
|
not
,or, and
|
Logical
operators
|
Control Structure
·
Sequential control structure
·
Decision control structure
·
Loop control structure
Sequential control structure:
All statements are
executed sequentially
Decision control structure:
According decision
some part of program will execute.
·
If
·
If-else
·
If-elif-else
·
Nested if-else
If statement:
|
Syntax:
if
condition: statements |
Example: num = int(input("Enter a
number: ")) if num> 0:
print("Positive number")
print(“inside if block”) print("This is always
printed")
|
output-1 Enter a number: 3 Positive number Inside if block This is always printed Output-2 Enter a number: -10 This is always printed
|
if – else :
Syntax
:
if condition:
Statements of if block else:
statements of else block |
Example: #Program to find
greater among 2 numbers a=int(input("Enter
the 1st number")) b=int(input("Enter
the second number")) if a>b: print("a is greater") print("I am inside if block") else: print("b is greater") print("I am inside else block")
|
output: Enter the 1st
number20 Enter the second
number10 a is greater I am inside if
block
|
If-elif-else:
Syntax:
if condition1: statement(s) elif condition2: statement(s) elif condition3: statement(s) . . elif condition n: statement(s) else: statement(s)
|
# In this program, we input a
number # check if the number is positive
or # negative or zero
num = int(input("Enter a
number: ")) if num> 0:
print("Positive number") elifnum == 0:
print("Zero") else:
print("Negative number")
|
Output
1: Enter a number: 2 Positive number Output
2: Enter a number: 0 Zero Output
3: Enter a number: -2 Negative number
|
Nested if statements:
We can have
aif...else statement inside another if...else
statement. This is called nested if…else statements.
|
Syntax: If
condition: If
condition: Statements else: Statements else: If
condition: Statements else
condition: statements
|
Example: # check a number is positive or # negative or zero by nested
if-else
num = int(input("Enter a
number: ")) if num>= 0:
if num == 0: print("Zero")
else: print("Positive number") else:
print("Negative number")
|
Output
1:
Enter a number: 5 Positive number
Output
2: Enter a number: -5 Negative number
Output
3: Enter a number: 0 Zero |
Loop control structure
Loop
is used to execute a statement or a number of statements for a specific no of times
according to a condition.
2 types of loop
·
while loop
·
for-in loop
while loop :
|
syntax : initialization while
condition : Statements Increment/decrement |
Example: i=1 while
i<=5: print('Ganesh') i=i+1 |
output: Ganesh Ganesh Ganesh Ganesh Ganesh |
# Write a program to find sum
of following series
1+2+3+4…………..+n
|
n=int(input("enter
value of n")) i=1 sum=0 while
i<=n: sum=sum+i i=i+1 print(sum) |
Output enter value of n 5 15 |
# write a program to find sum
of digits of a no
|
n=int(input('enter
a no')) sum=0 while
n!=0: r=n%10 sum=sum+r n=n//10 print(sum) |
Output enter ano123 6 |
While with else:
We can also use an else block with a while loop .The statements of else block will execute when the condition of while loop will become false.
|
Syntax: while
condition: Statements else: Statements |
Example : i=1 while
i<=5: print(i) i=i+1 else: print("loop over") |
output: 1 2 3 4 5 loop
over |
Nested while loop:
|
i=1 while
i<=3: j=1 while j<=2: print(i,',',j) j=j+1 i=i+1 |
Output: 1
, 1 1
, 2 2
, 1 2
, 2 3
, 1 3
, 2 |
Infinite loop
When
condition is never false the loop become a infinite loop
Example:
i=1
whilei<=5:
print('hello')
output:
hello
will be displayed infinite number of times
For in loop:
for
– in loop is used to iterate through a sequence. A sequence may be a list,
string, tuple, dictionary, range () function etc.
|
syntax: for
value in sequence: statements *
Here value refers to each element of sequence. |
Example 1: for
i in 'hello': print(i) output: |
Output-1 h e l l o |
|
Example 2: for
i in [10,20,30,40]: print(i ,end =' ') |
Output-2 10
20 30 40 |
range() function:
Used
to generate a sequence of numbers within a range .
Syntax:
range
(start,stop,step)
Example:
>>>list(range(5))
[0,
1, 2, 3, 4]
>>>list(range(10,20))
[10,
11, 12, 13, 14, 15, 16, 17, 18, 19]
>>>list(range(10,20,2))
[10,
12, 14, 16, 18]
|
#Write aprogram to find sum of following series 1+2+3…….+n sum=0 n=int(input('Enter
the range')) for
i in range (1,n+1 ): sum=sum+i print('sum
is',sum) |
output: Enter
the range5 sum
is 15 |
for in loop with else:
Like
while loop we also can use else block with for – in loop .The else block will
execute when iteration will be over.
|
Syntax: for
value in sequence: statements else: statements |
Example: #program
to check a number is prime or not n=int(input("enter a number")) for
i in range(2,n): if n % i==0: print(n,"is not prime") break else: print(n,"is prime") |
Output 1: enter
a number 5 5
is prime Output 2: enter
a number 4 4
is not prime |
Nested loop
Loop
with in another loop called as nested loop
|
Exapmle : for
i in range(1,6): for j in range(i): print('*' ,end=' ') print() |
output: *
*
* *
* * *
* * * *
* * * * |
Infinite loop
When
condition is never false the loop become a infinite loop
Example:
i=1
whilei<=5:
print('hello')
output:
hello
will be displayed infinite number of times
break:
break
keyword is used to terminate a loop. It can be used with while loop and for loop.
|
Example: for
i in [10,20,30,40,50] : if i==30: break print(i ,end=' ') |
output: 10 20 |
Continue:
Continue
keyword is used to take the control in to the loop. It is used to skip the rest
of the statements inside a loop for the current iteration only.
|
Example: for i in
[10,20,30,40,50] : if i==30: continue print(i ,end=' ') |
output: 10 20 40 50 |
Pass:
Pass is a
keyword. It is used to create an empty block.It is used when we want to make a
statement syntactically correct but does nothing.
Example:
|
Type of block |
Wrong |
Correct |
|
Empty
if block |
a,b=10,20 if
a> b : |
A,b=10,20 If a> b : pass |
|
Empty
for loop |
for i in range(5): |
for i in range(5): pass |
|
Empty
function |
def
add(a , b) : |
def
add(a , b) : pass |
|
Empty
class |
Class
Test : |
Class
Test : Pass |
Function:
·
A function is a
block of statements which performs a specific task.
·
Function provide
modularity for programming.
·
Once a function is
created it can be used again and again.
·
Program size is
reduced.
·
When program size
becomes larger functions are helpful for code maintenance.
·
We can add new
feature easily.
·
Code debugging is
easier by using function.
· The corresponding function can be modified without disturbing other functions.
2 types of function
a)
Built in function
Functions already defined.
Example:
print( )
input( )
len( )
max( )
etc
b)
User defined function
Functions defined by user.
How to create a function
Function
has 2 parts
a)Function definition
b) Function call
Function Definition:
Contains the logic
of function .
Syntax:
def function name(parameters):
'''docstring'''
Statements
Example:
def add(a,b):
'''This function add 2 numbers'''
c=a+b
print (“sum is ”,c)
Function call:
A function is executed when it
is called.
Syntax:
function name (parameters)
Example:
add (10,20)
return statement:
To return value from a function return
keyword is used
Example:
def calculate(a,b):
returna+b,a-b,a*b,a/b
a,b,c,d=calculate(10,5)
print(a,b,c,d)
output:
15 5 50 2.
Function parameters:
a) Required parameters
Here
the no of parameters in function definition and call must be same.
Example:
def add(a,b,c):
print(a+b+c)
add(10,20,30)#60
add(10,20)#Error
b) Default parameters
We can call a function with less no of arguments. But
for this we must give default values to parameter in function definition.
Default values must be given from right to left.
Example:
def add(a=1,b=2,c=3):
print(a+b+c)
add(10,20,30) #10+20+30
add(10,20) #10+20+3
add(10) #10+2+3
add( ) #1+2+3
c) Keyword parameters:
Here
the parameters are identified by their names.
Example:
def add(a=1,b=2,c=3):
print(a+b+c)
add(c=10,b=50,a=30)#30+50+10
add(b=10,a=20,c=30)#20+10+30
add(c=10)#1+2+10
d)variable length parameter:
When
a user does not know how many parameters to be passed to a function, we can use
variable length parameter in function definition. Use a * before the parameter
in function definition so that it will become a variable length parameter .A
variable length parameter stores data in a tuple.
|
Example: def show( a , *b): print('a
is',a,'and b is',b) show(10,20,30,40) show(100,200,300) |
output: a is 10 and b is (20, 30, 40) a is 100 and b is (200, 300) |
Local variable vs Global variable:
|
Local variable: When a variable is defined inside a function called
as local variable. It’s value is available inside the function only. Example: def show(): x=10 #local variable
print(x)#display 10 show() print(x)# Error as x is local |
Global variable: When a variable is defined above a function called
as global variable. Such variables are available to all the functions which
are defined after it. Example: x=10 #global variable def show():
print(x)#display 10 show() print(x)# 10 as x is global |
global keyword:
When
a local variable and global variable have same name, we can't access the global
variable inside the function. Butoutside the function it is accessible.
x=10 #global variable
def show():
x=20 #local
variable
print(x)#display 20 as it refers to local
show()
print(x)# 10 as it refers to global
**If
we want to use the global variable inside a function then use the keyword global
as follows.
Example:
x=10 #global variable
def show():
global x
x=20 #global
variable
print(x)#display 20 as it refers to global
show()
print(x)# 20 as it refers to global
Python supports call by value or call by reference:
Python supports
pass by object reference.
Example:
def show(L2):
print(L2 ,id(L2)) #[10, 20, 30, 40] 2260664305352
L2.append(50)
print(L2 ,id(L2)) #[10, 20, 30, 40, 50] 2260664305352
L1=[10,20,30,40]
print(L1,id(L1)) #[10, 20, 30, 40] 2260664305352
show(L1)
print(L1,id(L1)) #[10, 20, 30, 40, 50] 2260664305352
Main function:
In c,c++ and
java Program execution starts from main( ) function.But in python program
execution starts from beginning to end.We can explicitly use following concept
to show the main function.
def add(a,b):
print(a+b)
if __name__ =='__main__':
add(10,20)
__name__ is a special variable created internally when
a program is executed.
When a program is executed directly it stores the
value __main__ .and when a program is imported as a module to another program
it stores the module name.
Recursion:
When a function calls itself called as recursion.
|
#
Factorial of a number using recursion def fact(n):
"""This is a recursive function to find the
factorial of an integer""" if n == 1: return
1 else: return
(n *fact(n-1)) n = int(input("Enter a number: ")) f=fact(n) print("The
factorial of", n, "is", f) |
output: Enter a number: 5 The
factorial of 5 is 120 |
Anonymous Function
(lambda function):
A function defined without any name called as anonymous
function. While normal
functions are defined using the def keyword, in
Python anonymous functions are defined using the lambda
keyword. Hence, anonymous functions are also called lambda functions.
Syntax:
- arguments → input values
- expression → returned output (automatically returned, no return keyword needed)
square = lambda x: x * xprint(square(5))
- lambda → keyword to create an anonymous function
- x → input argument
- x * x → expression (what the function returns)
- The whole lambda function is assigned to the variable square
- Now square behaves like a normal function
- Calls the lambda function
- Passes 5 as x
- Calculates 5 * 5 = 25
- Output → 25
add = lambda a, b: a + bprint(add(10, 20))
def myfunc(n):return lambda a: a * nresult = myfunc(2)print(result(10))
hello = lambda : "Hello, World!"print(hello())
get_number = lambda : 100
print(get_number())
- A lambda function can have any number of parameters but only one expression.
- A lambda function can also have no parameter.
- A lambda function is a one line function.
- A lambda function does not need any return statement to return a value.
- A lambda function cannot access other variables except its own parameters.
- map()
- filter()
- sorted()
map(function, iterable)
- function → A function (normal or lambda) that is applied to each element
- iterable → List, tuple, set, dictionary, string, etc.
- A map object (which is an iterator)
- You must convert it to list/tuple to view results
numbers = [1, 2, 3, 4]result = map(lambda x: x * 2, numbers)print(list(result))
- Shorter and faster than loops
- Clean and elegant code
- Works well with lambda functions
- Ideal for data transformation
def square(n):return n * nnumbers = [1, 2, 3, 4]result = map(square, numbers)print(list(result))
a = [1, 2, 3]b = [4, 5, 6]result = map(lambda x, y: x + y, a, b)print(list(result))
filter(function, iterable)
- function → A function returning True or False
- iterable → List, tuple, set, string, etc.
- A filter object (iterator)
- Convert it into list/tuple to view results
- To extract only the elements that satisfy a given condition
- Used in data cleaning, filtering lists, removing unwanted values
- Works best with lambda functions
- Avoids writing loops for filtering
numbers = [1, 2, 3, 4, 5, 6]evens = filter(lambda x: x % 2 == 0, numbers)print(list(evens))
def check_even(n):return n % 2 == 0numbers = [10, 15, 20, 25, 30]result = filter(check_even, numbers)print(list(result))
names = ["Amit", "Rita", "Anil", "John"]result = list(filter(lambda x: x.startswith("A"), names))print(result)
- Numbers
- Strings
- Lists
- Tuples
- Sets
- Dictionaries (keys)
- Complex objects (like list of tuples, list of dictionaries)
sorted(iterable, key=None, reverse=False)
numbers = [5, 3, 8, 1, 2]result = sorted(numbers)print(result)
numbers = [10, 2, 8, 4]result = sorted(numbers, reverse=True)print(result)
words = ["banana", "apple", "cat", "dog"]print(sorted(words))
words = ["python", "go", "java", "c"]result = sorted(words, key=len)print(result)
File Handling
What is a File?
A file is a collection of related data stored on a storage device (like hard disk, SSD, or pen drive) under a specific name. A file is used to store data permanently on secondary storage devices.
- It is the smallest unit of storage for saving data permanently.
- Unlike variables (which store data temporarily in RAM), a file keeps data permanently, even after the program ends or the computer shuts down.
- Name – Each file has a unique name (e.g., data.txt, report.pdf).
- Extension – The suffix that defines file type (e.g., .txt, .jpg, .py).
- Path – Location of the file in the storage system (e.g., C:/Users/Student/sample.txt).
- Content – The actual data stored inside the file (text, numbers, images, audio, etc.).
- File Pointer – A cursor that keeps track of where the next read/write operation will happen.
- Store data in human-readable form (ASCII/Unicode).
- Data stored in text format or character format
- Examples: .txt, .csv, .py
- Content can be opened and read in text editors (Notepad, VS Code).
- Not human-readable – Data is stored as binary codes (machine-readable 0s and 1s).
- Compact and efficient – Stores raw data in a smaller size compared to text.
- File extensions – .bin, .jpg, .png, .mp3, .exe, .dat, .pdf.
- Used for structured data – Multimedia files, software executables, database storage.
# Write binary datadata = bytes([65, 66, 67, 68]) # Represents ABCDwith open("data.bin", "wb") as f:f.write(data)
# Read binary datawith open("data.bin", "rb") as f:content = f.read()print(content)
# Copy an image file using binary modewith open("image.jpg", "rb") as f1:data = f1.read()with open("copy.jpg", "wb") as f2:f2.write(data)
# Read large binary file in chunkswith open("video.mp4", "rb") as f:chunk = f.read(1024) # read 1024 byteswhile chunk:print(len(chunk), "bytes read")chunk = f.read(1024)
Difference Between Text File and Binary File
| Feature | Text File | Binary File |
|---|---|---|
| Storage Format | Human-readable characters | Binary (0s and 1s) |
| Example Extensions | .txt, .csv, .py | .jpg, .mp3, .exe |
| Size | Usually smaller | Usually larger |
| Readability | Can be opened in Notepad/VS Code | Cannot be read by normal editors |
| Example Usage | Config files, logs, source code | Images, videos, software files |
Basic file operations:
- Opening a file
- Reading a file
- Writing to a file
- Appending to a file
- Closing a file
Let’s explain each in detail.
file = open("filename", "mode")
|
Mode |
Meaning |
File
must exist? |
Overwrites? |
Cursor
Position |
|
'r' |
Read |
✔ Yes |
❌ No |
Start |
|
'w' |
Write |
❌ No |
✔ Yes |
Start |
|
'a' |
Append |
❌ No |
❌ No |
End |
|
'r+' |
Read + Write |
✔ Yes |
❌ No |
Start |
|
'w+' |
Write + Read |
❌ No |
✔ Yes |
Start |
|
'a+' |
Append + Read |
❌ No |
❌ No |
End |
|
'x' |
Create new |
❌ No |
❌ No |
Start |
|
'rb' |
Read binary |
✔ Yes |
❌ No |
Start |
|
'wb' |
Write binary |
❌ No |
✔ Yes |
Start |
|
'ab' |
Append binary |
❌ No |
❌ No |
End |
f = open("data.txt", "r")
- "data.txt" → file name
- "r" → open in read mode
f = open("notes.txt", "w")f.write("This is Python file handling example.\n")f.write("We are learning how to write files.")f.close()
- read() : Read all characters from file
- read(n) : Read n characters at a time from file .
- readline() : Read one line at a time .
- redlines() : Read all the lines from the file at a time and stores in a list .
f = open("info.txt", "r")content = f.read()print(content)f.close()
f = open("info.txt", "r")print(f.read(5)) # reads first 5 charactersf.close()
f = open("info.txt", "r")line1 = f.readline()line2 = f.readline()print(line1)print(line2)f.close()
f = open("info.txt", "r")lines = f.readlines()print(lines)f.close()
f = open("notes.txt", "a")f.write("\nThis line is added later.")f.close()
f.close()
- Saves data properly
- Frees memory
- Prevents file corruption
with open("sample.txt", "r") as f:data = f.read()print(data)
import osif os.path.exists("data.txt"):print("File exists")else:print("File not found")
import osos.remove("data.txt")
f = open("test.txt", "r")print(f.read(5)) # reads first 5 charactersprint(f.tell()) # prints cursor positionf.seek(0) # move cursor to startprint(f.read()) # read whole file againf.close()
File Handling
· name :returns name of file
1st way:
Use try...finally block.f =open("demo.txt")
# perform file operations
finally:
f.close()
2nd way:
Use with open. Here We don't need to explicitly call the close () method. It is done internally.
# perform file operations
Binary file:
A binary file is a file that stores data in binary format (0s and 1s), rather than plain text. Binary files are not human-readable because they store raw bytes, not characters.
- Images (.jpg, .png)
- Audio (.mp3, .wav)
- Video (.mp4, .avi)
- PDF documents (.pdf)
- Executable files (.exe, .bin)
|
Feature |
Text
File |
Binary
File |
|
Content |
Human-readable (ASCII/UTF-8) |
Machine-readable (bytes) |
|
File Mode |
'r', 'w', 'a' |
'rb', 'wb', 'ab' |
|
Data |
Strings |
Bytes |
|
Examples |
.txt, .csv, .py |
.jpg, .mp3, .pdf |
|
Mode |
Description |
|
'rb' |
Read binary |
|
'wb' |
Write binary (overwrite) |
|
'ab' |
Append binary |
|
'r+b' |
Read + write binary |
|
'w+b' |
Write + read binary |
Reading Binary Files
Binary files are read as bytes objects, not strings.Example: Read an image
with open("photo.jpg", "rb") as f:data is a bytes object
data = f.read()
print(type(data)) # <class 'bytes'>
print(len(data)) # Number of bytes
Cannot print as normal string; usually used for copying or processing
Writing Binary Files
You can write bytes to a binary file using 'wb' mode.Example: Create a copy of an image
with open("photo.jpg", "rb") as source:Copies exact content of original image
data = source.read()
with open("photo_copy.jpg", "wb") as dest:
dest.write(data)
Works with any binary data (audio, video, pdf, etc.)
Reading/Writing Bytes
You can read/write small chunks using:# Read 1024 bytes at a timeUseful for large files, avoids memory overload.
with open("video.mp4", "rb") as f:
chunk = f.read(1024)
while chunk:
# process chunk
chunk = f.read(1024)
Combining Text & Binary
Sometimes you need to write text in binary mode:text = "Hello World".encode() → string to bytes
with open("file.bin", "wb") as f:
f.write(text.encode()) # convert string to bytes
To read back:
with open("file.bin", "rb") as f:
data = f.read()
text = data.decode()
print(text)
.decode() → bytes to string
Practical Uses of Binary Files
- Images: Reading/writing images for programs
- Audio/Video: Media file manipulation
- Databases: Storing objects or binary data
- Machine Learning Models: Saving trained models (.pkl files)
- Networking: Sending/receiving raw data
Pickle module:
Pickle is a process of converting an object to byte stream so that it can be stored in a file. This is called as pickling or serialization. This is done by dump() method .
Pickle.dump(object , file)
Unpickle is a process of converting a byte stream to object.Unpickling also called as deserialization. This is done by load() method.
Pickle.load( file )
Example:
import pickle L=[10,20,30,40,50] f=open("D:/demo.dat",'wb') pickle.dump(L,f) f.close() f=open("D:/demo.dat",'rb') data=pickle.load(f) print(data) f.close() | OUTPUT:
[10, 20, 30, 40, 50] |
Modules
Module:
A module in Python is simply a file that contains Python code (functions, variables, and classes) which can be reused in other programs.
- It helps in organizing code.
- Promotes reusability (write once, use many times).
- Makes code modular and maintainable.
👉 Any Python file with the extension .py is considered a module.
Why Use Modules
- Avoids writing the same code again and again.
- Makes code clean, structured, and reusable.
- Provides access to built-in libraries (math, random, datetime, etc.).
- Allows us to create our own custom modules.
Types of Modules
(a) Predefined module / Built-in Modules (already provided by Python)
Modules already known to interpreter called as predefined module.
Examples:
- math → mathematical functions
- random → generate random numbers
- datetime → work with date and time
- os → operating system tasks
- sys → system-specific parameters
(b) User-defined Modules (created by programmers)
How to create a module:
How to access a module:
import mathprint(math.sqrt(16)) # 4.0
from math import sqrtprint(sqrt(25)) # 5.0
import math as mprint(m.factorial(5)) # 120
# mymodule.pydef greet(name):return f"Hello, {name}!"def add(a, b):return a + b
# main.pyimport mymoduleprint(mymodule.greet("Shree"))print("Sum:", mymodule.add(5, 3))
import mathprint(dir(math)) # shows all available functions inside math module
def greet(name):return f"Hello, {name}!"
def add(a, b):return a + b
# Import the packageimport mypackage# Use functions from modulesprint(mypackage.greet("Shree")) # Output: Hello, Shree!print(mypackage.add(5, 7)) # Output: 12
from mypackage import greet, addprint(greet("Jagannath")) # Hello, Jagannath!print(add(3, 4)) # 7
Regular Expressions
A Regular Expression (RegEx) is a pattern used to search, match, or manipulate text. Python provides a built-in re module for regular expressions:
import re
A regular expression is a sequence of symbols and characters that define a search pattern. RegEx is used for:
- Searching text
- Validating input
- Finding patterns
- Replacing text
- Splitting strings
|
Function |
Purpose |
|
re.search() |
Searches for a pattern anywhere in
the string |
|
re.match() |
Checks only at the beginning of
the string |
|
re.findall() |
Returns all matching patterns |
|
re.finditer() |
Returns iterator with match
objects |
|
re.sub() |
Replace occurrences of pattern |
|
re.split() |
Split string using a pattern |
|
Pattern |
Meaning |
|
\d |
Any digit (0–9) |
|
\D |
Non-digit |
|
\w |
Word character (a–z, A–Z, 0–9, _) |
|
\W |
Non-word character |
|
\s |
Whitespace (space, tab) |
|
\S |
Non-whitespace |
|
\b |
word boundary |
|
\B |
non-word boundar |
|
Symbol |
Meaning |
|
^ |
Start of string |
|
$ |
End of string |
|
Symbol |
Meaning |
Example |
Matches |
|
* |
0 or more |
a* |
"",
a, aaa |
|
+ |
1 or more |
a+ |
a, aaa |
|
? |
0 or 1 |
a? |
"",
a |
|
{m} |
exactly m |
a{3} |
aaa |
|
{m,n} |
between m and n |
a{2,4} |
aa…aaaa |
Python treats the backslash \ as a special escape character in normal strings. But in raw strings, the backslash is treated as a normal literal character. So regex uses raw strings to avoid confusion.
In a normal string:
- \n = newline
- \t = tab
- \b = backspace
- \\ = a single backslash
import repattern = r"^\d{10}$"text = "9876543210"if re.match(pattern, text):print("Valid Number")else:print("Invalid")
import retext = "Contact me at abc@gmail.com or xyz@outlook.com"emails = re.findall(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}", text)print(emails)
import rere.findall(r"\d+", "Order number 564 and 789")
import rere.split(r"\s+", "Python is very easy")
import rere.sub(r"\d", "X", "My pin is 1234")
Extract hashtags from text
import re
text = "#python is #fun and #useful"
result = re.findall(r"#\w+", text)
print(result)
Output
['#python', '#fun', '#useful']
Split text by commas or semicolons
import re
text = "apple,banana;orange,grapes"
result = re.split(r"[,;]", text)
print(result)
Output
['apple', 'banana', 'orange', 'grapes']
Extract dates in DD-MM-YYYY format
import re
text = "Today's dates: 12-05-2024, 15-10-2023."
pattern = r"\b\d{2}-\d{2}-\d{4}\b"
result = re.findall(pattern, text)
print(result)
Output
['12-05-2024', '15-10-2023']
Extract all vowels from text
import re
text = "Regular Expression"
result = re.findall(r"[aeiouAEIOU]", text)
print(result)
Output
['e', 'u', 'a', 'E', 'e', 'i', 'o']
Mask (hide) all digits in a string
import re
text = "My number is 987654"
result = re.sub(r"\d", "*", text)
print(result)
Output
My number is ******
|
Symbol |
Meaning |
Example |
|
. |
Any character |
"a.b"
→ aab, acb |
|
^ |
Start of string |
^Hello |
|
$ |
End of string |
world$ |
|
* |
0 or more repetitions |
ab* → a, ab, abb… |
|
+ |
1 or more |
ab+ → ab, abb |
|
? |
0 or 1 |
colou?r → color,
colour |
|
{m} |
Exactly m times |
\d{4} |
|
{m,n} |
Range |
\d{2,4} |
|
[] |
Character set |
[abc] |
|
() |
Group |
(abc)+ |
|
` |
` |
OR |
|
\ |
Escape |
\. to match a dot |
Networks and Sockets
What is a Network?
A network is a group of devices (computers, phones, servers) connected together to share data information, resources, and services with each other.
In simple words:
👉 Networking = Communication between computers
Common Types of Networks
|
Network Type |
Description |
|
LAN
(Local Area Network) |
Small area (home, office) |
|
WAN
(Wide Area Network) |
Covers large distances (Internet) |
|
PAN
(Personal Area Network) |
Bluetooth devices |
|
MAN
(Metropolitan Area Network) |
Covers a city |
Important Network Terms
- IP Address – Unique address of a device (e.g., 192.168.1.1)
- Port Number – A virtual point where applications send/receive data.(e.g., HTTP → port 80)
- Protocol – Rules for communication
- TCP → Reliable connection
- UDP → Fast but no guarantee
What is a Socket?
A socket is an endpoint for communication between two machines. It allows data to be exchanged between:
- Two computers on a network
- A web browser and a web server
- Any two processes communicating over TCP/UDP
Python Socket Module
The socket module is a built-in Python library used for:
- Network communication
- Sending data
- Receiving data
- Creating client-server applications
You import it as:
import socket
There are two major types of socket communication:
(A) TCP (Transmission Control Protocol) Socket
- Connection-oriented
- Reliable communication
- Ensures data reaches in correct order
- No data loss
- Uses SOCK_STREAM
(B) UDP (User Datagram Protocol) Socket
- Connection-less
- Fast but unreliable
- No guarantee of delivery or order
- Uses SOCK_DGRAM
Basic Socket Functions
|
Function |
Purpose |
|
socket() |
Creates a socket |
|
bind() |
Binds socket to IP + Port (server) |
|
listen() |
Listens for clients |
|
accept() |
Accepts a client connection |
|
connect() |
Client connects to server |
|
send() / sendto() |
Sends data |
|
recv() / recvfrom() |
Receives data |
|
close() |
Closes connection |
Introduction
The Internet is full of information available via the World Wide Web (WWW). Normally, users browse the web using applications like:
- Chrome
- Firefox
- Edge
But programs can also surf the web — retrieve web pages, submit forms, download files, and extract information — automatically.
These programs are called:
- Web Clients
- Web Bots
- Web Scrapers
- Crawlers
Python provides simple and powerful tools for building such programs.
2. Basic Concepts of Web Surfing by Programs
A program that “surfs the web” interacts with a web server using: HTTP (Hyper Text Transfer Protocol) You send a request, the server sends a response.
2.1 HTTP Methods
- GET – fetch a resource (most common)
- POST – submit data to a form
- PUT – update a resource
- DELETE – remove a resource
- HEAD – request headers only
- urllib (built-in) Lower-level, handles basic HTTP requests
- requests (external library)Most commonly used Human-friendly, simple API Powerful for automation
- BeautifulSoup (for HTML parsing)
- Selenium (for browser automation)
- Scrapy (for large-scale crawling)
from urllib import requesturl = "https://www.example.com"response = request.urlopen(url)html = response.read().decode("utf-8")print(html)
- urlopen() sends an HTTP GET request
- Server sends HTML response
- Program prints the page contents
from urllib import request, errortry:response = request.urlopen("https://wrong-url.com")print(response.read())except error.HTTPError as e:print("HTTP Error:", e.code)except error.URLError as e:print("URL Error:", e.reason)
import urllib.requesturl = "https://example.com/sample.pdf"urllib.request.urlretrieve(url, "sample.pdf")print("Download Complete")
pip install requests
import requestsurl = "https://www.example.com"response = requests.get(url)print(response.status_code)print(response.text)
import requestspayload = {"q": "python programming"}response = requests.get("https://www.google.com/search", params=payload)print(response.url)print(response.text)
import requestsdata = {"username": "admin","password": "12345"}response = requests.post("https://httpbin.org/post", data=data)print(response.text)
import requestsresponse = requests.get("https://www.example.com")print(response.headers)print(response.headers["Content-Type"])
- Applications are developed using different languages and platforms
- Data needs to be shared between systems (Web, Mobile, Cloud)
- Web services provide interoperability
- A mobile app requests student attendance data from a Python server
- A website fetches results from a backend Python service
- Uses XML for message format
- Follows strict standards
- Works over protocols like:
- HTTP
- HTTPS
- SMTP
- Supports WS-Security, transactions, and reliability
- Described using WSDL (Web Services Description Language)
SOAP Client
- Sends a request message to the web service in XML format
- Can be written in Java, Python, .NET, etc.
SOAP Server
- Hosts the web service
- Processes the SOAP request and sends a response
WSDL (Web Services Description Language)
- XML-based document
- Describes available services, methods, parameters, and data types
SOAP Message
SOAP messages are XML-based and follow a fixed structure.
SOAP Message Structure
<soap:Envelope>
<soap:Header> (Optional) </soap:Header>
<soap:Body> (Mandatory) </soap:Body>
</soap:Envelope>
- Envelope: Root element
- Header: Security, authentication, transaction info
- Body: Actual request/response data
SOAP Faults (Error Handling)
SOAP provides built-in error handling using SOAP Fault.
Example:
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>Invalid Account Number</faultstring>
</soap:Fault>
Real-World Example: Online Banking Fund Transfer
Scenario
A bank’s mobile app wants to transfer money from Account A to Account B.
Because this involves:
- Money
- Security
- Transactions
- Audit trails
👉 The bank uses SOAP Web Services.
How SOAP Works in This Example
Step-by-Step Flow
- Customer initiates fund transfer in mobile app
- Mobile app sends a SOAP request to the bank server
- SOAP server:
- Authenticates user
- Validates account balance
- Performs transaction
- SOAP server returns a SOAP response
- Mobile app displays transaction status
SOAP Request Example (Fund Transfer)
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<Security>
<Username>customer123</Username>
<Password>******</Password>
</Security>
</soap:Header>
<soap:Body>
<TransferFundsRequest>
<FromAccount>123456789</FromAccount>
<ToAccount>987654321</ToAccount>
<Amount>5000</Amount>
</TransferFundsRequest>
</soap:Body>
</soap:Envelope>
SOAP Response Example
Successful Transaction
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<TransferFundsResponse>
<Status>Success</Status>
<TransactionID>TXN789456</TransactionID>
</TransferFundsResponse>
</soap:Body>
</soap:Envelope>
Failed Transaction
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<Fault>
<faultcode>soap:Client</faultcode>
<faultstring>Insufficient Balance</faultstring>
</Fault>
</soap:Body>
</soap:Envelope>
- Uses HTTP
- Lightweight and fast
- Uses data formats like:
- JSON (most popular)
- XML
- Popular Python frameworks for creating web services:
- Flask – Lightweight, easy
- Django REST Framework (DRF) – Powerful, enterprise-level
- FastAPI – Very fast, modern, async support
1. Introduction to Web Services
A Web Service is a software system designed to support machine-to-machine communication over a network, usually the Internet. It allows different applications, developed using different programming languages and running on different platforms, to communicate with each other.
Key Characteristics of Web Services
- Platform independent
- Language independent
- Uses standard Internet protocols
- Enables interoperability between heterogeneous systems
Example Use Case
- A mobile app fetching weather data from a remote server
- A college ERP system communicating with an online payment gateway
Types of Web Services
- Uses XML as the message format
- Platform and language independent
- Supports stateful and stateless operations
- Works over multiple protocols such as HTTP, HTTPS, SMTP
- Highly secure (supports WS-Security)
- Built-in error handling mechanism
- Root element of the SOAP message
- Defines the start and end of the message
- Contains metadata like authentication, security, and transaction details
- Contains the actual request or response data
- Provides error information if a request fails
- Client sends SOAP request (XML) to server
- Request is wrapped inside SOAP Envelope
- Server processes the request
- Server sends SOAP response back to client
- Strong security support (WS-Security)
- Standardized and reliable
- Suitable for distributed and enterprise systems
- Supports transactions and ACID compliance
- Heavy and complex due to XML
- Slower than REST
- More bandwidth consumption
- Difficult to implement compared to REST
2.2 RESTful Web Services
REST stands for Representational State Transfer.
Features:
Lightweight
Uses HTTP methods (GET, POST, PUT, DELETE)
Can use XML, JSON, HTML
Faster and simpler than SOAP
Comments
Post a Comment