Skip to main content

Python Course

 

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

  1. Go to www.python.org.
  2. Download the latest version (currently 3.8) according to your system specification (32 bit or 64 bit)
  3. 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

  1. Interactive mode /python interpreter mode
  2. Script mode
  3. IDLE (Integrated Development Environment)

Writing Your First python program

  1. Open python IDLE
  2. Create a new file
  3. Write a program
  4. Save the program as filename.py
  5. 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

  1. Jupyter Notebook
  2. Spyder
  3. pycharm
  4. Notepad++
  5. 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.
Naming Conventions (Best Practices)
  • Use snake_case for variables and functions:
            student_name = "Alice"
  • Use PascalCase for classes:
            class StudentProfile:
  • Use UPPER_CASE for constants:
            PI = 3.1416
Avoid single-character names except for loop counters (i, j, k).

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

When you create a variable, Python creates an object in memory to hold the value.
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. A statement is a complete line of code in Python that performs some action. It is the smallest executable unit in a Python program.

In simple terms:

A statement tells Python to do something.

Types of Statements in Python

  1. Assignment Statements Used to assign a value to a variable.
  2. Conditional Statements Used to make decisions based on conditions.
  3. Looping Statements Used to repeat a block of code.
  4. Import Statements Used to include external Python modules.
  5. Function Definition Statements Used to define functions.
  6. Class Definition Statements Used to define classes.
  7. 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. 

A comment is a piece of text in a program that is ignored by the Python interpreter. It is meant for humans to read — to explain, describe, or annotate code — and has no effect on program execution.

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

  1. All statements in the same block must have the same indentation.
  2. Indentation can be spaces or tabs (PEP 8 recommends 4 spaces).
  3. Mixing spaces and tabs is not allowed (can cause errors).
  4. 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.                                                                                                      

  1. Number / Numeric Type (int, float, complex)
  2. Boolean
  3. Sequence Type (String, List, Tuple, Range)
  4. Dictionary
  5. Set
Numeric types are Python’s built-in data types that store numbers.
Python supports three main numeric types:

int → Integer numbers
float → Decimal (floating-point) numbers
complex → Complex numbers (real + imaginary part)

1. Integer (int)
Whole numbers without a decimal point. Can be positive, negative, or zero. No fixed size limit — Python handles very large integers.

Example:
a = 10
b = -5
c = 0
print(type(a))  # <class 'int'>
2. Floating Point (float)
Numbers with a decimal point or in scientific notation. Used for real numbers.

Example:
x = 3.14
y = -0.5
z = 2e3  # 2000.0 (scientific notation)
print(type(x))  # <class 'float'>
3. Complex Numbers (complex)
Numbers with a real and an imaginary part. Written as real + imaginaryj (where j is √-1 in Python).

Example:
num = 2 + 3j
print(num.real)  # 2.0
print(num.imag)  # 3.0
print(type(num)) # <class 'complex'>
Type Conversion Between Numeric Types
a = 5       # int
b = float(a) # int → float
c = complex(a) # int → complex
Common Numeric Functions
Python provides built-in functions for numeric operations:
abs(-7)        # 7
pow(2, 3)      # 8
round(3.1416, 2) # 3.14
Example Program
# Working with numeric types
x = 10        # int
y = 3.5       # float
z = 2 + 4j    # complex
print("Sum:", x + y)
print("Multiply:", x * y)
print("Complex addition:", z + (1 + 2j))
Output:
Sum: 13.5
Multiply: 35.0
Complex 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 = ' ' 'Ganesh

Das' ' '

>>>name=” ” ”Ganesh

Das” ” ”

>>>name

‘Ganesh\nDas’

>>>print(name)

Ganesh

Das

 

 

Accessing string elements:         

  1. Indexing ( [ ] )
  2. Slicing ( [  :  : ] ) 

        -5            -4            -3            -2            -1

H

e

l

l

o

        0            1                2            3                4

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

            3=   00000011

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

2’s compliment      =                +1

                                    11111011        This is -5 in 2’s

Question 1:Find  -5 & 3

            -5 = 11111011

             3=  00000011

-5&3 =   00000011        which is equals to 3

