Python
Python
Python is widely used in various domains, including web development, data science, artificial
intelligence, automation, and more. Its extensive standard library and support for third-party
packages make it a powerful tool for solving complex problems efficiently. Due to its
versatility, Python is one of the most popular programming languages in the world today.
Another significant feature of Python is its portability. Python programs can run on various
operating systems, such as Windows, macOS, and Linux, without modification. Additionally,
Python has automatic memory management, reducing the need for manual memory allocation
and deallocation, which simplifies coding and improves performance.
Automation is another area where Python excels. With simple scripts, tasks like file handling,
data extraction, and web scraping can be automated, saving time and effort. Python is also
commonly used in cybersecurity, network programming, embedded systems, and even game
development, showcasing its versatility in the software industry.
1
1.4 Installing Python and Setting Up the Environment
Before starting with Python programming, it is essential to install Python and set up a suitable
development environment. The official Python website (python.org) provides downloadable
versions for different operating systems. The installation process is straightforward, with
options to include pip, the package manager for Python.
For writing and running Python programs, various integrated development environments
(IDEs) are available, such as PyCharm, VS Code, and Jupyter Notebook. The default Python
IDLE (Integrated Development and Learning Environment) is also a simple option for
beginners. Setting up a proper development environment ensures a smooth coding experience
and enables better debugging and execution of Python scripts.
Python scripts typically start with a print() statement or variable declarations. Statements are
written in a single line, and comments are added using the # symbol. Multi-line comments can
be written using triple quotes (''' or """). Python follows a dynamic typing approach, meaning
variables do not require explicit type declarations, making code development faster and more
flexible.
2
2.PYTHON BASICS
2.1 Writing and Running Python Programs
Python programs are written as scripts in .py files or executed interactively in the Python shell.
The simplest way to run Python code is through the command line by typing python or python3,
followed by the script name. Python’s interactive mode allows users to test small code snippets
quickly.
Python provides various ways to execute scripts, including IDEs like PyCharm and VS Code,
text editors like Notepad++, and Jupyter Notebooks for interactive computing. Regardless of
the environment, Python’s easy-to-use syntax makes it a preferred choice for beginners and
professionals alike.
Strings (str) – Textual data enclosed in single or double quotes, such as "Hello, World!".
Complex Numbers (complex) – Numbers with real and imaginary parts, such as 2 + 3j.
Python also allows type conversion between these data types using functions like int(), float(),
and str(), making it flexible for various operations.
3
For user input, Python uses the input() function, which reads input as a string. If numerical
operations are needed, the input must be converted using int() or float(). Handling input/output
efficiently is crucial for building interactive Python programs.
Explicit conversion, or type casting, is done using functions like int(), float(), str(), and bool().
This is useful when performing operations that require specific data types, such as
mathematical calculations or string manipulations. Understanding type conversion helps avoid
errors and ensures data consistency in programs.
4
3.OPERATORS IN PYTHON
Operators are symbols that perform operations on variables and values. Python supports
various types of operators to handle mathematical, logical, and bitwise operations.
For example:
a = 10
b=3
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333
Floor Division: 3
Modulus: 1
Exponentiation: 1000
5
The // operator performs floor division, meaning it rounds down the result to the nearest whole
number. The ** operator raises the number to the power of another number.
For example:
x=5
y = 10
x is equal to y: False
For example:
a = True
6
b = False
print("a or b:", a or b)
a and b: False
a or b: True
not a: False
For example:
a = 5 (Binary: 0101)
b = 3 (Binary: 0011)
print("Bitwise OR:", a | b)
print("Bitwise XOR:", a ^ b)
Bitwise AND: 1
Bitwise OR: 7
7
Bitwise XOR: 6
Bitwise NOT of a: -6
Left Shift: 10
Right Shift: 2
For example:
x = 10
x += 5 (Equivalent to x = x + 5)
x -= 3 (Equivalent to x = x - 3)
x *= 2 (Equivalent to x = x * 2)
x /= 4 (Equivalent to x = x / 4)
x %= 3 (Equivalent to x = x % 3)
x **= 2 (Equivalent to x = x ** 2)
If the initial value of x is 10, the output after each operation will be:
x = 15
x = 12
x = 24
8
x = 6.0
x = 0.0
x = 0.0
For example:
my_list = [1, 2, 3, 4, 5]
print(3 in my_list)
True
True
For example:
b=a
print(a is b)
print(a is not c)
True
True
9
4.CONTROL FLOW STATEMENTS
Control flow statements determine the sequence in which instructions are executed in a
program. Python provides conditional statements, loops, and loop control mechanisms to
control the flow of execution.
For example:
num = 10
if num > 0:
print("Positive number")
Positive number
num = -5
if num > 0:
print("Positive number")
else:
print("Negative number")
Output:
Negative number
num = 0
if num > 0:
print("Positive number")
10
elif num < 0:
print("Negative number")
else:
print("Zero")
Output:
Zero
count = 1
print("Count:", count)
count += 1
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
A for loop is used to iterate over sequences like lists, tuples, and strings:
print("Iteration:", i)
Output:
Iteration: 1
11
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
if i == 5:
break
print(i)
Output:
The continue statement skips the current iteration and moves to the next one:
if i == 3:
continue
print(i)
Output:
12
5
if i == 3:
pass
print(i)
Output:
13
5.FUNCTIONS IN PYTHON
Functions in Python allow code reuse and modular programming. Python supports different
types of function arguments, including positional arguments, keyword arguments, default
arguments, arbitrary positional arguments (*args), and arbitrary keyword arguments
(**kwargs).
Example:
greet("Alice", 25)
Output:
If the number of arguments in the function call does not match the function definition, an error
occurs.
Example:
greet("Bob")
greet("Charlie", 22)
Output:
14
Hello Charlie You are 22 years old.
Example:
greet(age=30, name="David")
Output:
Using keyword arguments improves readability and avoids confusion in argument order.
Example:
def sum_numbers(*numbers):
total = sum(numbers)
print("Sum:", total)
sum_numbers(1, 2, 3, 4, 5)
Output:
Sum: 15
The function can take any number of arguments, and they are stored in a tuple.
15
Example:
def person_info(**info):
Output:
name : Eve
age : 28
This is useful when a function must accept a varying number of named parameters.
16
6.DATA STRUCTURES IN PYTHON
Data structures help in organizing and managing data efficiently. Python provides several built-
in data structures that allow storing and manipulating data in various ways. The primary data
structures in Python include:
Lists
Tuples
Sets
Dictionaries
Strings as a Data Structure
6.1 Lists
A list is an ordered, mutable collection that allows duplicate elements. Lists are defined using
square brackets [ ].
Example:
fruits = ["apple", "banana", "cherry", "apple"]
print(fruits)
Output:
['apple', 'banana', 'cherry', 'apple']
Lists support indexing, slicing, and various methods like:
Adding elements:
fruits.append("mango")
Removing elements:
fruits.remove("banana")
Looping through a list:
for fruit in fruits:
print(fruit)
Lists are versatile and used frequently in Python programming.
6.2 Tuples
A tuple is an ordered, immutable collection that allows duplicate elements. Tuples are defined
using parentheses ( ).
Example:
numbers = (10, 20, 30, 40, 50)
print(numbers)
17
Output:
(10, 20, 30, 40, 50)
Tuples are useful when data should not be modified after creation.
Accessing tuple elements:
print(numbers[1]) # Outputs: 20
Tuples can be used as dictionary keys and are more memory-efficient than lists.
6.3 Sets
A set is an unordered collection of unique elements. Sets are defined using curly braces { }.
Example:
unique_numbers = {1, 2, 3, 4, 5, 1, 2}
print(unique_numbers)
Output:
{1, 2, 3, 4, 5}
Sets do not allow duplicate values and provide fast membership testing.
Adding elements:
unique_numbers.add(6)
Removing elements:
unique_numbers.remove(3)
Sets are useful for operations like union and intersection.
6.4 Dictionaries
A dictionary is an unordered collection of key-value pairs. Dictionaries are defined using curly
braces { } with keys and values separated by colons :.
Example:
student = {"name": "Alice", "age": 21, "course": "Python"}
print(student)
Output:
{'name': 'Alice', 'age': 21, 'course': 'Python'}
Accessing values:
print(student["name"]) # Outputs: Alice
Adding a new key-value pair:
student["grade"] = "A"
18
Dictionaries are widely used for structured data representation.
19
7.FILE HANDLING
File handling allows reading, writing, and manipulating files in Python. Python provides built-
in functions to work with files using the open() function. The key operations in file handling
include:
Writing to a File
Appending to a File
Syntax:
Example:
The close() method is used to free up system resources after file operations.
Example:
content = file.read()
print(content)
file.close()
20
Example:
print(line.strip())
file.close()
Example:
file.write("Hello, Python!")
file.close()
Hello, Python!
Example:
file.close()
Hello, Python!
21
"r" → Read mode (default)
file.write("New Content")
print(file.read())
file.close()
22
8.EXCEPTION HANDLING
Exception handling in Python allows programs to deal with unexpected errors and prevent
crashes. Python provides a robust mechanism to handle runtime errors using the try-except
block. The key concepts in exception handling include:
Introduction to Exceptions
Custom Exceptions
Example of an exception:
a = 10
b=0
Output:
23
8.2 Handling Exceptions using try and except
We use try to test code and except to handle errors.
Example:
try:
a = 10
b=0
print(a / b)
except ZeroDivisionError:
Output:
If an exception occurs in the try block, control jumps to except, preventing a crash.
Example:
try:
print(x / y)
except ZeroDivisionError:
except ValueError:
If the user enters "abc", a ValueError occurs, and the respective message is displayed.
24
8.4 Using else with try-except
The else block executes only if no exception occurs in try.
Example:
try:
except ValueError:
else:
print("Operation successful!")
Example:
try:
content = file.read()
print(content)
except FileNotFoundError:
finally:
25
8.6 Raising Exceptions with raise
The raise keyword allows us to generate custom exceptions.
Example:
def check_age(age):
print("Access granted.")
try:
check_age(16)
except ValueError as e:
print("Error:", e)
Output:
Example:
class NegativeNumberError(Exception):
pass
def check_positive(num):
if num < 0:
print("Number is positive.")
try:
check_positive(-5)
26
except NegativeNumberError as e:
print("Error:", e)
Output:
27
9.OBJECT-ORIENTED PROGRAMMING
Object-Oriented Programming (OOP) is a programming paradigm that organizes code into
objects, which combine data and behavior. Python supports OOP principles such as
encapsulation, inheritance, and polymorphism.
The key concepts in OOP include:
Introduction to OOP
Classes and Objects
Constructors and the init Method
Instance and Class Variables
Encapsulation and Access Modifiers
Inheritance
Polymorphism
28
Here, Car is a class, and my_car is an object of that class.
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
p1 = Person("Alice", 25)
p1.display()
Output:
Name: Alice, Age: 25
The __init__ method automatically executes when an object is created.
s1 = Student("John")
s2 = Student("Emma")
print(s1.name, s1.school)
print(s2.name, s2.school)
Output:
29
John ABC School
Emma ABC School
def get_balance(self):
return self.__balance
acc = BankAccount(1000)
acc.deposit(500)
print(acc.get_balance()) # Outputs: 1500
Here, __balance cannot be accessed directly, ensuring data security.
9.6 Inheritance
Inheritance allows a class to acquire properties of another class.
Single Inheritance → One class inherits from another
Multiple Inheritance → A class inherits from multiple classes
Multilevel Inheritance → Inheritance in multiple levels
Example of Single Inheritance:
class Animal:
def make_sound(self):
30
print("Animal makes a sound")
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
d.make_sound()
d.bark()
Output:
Animal makes a sound
Dog barks
The Dog class inherits the make_sound method from Animal.
9.7 Polymorphism
Polymorphism allows using a single function name for different types.
Example of method overriding:
class Shape:
def area(self):
print("Calculating area...")
class Circle(Shape):
def area(self):
print("Area of Circle = π × r²")
c = Circle()
c.area()
Output:
Area of Circle = π × r²
Here, the area method is overridden in the Circle class.
31