Question 2:Find  -5 | 3

            -5 = 11111011

             3=  00000011

-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

2’s                       +1

            10000101          = -5

Question 3:Find  ~ 5

5=  00000101

~5=11111010            is  a negative no so find 2’s

1’s=10000101

2’s=           +1

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:

lambda arguments: expression
  • arguments → input values
  • expression → returned output (automatically returned, no return keyword needed)
Example 1: Simple Lambda Function
square = lambda x: x * x
print(square(5))
Line-by-line explanation:
Line 1:
square = lambda x: x * x
  • 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
Line 2:
print(square(5))
  • Calls the lambda function
  • Passes 5 as x
  • Calculates 5 * 5 = 25
  • Output → 25
Lambda with Multiple Arguments
add = lambda a, b: a + b
print(add(10, 20))
Lambda Inside a Function
def myfunc(n):
    return lambda a: a * n
result = myfunc(2)
print(result(10))
Lambda with no parameters
hello = lambda : "Hello, World!"
print(hello())
Or
get_number = lambda : 100
print(get_number()) 
Characteristics of lambda function:
  • 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.
Where Are Lambda Functions Used?
Lambda functions are commonly used with:
  1. map()
  2. filter()
  3. sorted()
What is map() in Python?
map() is a built-in Python function used to apply a function to every item in an iterable (like list, tuple, string, etc.).It transforms each element of the iterable without writing loops.

map() Function Syntax
map(function, iterable)
Parameters:
  • function → A function (normal or lambda) that is applied to each element
  • iterable → List, tuple, set, dictionary, string, etc.
Returns:
  • A map object (which is an iterator)
  • You must convert it to list/tuple to view results
Basic Example of map()
numbers = [1, 2, 3, 4]
result = map(lambda x: x * 2, numbers)
print(list(result))
Output:
[2, 4, 6, 8]

Explanation:

lambda x: x * 2 → function applied to each number
map() goes through each element in numbers
Doubles the element
Returns a map object, later converted to list

Uses of map()
  1. Shorter and faster than loops
  2. Clean and elegant code
  3. Works well with lambda functions
  4. Ideal for data transformation
Example 1: map() with a normal function
def square(n):
    return n * n
numbers = [1, 2, 3, 4]
result = map(square, numbers)
print(list(result))
Output:

[1, 4, 9, 16]

Example 2: map() with multiple iterables

map() can accept multiple iterables (like lists), but the function must accept the same number of arguments.
a = [1, 2, 3]
b = [4, 5, 6]
result = map(lambda x, y: x + y, a, b)
print(list(result))
Output:
[5, 7, 9]

Explanation:

First elements: 1 + 4 = 5
Second: 2 + 5 = 7
Third: 3 + 6 = 9

If lengths differ → map() stops at the shortest iterable.

What is filter() in Python?

filter() is a built-in Python function that is used to filter (select) items from an iterable (list, tuple, set, etc.) based on a condition.The condition must be given using a function that returns True or False.

If the function returns True → element is kept
If the function returns False → element is removed

filter() Syntax
filter(function, iterable)
Parameters:
  • function → A function returning True or False
  • iterable → List, tuple, set, string, etc.
Returns:
  • A filter object (iterator)
  • Convert it into list/tuple to view results
Uses of filter()
  • 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
Example 1: Basic usage with lambda
numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens))
Output:
[2, 4, 6]

✔ Condition: x % 2 == 0 (True only for even numbers)
✔ Only even numbers are kept.

Example 2: Using filter() with a normal function
def check_even(n):
    return n % 2 == 0
numbers = [10, 15, 20, 25, 30]
result = filter(check_even, numbers)
print(list(result))

Output:
[10, 20, 30]

Example 3: Filter names starting with letter “A”
names = ["Amit", "Rita", "Anil", "John"]
result = list(filter(lambda x: x.startswith("A"), names))
print(result)
Output:
['Amit', 'Anil']

What is sorted() in Python?

sorted() is a built-in Python function that returns a new sorted list from any iterable (list, tuple, dictionary, set, string).It does not modify the original data, it always returns a new list

It can sort:
  1. Numbers
  2. Strings
  3. Lists
  4. Tuples
  5. Sets
  6. Dictionaries (keys)
  7. Complex objects (like list of tuples, list of dictionaries)
Sorted() Syntax
sorted(iterable, key=None, reverse=False)
Parameters:
Parameter Description
iterable List/tuple/set/string/dict
key (Optional) A function that decides how to sort
reverse If True, sorts in descending order
✔ Returns:

A new sorted list.

Example 1: Sorting a list of numbers (default)
numbers = [5, 3, 8, 1, 2]
result = sorted(numbers)
print(result)

Output:
[1, 2, 3, 5, 8]

✔ Original list not changed.

Example 2: Sorting in descending order

Use reverse=True:
numbers = [10, 2, 8, 4]
result = sorted(numbers, reverse=True)
print(result)
Output:
[10, 8, 4, 2]

Example 3: Sorting strings alphabetically
words = ["banana", "apple", "cat", "dog"]
print(sorted(words))
Output:
['apple', 'banana', 'cat', 'dog']

Example 4: Sorting strings by length using key
words = ["python", "go", "java", "c"]
result = sorted(words, key=len)
print(result)
Output:
['c', 'go', 'java', 'python']


✔ Sorted by length, not alphabetical.

Normal function vs Lambda function

Normal Function                                     Lambda Function
Defined using def                                     Defined using lambda
Has a name                                             Anonymous (no name)
Can contain multiple statements             Only one expression
Used for general purposes                     Used for short, simple operations

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.

Characteristics of a File
  • 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.
Types of Files

1. Text Files
A text file is a type of file that stores information in human-readable characters (letters, numbers, symbols). They use ASCII (American Standard Code for Information Interchange) or Unicode encoding. When you open a text file in Notepad, VS Code, or any editor, you can directly read its contents.

Example: data.txt, notes.csv, program.py
  • 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).
Hello, this is a text file.
Python is simple.

2. Binary Files
A binary file is a file that stores data in the form of 0s and 1s (binary format) instead of plain, human-readable text. Unlike text files, you cannot open and read binary files in a text editor (you’ll see strange characters). Binary files are used to store data like images, audio, video, executables, PDFs, and program data.

Characteristics of Binary Files
  1. Not human-readable – Data is stored as binary codes (machine-readable 0s and 1s).
  2. Compact and efficient – Stores raw data in a smaller size compared to text.
  3. File extensions – .bin, .jpg, .png, .mp3, .exe, .dat, .pdf.
  4. Used for structured data – Multimedia files, software executables, database storage.
01001101 01111001 01001001 01101101 01100001 01100111 01100101

1. Writing to a Binary File
# Write binary data
data = bytes([65, 66, 67, 68])  # Represents ABCD
with open("data.bin", "wb") as f:
    f.write(data)

This creates a file data.bin that stores ABCD in binary format.

2. Reading from a Binary File
# Read binary data
with open("data.bin", "rb") as f:
    content = f.read()
    print(content)
Output:

b'ABCD'

3. Copying an Image File
# Copy an image file using binary mode
with open("image.jpg", "rb") as f1:
    data = f1.read()
with open("copy.jpg", "wb") as f2:
    f2.write(data)

This creates an exact copy of image.jpg.

4. Reading File in Chunks (Efficient for Large Files)
# Read large binary file in chunks
with open("video.mp4", "rb") as f:
    chunk = f.read(1024)   # read 1024 bytes
    while chunk:
        print(len(chunk), "bytes read")
        chunk = f.read(1024)

Difference Between Text File and Binary File

FeatureText FileBinary File
Storage FormatHuman-readable charactersBinary (0s and 1s)
Example Extensions.txt, .csv, .py.jpg, .mp3, .exe
SizeUsually smallerUsually larger
ReadabilityCan be opened in Notepad/VS CodeCannot be read by normal editors
Example UsageConfig files, logs, source codeImages, videos, software files

Basic file operations:

To work with files in Python, you perform these 5 basic operations:
  1. Opening a file
  2. Reading a file
  3. Writing to a file
  4. Appending to a file
  5. Closing a file
Additionally, supporting operations include checking existence, deleting, and using the with statement.
Let’s explain each in detail.

1. Opening a File

Before reading or writing, you must open the file using:
file = open("filename", "mode")
What is a mode?

The mode tells Python how you want to use the file.
File modes:

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


Mode Description
'r' Read mode (file must exist)
'w' Write mode (creates new or overwrites old file)
'a' Append mode (adds data at the end)
'x' Create a new file (error if file exists)
'b' Binary mode (for images, videos, mp3)
't' Text mode (default)
Example of opening a file:
f = open("data.txt", "r")
  • "data.txt" → file name
  • "r" → open in read mode
2. Writing to a File

Writing means putting new data inside the file. If file does not exist a new file will be created. But if file already exists its contents will be erased. write() method is used to write data to a file.

Use mode 'w' → write mode.

⚠ Important:
'w' overwrites the file (deletes old data).

Example:
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()
After writing, file content becomes NEW data.

3. Reading a File

Reading means getting content from the file. If file does not exists produce FileNotFoundError. Otherwise read operation is possible.

Python provides 4 useful methods.
  1. read()  : Read all characters from file
  2. read(n) : Read n characters at a time from file .
  3. readline() : Read one line at a time .
  4. redlines() : Read all the lines from the file at a time and stores in a list .

(a) read()- Read Entire File
Reads all content as a single string.
f = open("info.txt", "r")
content = f.read()
print(content)
f.close()
If the file contains:

Hello Students
Welcome to Python

Output:

Hello Students
Welcome to Python

(b) read(n) - Read First n Characters
f = open("info.txt", "r")
print(f.read(5))   # reads first 5 characters
f.close()
(c) readline() — Read One Line at a Time
f = open("info.txt", "r")
line1 = f.readline()
line2 = f.readline()
print(line1)
print(line2)
f.close()
Useful for reading large files line-by-line.

(d) readlines() — Read All Lines as a List
f = open("info.txt", "r")
lines = f.readlines()
print(lines)
f.close()
Output:

['Hello Students\n', 'Welcome to Python\n']

4. Appending to a File

Appending adds text at the end of the file without deleting existing data.

Use mode 'a' → append mode.

Example:
f = open("notes.txt", "a")
f.write("\nThis line is added later.")
f.close()
Now original content + new content is saved.

5. Closing a File

Always close files after usage using:
f.close()
Why close?
  • Saves data properly
  • Frees memory
  • Prevents file corruption
6. Using with Statement (Best Practice)

The with statement automatically closes the file, even if errors occur.

Example:
with open("sample.txt", "r") as f:
    data = f.read()
    print(data)
No need to write f.close().

This is the recommended method in real projects.

7. Checking if a File Exists

Using the os module:
import os
if os.path.exists("data.txt"):
    print("File exists")
else:
    print("File not found")
8. Deleting a File
import os
os.remove("data.txt")
9. Additional Operations: Cursor Control

Python provides methods to control the file cursor (pointer).

Method Explanation
tell() Shows current cursor position
seek(x) Moves cursor to position x
Example:
f = open("test.txt", "r")
print(f.read(5))        # reads first 5 characters
print(f.tell())         # prints cursor position
f.seek(0)               # move cursor to start
print(f.read())         # read whole file again
f.close()
 Program: login_system.py
# Simple Login System using File Handling

def register():
    with open("users.txt", "a") as f:
        username = input("Enter username: ")
        password = input("Enter password: ")
        f.write(f"{username},{password}\n")
    print("Registration successful!\n")

def login():
    username = input("Enter username: ")
    password = input("Enter password: ")
    found = False
    try:
        with open("users.txt", "r") as f:
            for line in f:
                u, p = line.strip().split(",")
                if u == username and p == password:
                    print("Login successful!\n")
                    found = True
                    break
        if not found:
            print("Invalid username or password.\n")
    except FileNotFoundError:
        print("No users registered yet.\n")

# Menu
while True:
    print("=== Login System ===")
    print("1. Register")
    print("2. Login")
    print("3. Exit")
    choice = input("Enter choice: ")

    if choice == "1":
        register()
    elif choice == "2":
        login()
    elif choice == "3":
        break
    else:
        print("Invalid choice. Try again.\n")

File Handling

File attributes:
·         name   :returns name of file
·         mode  :returns the mode in which the file was opened
·         closed :return True if file is closed

1st way:

Use try...finally block.
try:
   =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.

with open("test.txt")as f:
# 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. 

Examples of binary files:
  • Images (.jpg, .png)
  • Audio (.mp3, .wav)
  • Video (.mp4, .avi)
  • PDF documents (.pdf)
  • Executable files (.exe, .bin)
Difference Between Text and Binary Files

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


Opening Binary Files

When opening a binary file, you add 'b' to the mode:

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 = f.read()
    print(type(data))  # <class 'bytes'>
    print(len(data))   # Number of bytes
data is a bytes object
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:
    data = source.read()
with open("photo_copy.jpg", "wb") as dest:
    dest.write(data)
Copies exact content of original image
Works with any binary data (audio, video, pdf, etc.)

Reading/Writing Bytes

You can read/write small chunks using:
# Read 1024 bytes at a time
with open("video.mp4", "rb") as f:
    chunk = f.read(1024)
    while chunk:
        # process chunk
        chunk = f.read(1024)
Useful for large files, avoids memory overload.

Combining Text & Binary

Sometimes you need to write text in binary mode:
text = "Hello World"
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)
.encode() → string to bytes
.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

  1. Avoids writing the same code again and again.
  2. Makes code clean, structured, and reusable.
  3. Provides access to built-in libraries (math, random, datetime, etc.).
  4. 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)

You can write your own .py file and import it into another program.

How to create a module:

Step-1: create a python file and give a name to it
Step 2: Add variables, functions and classes to it.

How to access a module:

Importing Modules
(a) Import Entire Module
import math
print(math.sqrt(16))   # 4.0
(b) Import Specific Function
from math import sqrt
print(sqrt(25))   # 5.0
(c) Import with Alias (short name)
import math as m
print(m.factorial(5))   # 120
Creating a User-Defined Module

Step 1: Create a file mymodule.py
# mymodule.py
def greet(name):
    return f"Hello, {name}!"

def add(a, b):
    return a + b
Step 2: Import and Use in Another File
# main.py
import mymodule

print(mymodule.greet("Shree"))
print("Sum:", mymodule.add(5, 3))
Output:

Hello, Shree!
Sum: 8

Using dir() Function

The dir() function lists all functions, variables, and classes defined inside a module.
import math
print(dir(math))   # shows all available functions inside math module
Standard vs Third-Party Modules

Standard Library Modules → Come with Python (e.g., math, os, datetime).

Third-Party Modules → Installed separately using pip.
Example:

pip install numpy

import numpy as np
arr = np.array([1,2,3])
print(arr)
Package 

What is a Package in Python?

A package is a way of organizing related modules together. It is essentially a directory (folder) that contains a special file called __init__.py. Packages allow you to structure your code logically, especially for large projects. A module is a single Python file (.py) containing functions, classes, or variables. A package is a collection of modules (and even sub-packages).

Anatomy of a Python Package

Suppose we have a package named math_tools. Its structure could look like this:

math_tools/          <-- This is the package
├── __init__.py                  <-- Makes Python treat this folder as a package
├── basic.py                       <-- A module
├── advanced.py                <-- Another module
└── sub_tools/                    <-- A subpackage
    ├── __init__.py
    └── extra.py

Creating a Simple Package Example

Let’s create a simple package called mypackage.

Folder structure:

mypackage/
├── __init__.py
├── module1.py
└── module2.py

module1.py
def greet(name):
    return f"Hello, {name}!"
module2.py
def add(a, b):
    return a + b
__init__.py
# We can import modules here for easy access
from .module1 import greet
from .module2 import add

Using the Package

Now in another Python file (or interactive console), you can use:
# Import the package
import mypackage

# Use functions from modules
print(mypackage.greet("Shree"))  # Output: Hello, Shree!
print(mypackage.add(5, 7))       # Output: 12
You can also import only specific modules:
from mypackage import greet, add

print(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

Basic Functions in Python’s re Module

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

Basic RegEx Symbols

1. Character Classes

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


2. Anchors

Symbol

Meaning

^

Start of string

$

End of string


Example:

^Hello

Matches a string starting with “Hello”.

3. Quantifiers

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}

aaaaaa


Example:

a{3}  → "aaa"

5. Special Patterns

Set of characters
[abc]     → a OR b OR c
[0-9]     → any digit
[A-Z]     → uppercase alphabets

Negated set
[^0-9]     → anything except digits

Using Raw String r" "

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

Example:

r"\d+"          # correct regex
"\d+"           # Python sees \d as normal string escape

Useful Examples
Example 1: Valid Mobile Number (10 digits)
import re
pattern = r"^\d{10}$"
text = "9876543210"

if re.match(pattern, text):
    print("Valid Number")
else:
    print("Invalid")

Example 2: Find all email IDs
import re
text = "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)

Output:

['abc@gmail.com', 'xyz@outlook.com']

Example 3: Extract all digits
import re
re.findall(r"\d+", "Order number 564 and 789")
Output:

['564', '789']

Example 4: Split using spaces
import re
re.split(r"\s+", "Python is very easy")
Output:

['Python', 'is', 'very', 'easy']

Example 5: Replace digits with X
import re
re.sub(r"\d", "X", "My pin is 1234")
Output:

"My pin is XXXX"

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 ******

Met characters define special meaning in patterns.

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
  1. TCP → Reliable connection
  2. 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

Types of 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
Example: WhatsApp, Email, Web Browsers
(B) UDP (User Datagram Protocol) Socket
  • Connection-less
  • Fast but unreliable
  • No guarantee of delivery or order
  • Uses SOCK_DGRAM
Example: Video streaming, Online games, Live calls

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


Python Chat App
#Server.py
import socket

s = socket.socket()
s.bind(('localhost', 5000))
s.listen(1)

c, addr = s.accept()
print("Connected:", addr)

while True:
    msg = c.recv(1024).decode()
    print("Client:", msg)
    reply = input("Server: ")
    c.send(reply.encode())

#Client.py
import socket

s = socket.socket()
s.connect(('localhost', 5000))

while True:
    msg = input("Client: ")
    s.send(msg.encode())
    reply = s.recv(1024).decode()
    print("Server:", reply)

Programs that Surf the Web

Introduction

The Internet is full of information available via the World Wide Web (WWW). Normally, users browse the web using applications like:

  1. Chrome
  2. Firefox
  3. Edge

But programs can also surf the web — retrieve web pages, submit forms, download files, and extract information — automatically.

These programs are called:

  1. Web Clients
  2. Web Bots
  3. Web Scrapers
  4. 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

  1. GET – fetch a resource (most common)
  2. POST – submit data to a form
  3. PUT – update a resource
  4. DELETE – remove a resource
  5. HEAD – request headers only

3. Python Tools to Surf the Web

Python provides these modules:
  1. urllib (built-in) Lower-level, handles basic HTTP requests
  2. requests (external library)Most commonly used Human-friendly, simple API Powerful for automation
  3. BeautifulSoup (for HTML parsing)
  4. Selenium (for browser automation)
  5. Scrapy (for large-scale crawling)
4. Surfing the Web Using urllib

urllib is built into Python.

4.1 Fetching a Web Page
from urllib import request

url = "https://www.example.com"
response = request.urlopen(url)

html = response.read().decode("utf-8")
print(html)

Steps:
  1. urlopen() sends an HTTP GET request
  2. Server sends HTML response
  3. Program prints the page contents
4.2 Handling Errors
from urllib import request, error

try:
    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)

4.3 Downloading a File
import urllib.request

url = "https://example.com/sample.pdf"
urllib.request.urlretrieve(url, "sample.pdf")

print("Download Complete")
5. Surfing the Web Using the requests Library

Most professionals use requests because it is simpler and more powerful.

Install:
pip install requests
5.1 GET Request
import requests

url = "https://www.example.com"
response = requests.get(url)

print(response.status_code)
print(response.text)

5.2 GET with Query Parameters

Just like typing in a search URL:
import requests
payload = {"q": "python programming"}
response = requests.get("https://www.google.com/search", params=payload)
print(response.url)
print(response.text)
5.3 POST Request (Submitting a Form)
import requests
data = {
    "username": "admin",
    "password": "12345"
}
response = requests.post("https://httpbin.org/post", data=data)
print(response.text)
5.4 Viewing Headers
import requests
response = requests.get("https://www.example.com")
print(response.headers)
print(response.headers["Content-Type"])
Python Web Services
1. Introduction to Web Services

A Web Service is a software system designed to allow communication between different applications over the internet using standard protocols. In simple words Web services allow one program to talk to another program over the web, regardless of the programming language or platform. Python is widely used to create (provide) as well as consume (use) web services.

2. Why Web Services Are Needed
  • Applications are developed using different languages and platforms
  • Data needs to be shared between systems (Web, Mobile, Cloud)
  • Web services provide interoperability
Example:
  • A mobile app requests student attendance data from a Python server
  • A website fetches results from a backend Python service
3. Types of Web Services

Web services are mainly classified into:

Introduction to SOAP

SOAP stands for Simple Object Access Protocol. SOAP is a protocol used to exchange structured information between applications over a network. It is platform-independent and language-independent. SOAP is commonly used in banking, finance, government, and enterprise systems where security, reliability, and standardization are critical.

Key Characteristics of SOAP Web Services
  • Uses XML for message format
  • Follows strict standards
  • Works over protocols like:
  1. HTTP
  2. HTTPS
  3. SMTP
  • Supports WS-Security, transactions, and reliability
  • Described using WSDL (Web Services Description Language)
SOAP Architecture

SOAP web services are based on a client-server architecture.
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:
  1. Authenticates user
  2. Validates account balance
  3. 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> 


2. RESTful Web Services (Most Common)
  • Uses HTTP
  • Lightweight and fast
  • Uses data formats like:
  • JSON (most popular)
  • XML
Easy to implement in Python

👉 Python mostly uses RESTful Web Services

4. RESTful Web Services

REST stands for Representational State Transfer.

A RESTful web service:

Uses standard HTTP methods

Transfers data in JSON format

Is stateless (each request is independent)

Common HTTP Methods
Method Purpose
GET Retrieve data
POST Send new data
PUT Update data
DELETE Delete data
5. Python Frameworks for Web Services
  • Popular Python frameworks for creating web services:
  • Flask – Lightweight, easy
  • Django REST Framework (DRF) – Powerful, enterprise-level
  • FastAPI – Very fast, modern, async support
👉 For learning: Flask
👉 For production: Django REST / FastAPI

6. Example: Simple Python Web Service Using Flask
Step 1: Install Flask
pip install flask

Step 2: Create a Simple Web Service
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/hello', methods=['GET'])
def hello():
    return jsonify({"message": "Hello from Python Web Service"})

if __name__ == '__main__':
    app.run(debug=True)

Explanation

Flask(__name__) creates the web application

@app.route() defines the URL

/hello is the endpoint

jsonify() returns data in JSON format

Server runs on http://127.0.0.1:5000

Output (Browser / Postman)
{
  "message": "Hello from Python Web Service"
}

7. Example: Using HTTP Methods
GET Request Example
@app.route('/student', methods=['GET'])
def student():
    return jsonify({
        "name": "Rahul",
        "branch": "CSE",
        "year": 3
    })

POST Request Example
from flask import request

@app.route('/add', methods=['POST'])
def add():
    data = request.json
    return jsonify({
        "status": "Success",
        "received_data": data
    })

8. Consuming a Web Service in Python

Python can also consume web services using the requests library.

Example:
import requests

response = requests.get("http://127.0.0.1:5000/hello")
print(response.json())

9. Advantages of Python Web Services

Easy to develop and maintain

Platform independent

Scalable and secure

Supports JSON and REST APIs

Used in real-world applications

10. Real-World Applications

Student attendance systems

Online examination systems

Mobile app backends

Payment gateways

Cloud services

AI & ML APIs

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

  1. Platform independent
  2. Language independent
  3. Uses standard Internet protocols
  4. Enables interoperability between heterogeneous systems

Example Use Case

  1. A mobile app fetching weather data from a remote server
  2. A college ERP system communicating with an online payment gateway

Types of Web Services

SOAP Web Services

SOAP stands for Simple Object Access Protocol. It is a protocol used for exchanging structured information in web services using XML. SOAP is designed to be platform-independent and language-independent, making it suitable for enterprise-level applications.

SOAP web services follow strict standards and are commonly used where security, reliability, and transactional integrity are critical.

Key Features of SOAP Web Services

  1. Uses XML as the message format
  2. Platform and language independent
  3. Supports stateful and stateless operations
  4. Works over multiple protocols such as HTTP, HTTPS, SMTP
  5. Highly secure (supports WS-Security)
  6. Built-in error handling mechanism

SOAP Message Structure

A SOAP message is an XML document consisting of the following elements:

SOAP Envelope
  • Root element of the SOAP message
  • Defines the start and end of the message
SOAP Header (Optional)
  • Contains metadata like authentication, security, and transaction details
SOAP Body
  • Contains the actual request or response data
SOAP Fault (Optional)
  • Provides error information if a request fails
SOAP Message Example
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <auth>
      <username>admin</username>
      <password>1234</password>
    </auth>
  </soap:Header>
  <soap:Body>
    <getStudentDetails>
      <roll>101</roll>
    </getStudentDetails>
  </soap:Body>
</soap:Envelope>

Explanation:

<soap:Envelope> defines the SOAP message
<soap:Header> contains authentication data
<soap:Body> carries the service request

SOAP Fault Example
<soap:Fault>
  <faultcode>soap:Client</faultcode>
  <faultstring>Invalid Roll Number</faultstring>
</soap:Fault>

This message is returned when an error occurs during request processing.

SOAP Communication Process
  1. Client sends SOAP request (XML) to server
  2. Request is wrapped inside SOAP Envelope
  3. Server processes the request
  4. Server sends SOAP response back to client
Advantages of SOAP Web Services
  1. Strong security support (WS-Security)
  2. Standardized and reliable
  3. Suitable for distributed and enterprise systems
  4. Supports transactions and ACID compliance
Disadvantages of SOAP Web Services
  1. Heavy and complex due to XML
  2. Slower than REST
  3. More bandwidth consumption
  4. 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

Popular posts from this blog

How to write and naming a java program

Java program can be created by using any editor.  The source code in java contains one or multiple number of classes.  Naming a java program Java program must be saved with a .java extension.  The primary name of the program must be same as class name if the class is declared as public.  It can be any name if no class is declared as public.  In one Java program there is only one public class.  How to compile a java program To compile a java program in command prompt (CMD)  Syntax- javac <file_name.java> Example- javac Hello.java How to run a java program To run a java program in command prompt Syntax- java class_name Example- java Hello

Command Prompt (CMD) Basic commands to Compile and Run java programs

How to change the drive in CMD (Command Prompt) To access another drive, type the drive’s letter, followed by : For instance, if you wanted to change the drive from C: to E:, you should type- Example-  E: ⤶ How to change the directory in CMD (CD in Command Prompt) The first command from the list is CD (Change Directory). This command enables you to change the current directory or, in other words, to navigate to another folder from your PC. Syntax- CD <Folder_Name> ⤶ Example- CD Saubhagya ⤶ How to go to the root of the drive in CMD (CD\) The first iteration of the CD command you should know is CD\. It takes you to the top of the directory tree. To see how it works, after you open the Command Prompt, type: Example- CD\ ⤶ How to change the parent directory in CMD (CD..) When you need to go one folder up, use the cd.. command. Let's assume that you’re inside the system32 folder and want to go back to the Windows folder. Type Example-  CD.. ⤶

Features of Java

  Features of Java The primary objective of Java programming language creation was to make it portable, simple and secure programming language. Apart from this, there are also some excellent features which play an important role in the popularity of this language. The features of Java are also known as Java buzzwords . A list of the most important features of the Java language is given below. Simple Object-Oriented Portable Platform independent Secured Robust Architecture neutral Interpreted High Performance Multithreaded Distributed Dynamic Simple Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java language is a simple programming language because: Java syntax is based on C++ (so easier for programmers to learn it after C++). Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc. There is no need to remove unreferenced objects because there is an Autom...