0% found this document useful (0 votes)
6 views28 pages

Python Unit 1 Notes

Python is a high-level, interpreted programming language known for its readability and versatility, supporting multiple programming paradigms. It features dynamic typing, extensive libraries, and strong community support, making it suitable for web development, data science, automation, and more. Created by Guido van Rossum in the late 1980s, Python has evolved through various versions, with significant enhancements in functionality and performance.

Uploaded by

mathumithra669
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views28 pages

Python Unit 1 Notes

Python is a high-level, interpreted programming language known for its readability and versatility, supporting multiple programming paradigms. It features dynamic typing, extensive libraries, and strong community support, making it suitable for web development, data science, automation, and more. Created by Guido van Rossum in the late 1980s, Python has evolved through various versions, with significant enhancements in functionality and performance.

Uploaded by

mathumithra669
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-1

Introduction to python
Python
Python is a high-level, interpreted, general-purpose programming language that
emphasizes readability and simplicity. It was designed with the philosophy that code should be
easy to write and easy to understand. Unlike low-level languages such as C or assembly, Python
abstracts away machine-level complexities, allowing developers to focus on solving problems
logically rather than worrying about memory management or syntax intricacies. It supports
multiple programming paradigms such as procedural, object-oriented, and functional
programming, making it versatile for different types of applications. According to Mark Lutz,
Python is often called a “glue language” because of its ability to integrate systems and libraries
written in other languages like C, C++, or Java.
Features of Python
Python is popular because of its unique set of features that distinguish it from other
programming languages:
1. Simple and Readable – Python’s syntax is close to natural English, making it beginner-
friendly and easy to understand. Bill Lubanovic highlights Python’s philosophy of
“readability counts.”
2. Interpreted Language – Python code does not need to be compiled. The interpreter
executes instructions line by line, which improves debugging and testing.
3. Cross-Platform Support – Python programs can run on Windows, macOS, Linux, and
even mobile platforms without modification.
4. Extensive Standard Library – Python comes with a “batteries included” approach,
offering built-in libraries for file handling, networking, web development, and more.
5. Object-Oriented and Functional – It supports both object-oriented programming
(classes, inheritance) and functional programming (map, filter, lambda).
6. Dynamic Typing – Variables in Python do not need explicit type declaration; their type
is inferred at runtime.
7. Large Community Support – Python has one of the largest developer communities
and vast third-party libraries like NumPy, Pandas, TensorFlow, and Django.
Advantages of Python
Python offers several benefits that make it suitable for a wide variety of tasks:
• Ease of Learning: Beginners can quickly pick up Python due to its clean syntax.
• Productivity: Developers can write fewer lines of code compared to Java or C++.
• Integration: Python integrates easily with C/C++, Java, and .NET components.
• Rapid Development: Frameworks like Django and Flask accelerate web application
development.
• Strong Support in Data Science: Libraries like NumPy, Pandas, Matplotlib, and
Scikit-learn make Python the most widely used language in AI and ML.
Applications of Python
Python is not limited to one field; its applications span multiple domains:
• Web Development – Using frameworks like Django, Flask, and FastAPI.
• Data Science and Machine Learning – Popular for statistical analysis, AI models, and
data visualization.
• Automation and Scripting – Widely used for writing scripts to automate repetitive
tasks.
• Software Development – Used to develop desktop applications, games, and system
utilities.
• Networking and Cybersecurity – Used in penetration testing tools and network
automation.
• Education – Because of its simplicity, Python is the first programming language taught
in many universities worldwide.
History of Python
Python was created by Guido van Rossum in the late 1980s at Centrum Wiskunde &
Informatica (CWI) in the Netherlands. The language’s development began in 1989 during
Guido’s Christmas holidays as a hobby project, but it quickly evolved into something much
larger. The first official version, Python 0.9.0, was released in February 1991. This version
already included many core features such as functions, exceptions, and core data types (str, list,
dict). Later, Python 2.0 was released in 2000, introducing features like list comprehensions and
garbage collection. However, Python 2 had backward compatibility issues, which led to the
release of Python 3.0 in 2008, a modernized version that emphasized clarity and consistency.
Today, Python is maintained by the Python Software Foundation (PSF) and is one of the
most widely used programming languages across industries, research, and education.

Version Year Key Features / Highlights


Released

Python 1.0 1994 First official release by Guido van Rossum. Included basic data
types (str, list, dict), error handling with exceptions, and core
functions.
Python 2.0 2000 List comprehensions, garbage collection using reference
counting and cycles, Unicode support.

Python 2.7 2010 Last stable release of Python 2.x series. Long-term support
version, widely used until 2020.

Python 3.0 2008 Major redesign (not backward compatible with 2.x). Improved
Unicode support, print() as a function, better integer division,
new I/O system.

Python 3.3 2012 Virtual environment (venv) introduced, flexible module import
system.

Python 3.4 2014 asyncio module for asynchronous programming, pip included
by default.

Python 3.5 2015 Introduced async and await keywords, matrix multiplication
operator @.

Python 3.6 2016 Formatted string literals (f-strings), variable annotations.

Python 3.7 2018 Data classes (dataclass), context variables, time functions with
nanosecond precision.

Python 3.8 2019 Walrus operator :=, positional-only parameters, performance


improvements.

Python 3.9 2020 Dictionary merge (`

Python 3.10 2021 Structural pattern matching (match statement), precise error
messages.

Python 3.11 2022 Major performance improvements (10–60% faster), better


error tracebacks.

Python 3.12 2023 Enhanced f-strings, improved error messages, more


optimization.

Python 3.13 2024 Further speed improvements, better Unicode, improved type
hints and modules.

How Python Code is Executed


When we write a Python program, it goes through a series of steps before execution.
Unlike compiled languages like C or Java, Python is an interpreted language, meaning the
code is executed line by line by the Python interpreter. The process can be explained as follows:
• Step 1: Writing the Code (Source Code)
The programmer writes Python code in a .py file using any text editor or IDE.
This source code is plain text that humans can understand but computers cannot
directly execute.
• Step 2: Python Interpreter Reads the Code
When the code is run, the Python interpreter takes the source code as input.
Internally, the interpreter first checks for any syntax errors. If an error is found, the
program stops before execution begins.
• Step 3: Compilation to Bytecode
Python does not directly convert code into machine language. Instead, it
compiles the source code into an intermediate form called bytecode. This
bytecode is a low-level, platform-independent representation of the code.
o This bytecode is stored in .pyc files (inside the __pycache__ folder) for faster
execution when the program runs again.
• Step 4: Python Virtual Machine (PVM)
The generated bytecode is then passed to the Python Virtual Machine (PVM).
The PVM is part of the interpreter that actually executes the instructions line by line.
o If there are runtime errors (like dividing by zero), the execution stops here.
o Otherwise, the PVM translates the bytecode into machine-specific instructions
that the operating system and hardware can understand.
• Step 5: Execution and Output
Finally, the program produces the desired output on the screen or performs the
required operation.
Variables
In Python, a variable is a symbolic name or identifier that is used to store data in
memory so it can be referenced and manipulated later in a program. Think of a variable as a
container or a label attached to a memory location that holds a value. Unlike some other
programming languages (like C, C++ or Java), Python variables do not require explicit
declaration of their type before use. When a value is assigned to a variable, Python
automatically creates the variable and determines its type based on the value.
For example:
x = 10 # x stores an integer
name = "Hari" # name stores a string
pi = 3.14 # pi stores a float

Key Points about Variables in Python:


• Dynamic Typing: Variables in Python are not bound to a fixed type; you can reassign a
variable with a value of a different data type at any point.
x=5 # integer
x = "hello" # now string

• Memory Reference: A variable does not store the value directly; it stores a reference to
the object in memory. For example, when you write a = 10, the name a refers to the
memory location where the integer object 10 is stored.
• No Declaration Needed: Unlike Java or C++, you don’t declare variables with types. A
variable comes into existence the moment you assign a value to it.
• Case Sensitivity: Python treats uppercase and lowercase letters differently. For
example, Name and name are two distinct variables.
• Flexibility: A single variable can be reassigned multiple times to different data types or
objects.
Rules for Naming Variables
When creating variables, Python follows certain rules:
1. Variable names must start with a letter (a–z, A–Z) or an underscore (_).
2. They cannot start with a number.
3. They can contain letters, digits, and underscores, but no special characters like @, $,
%.
4. Variable names are case-sensitive (Name and name are different).
5. Keywords (like class, if, for) cannot be used as variable names.
Different Types of Variables in Python
1. Local Variables
• A local variable is declared inside a function or block and can only be accessed within
that scope.
• These variables are created when the function is called and destroyed when the function
ends.
• They are useful for temporary storage during function execution.
Example:

def greet():
name = "Hari" # Local variable
print("Hello", name)
greet()
# print(name) # Error: 'name' not accessible here
2. Global Variables
• A global variable is declared outside all functions and is accessible throughout the
program.
• They remain in memory for the program’s lifetime.
• However, modifying global variables inside a function requires the global keyword.
Example:

x = 10 # Global variable
def update():
global x
x=x+5
print("Inside function:", x)
update()
print("Outside function:", x)

3. Constants
• A constant is a variable whose value should not be changed after initialization.
• Python does not have built-in constant support, but by naming convention, constants
are written in uppercase letters.
• Constants are usually declared in a separate file (e.g., [Link]).
Example:

PI = 3.14159
APP_NAME = "MyChatbot"
print("Value of PI:", PI)

Data Types
In Python, a data type defines the kind of value a variable can hold and what operations
can be performed on it. Since Python is a dynamically typed language, we do not need to
declare the data type of a variable explicitly. Instead, Python interprets the type at runtime
depending on the value assigned. Data types help Python manage memory efficiently and
provide specific behaviors for different values.
Data types in Python are important because they:
1. Determine the memory allocation needed to store a variable.
2. Define the operations that can be performed on the data (e.g., addition is allowed
on numbers but not on strings).
3. Ensure data integrity by restricting inappropriate operations.
In simple terms, a data type acts as a blueprint for the data stored in a variable,
guiding Python on how to handle it internally. Using proper data types is essential
for writing efficient, error-free, and logical programs.
Formal definition for exams:
"A data type in Python is a classification of data that specifies what kind of value
a variable can hold, what operations can be performed on it, and how it should be
stored in memory. Python is dynamically typed, so the data type is automatically
assigned by the interpreter at runtime based on the value given to the variable."
Types of Data Types in Python

1. Numeric Data Types in Python


In Python, numeric data types are used to represent numbers. They are among the
most fundamental types because almost every program deals with calculations, measurements,
or values that can be expressed as numbers. Python supports three main numeric types: int
(integer), float (floating-point numbers), and complex (complex numbers). These types are
objects in Python and provide built-in functions and operators for mathematical operations.
a) Integer (int)
The integer data type in Python represents whole numbers without any fractional or
decimal part. These numbers can be positive, negative, or zero. Python’s int type has
unlimited precision, which means unlike some programming languages (like C or Java) that
restrict the size of integers based on system architecture, Python can handle arbitrarily large
integers as long as memory is available.
Integers are one of the most commonly used data types because they allow us to perform
mathematical operations such as addition, subtraction, multiplication, division, modulus,
exponentiation, and more. Python also provides a rich set of built-in functions and operators to
work with integers.
Key Points about int:
• Represents whole numbers (no decimal point).
• Can be positive, negative, or zero.
• Unlimited size (depends only on system memory).
• Stored internally as signed integers.
• Commonly used in loop counters, indexing, arithmetic calculations, Boolean logic,
and mathematical algorithms.
Example:

x = 10 # Positive integer
y = -25 # Negative integer
z=0 # Zero

b) Floating-point numbers (float)


Floating-point numbers, commonly known as floats, are used to represent real
numbers that have a decimal point. They are one of the most important numeric data types in
Python because they allow us to perform calculations involving fractions, approximations, and
continuous values.
A float can represent both positive and negative numbers and can also be expressed in
scientific notation (using e or E to denote powers of 10).
Key Points about Floats:
• Defined by including a decimal point (3.14, -7.5).
• Can also be written in exponential form (1.5e3 means 1.5 × 10³ = 1500.0).
• Precision is limited to about 15–17 decimal places, since Python’s float is implemented
using double-precision (64-bit IEEE 754).
• Supports all basic arithmetic operations (+, -, *, /, **, //, %).
• Division of two integers using / always produces a float, even if divisible. Example: 4/2
→ 2.0.
Example:

a = 3.14 # Decimal value


b = -0.5 # Negative float
c = 1.2e3 # Scientific notation (1.2 × 10³ = 1200.0)

c) Complex numbers (complex)


A complex number is a number that consists of two parts: a real part and an
imaginary part. The imaginary part is represented using the letter j in Python (instead of i in
mathematics). Complex numbers are widely used in scientific computing, electrical
engineering, quantum physics, and other advanced mathematical applications.
Meaning:
• A complex number in Python has the form:
• a+bja + bja+bj
• where:
o a → real part (float or int)
o b → imaginary part (float or int)
o j → represents the square root of -1
Key Points:
• Defined using complex() function or by directly writing in a + bj format.
• The real and imaginary parts can be accessed using .real and .imag.
• Complex numbers can be used in arithmetic operations (addition, subtraction,
multiplication, division).
• Python also provides a built-in cmath module for advanced complex math functions.

c1 = 2 + 3j # Complex number
c2 = 1 - 4j
print([Link]) # Output: 2.0
print([Link]) # Output: 3.0
Boolean Data Type in Python
The Boolean data type in Python represents one of the two possible truth values: True
or False. These values are used to express logical conditions, comparisons, and decision-
making in programs. In Python, the Boolean data type is denoted as bool and is a subclass of
integers, meaning True is internally treated as 1 and False as 0. This makes it possible to use
Boolean values in mathematical expressions as well.
Key Characteristics of Boolean Data Type
• Boolean data type has only two values: True and False.
• It is often the result of comparison or logical operations.
• Since bool is a subclass of int, we can use it in arithmetic expressions. For example,
True + True = 2.
• Boolean values are widely used in conditional statements like if, while, and for.
Boolean Values in Python
1. True → Represents correctness or logical truth.
2. False → Represents falseness or logical failure.
Conversion to Boolean
Python provides a built-in function bool() which can convert other data types into Boolean
values.
• bool(0) → False
• bool("") → False
• bool(None) → False
• bool(5) → True
• bool("Hello") → True
So, in Python:
• Zero, empty collections, and None are False.
• Non-zero numbers, non-empty collections, and objects are True.
Examples
# Example 1: Boolean assignment
x = True
y = False
print(x, y) # Output: True False
# Example 2: Boolean as result of comparison
a = 10
b = 20
print(a > b) # Output: False
print(a < b) # Output: True
# Example 3: Boolean in arithmetic
print(True + True) # Output: 2
print(True * 5) # Output: 5
print(False + 10) # Output: 10
# Example 4: Using bool() function
print(bool(0)) # Output: False
print(bool(1)) # Output: True
print(bool("")) # Output: False
print(bool("Hi")) # Output: True
Use of Boolean Data Type
• Decision making → if and while statements depend on Boolean values.
• Condition checking → Comparisons (==, >, <) return Boolean results.
• Logical operations → and, or, not operators work with Boolean values.
3. Sequence Data Types in Python
In Python, sequences are one of the most important and widely used data structures. A
sequence is an ordered collection of items where each element is assigned a unique position
(index). The index starts from 0 for the first element, 1 for the second, and so on. Python allows
accessing individual elements of a sequence using these indexes, slicing (extracting parts of a
sequence), and iteration (looping through the sequence).
The built-in sequence data types in Python include:
• String (str)
• List (list)
• Tuple (tuple)
Each of these has unique properties and use cases. Let us study them in detail.
3.1 String (str)
In Python, a string is a sequence of characters enclosed within single quotes ('), double
quotes ("), or triple quotes (''' or """). Strings are one of the most widely used data types in
Python and are immutable, meaning once a string is created, it cannot be modified directly.
Instead, any operation on a string creates a new string.
Features of Strings
• Strings are ordered collections of characters.
• They are immutable (cannot be changed after creation).
• Strings support indexing and slicing.
• They can contain letters, numbers, special characters, or even spaces.
• Strings can be created using single-line or multi-line declarations.
Creating Strings

# Single quotes
s1 = 'Hello'
# Double quotes
s2 = "World"
# Triple quotes (used for multi-line strings or docstrings)
s3 = '''This is
a multi-line
string.'''
print(s1, s2, s3)

Accessing Characters in Strings


• Strings are indexed starting from 0.
• Negative indices can be used to access characters from the end.

text = "Python"
print(text[0]) # P
print(text[-1]) # n
Slicing Strings
Slicing allows extracting a portion of a string.

text = "Programming"
print(text[0:6]) # Progra (characters from 0 to 5)
print(text[3:]) # gramming (from index 3 till end)
print(text[:5]) # Progr (from start till index 4)

String Operations
1. Concatenation (+) → Joining two strings.
2. Repetition (*) → Repeating a string multiple times.
3. Membership (in, not in) → Checking existence of substring.

a = "Hello"
b = "World"
print(a + " " + b) # Hello World
print(a * 3) # HelloHelloHello
print("H" in a) # True
print("z" not in a) # True

Important String Methods


• upper() – Converts string to uppercase.
• lower() – Converts string to lowercase.
• capitalize() – Capitalizes first character.
• title() – Capitalizes first letter of each word.
• strip() – Removes whitespace.
• replace(old, new) – Replaces substring.
• split() – Splits string into list.
• join() – Joins list into string.
• find() – Returns index of substring, -1 if not found.

s = " python programming "


print([Link]()) # PYTHON PROGRAMMING
print([Link]()) # python programming
print([Link]()) # python programming
print([Link]("python", "Java")) # Java programming
print([Link]()) # ['python', 'programming']
print("-".join(["AI", "ML", "DS"])) # AI-ML-DS
print([Link]("pro")) #9

Escape Sequences in Strings


• \n → New line
• \t → Tab
• \' → Single quote
• \" → Double quote
• \\ → Backslash

print("Hello\nWorld") # Hello (newline) World


print("Hello\tWorld") # Hello World

3.2 List (list)


A list in Python is one of the most widely used sequence data types. It is an ordered
collection of items, which means the elements inside a list are arranged in a specific sequence
and each element can be accessed using its index. Lists are mutable, which means their
contents can be changed even after creation — elements can be added, removed, or modified.
Lists can store elements of different data types such as integers, floats, strings, or even other
lists (nested lists).
A list in Python is a powerful, flexible data type that allows storing multiple values in
an ordered and mutable manner, supporting dynamic programming needs
Key Features of Lists
• Lists are ordered: Items have a defined order, and that order will not change unless
explicitly modified.
• Lists are mutable: Elements can be updated, deleted, or appended.
• Lists allow duplicate elements: The same value can appear more than once.
• Lists can hold heterogeneous data: They may contain a mix of numbers, strings,
booleans, or even other lists.
Syntax
my_list = [element1, element2, element3, ...]
Examples
1. Creating a List

numbers = [1, 2, 3, 4, 5]
mixed = [10, "Python", 3.14, True]

2. Accessing Elements

print(numbers[0]) # Output: 1 (first element)


print(mixed[1]) # Output: Python
print(numbers[-1]) # Output: 5 (last element)

3. Modifying Elements

numbers[2] = 30
print(numbers) # Output: [1, 2, 30, 4, 5]

4. Adding Elements

[Link](6) # Add single element


[Link]([7, 8]) # Add multiple elements
[Link](2, 100) # Insert at specific index
print(numbers) # Output: [1, 2, 100, 30, 4, 5, 6, 7, 8]
5. Removing Elements

[Link](100) # Remove by value


popped = [Link](3) # Remove by index
del numbers[0] # Delete element at index

6. Slicing Lists

print(numbers[1:4]) # Output: [2, 30, 4]


print(numbers[:3]) # First 3 elements
print(numbers[::2]) # Elements with step of 2

[Link] Lists

nested = [[1, 2], [3, 4], [5, 6]]


print(nested[1][0]) # Output: 3 (first element of second list)

Common List Functions


• len(my_list) → Returns number of elements.
• min(my_list) / max(my_list) → Smallest / largest element.
• sum(my_list) → Sum of numeric elements.
• my_list.sort() → Sorts list in ascending order.
• my_list.reverse() → Reverses list.

3.3 Tuples in Python


A tuple in Python is an ordered, immutable collection of elements. Tuples are very
similar to lists, but unlike lists, once a tuple is created, its elements cannot be modified, added,
or removed. They are often used to represent fixed collections of items or when immutability
is required for security or performance reasons. Tuples are created by enclosing elements
within parentheses () and separating them with commas.
Tuples are ordered, immutable, and efficient data structures in Python. They are useful
when you need fixed collections of items, return multiple values from functions, or use
compound keys in dictionaries.
Features of Tuples:
• Ordered: Elements maintain the order in which they are defined.
• Immutable: Elements cannot be changed after creation (no modification, addition, or
deletion).
• Heterogeneous: Tuples can store different data types (int, float, string, list, etc.).
• Indexing and Slicing: Elements can be accessed using indexes [ ], and portions can be
retrieved using slicing [:].
• Faster Access: Since tuples are immutable, they are generally faster than lists in
execution.
• Hashable: Tuples can be used as dictionary keys or stored in sets, provided all their
elements are immutable.
Creating Tuples:

# Empty tuple
t1 = ()
# Tuple with integers
t2 = (1, 2, 3, 4)
# Tuple with mixed data types
t3 = (10, "Python", 3.14, True)
# Nested tuple
t4 = (1, (2, 3), [4, 5])
# Tuple without parentheses (implicit tuple packing)
t5 = 10, 20, 30
# Single-element tuple (comma required)
t6 = (5,)

Accessing Tuple Elements:

t = (10, 20, 30, 40, 50)


print(t[0]) # 10 (first element)
print(t[-1]) # 50 (last element)
print(t[1:4]) # (20, 30, 40) - slicing
Tuple Operations:

# Concatenation
a = (1, 2, 3)
b = (4, 5)
print(a + b) # (1, 2, 3, 4, 5)

# Repetition
print(a * 2) # (1, 2, 3, 1, 2, 3)

# Membership test
print(2 in a) # True
print(10 not in a) # True

# Length of tuple
print(len(a)) # 3

Immutability Example:

t = (1, 2, 3)
# t[1] = 5 #Error: 'tuple' object does not support item assignment

Tuple Methods:
Tuples support limited built-in methods compared to lists (since they are immutable):

t = (1, 2, 3, 2, 4, 2)
print([Link](2)) # 3 (number of times 2 appears)
print([Link](3)) # 2 (first occurrence of element 3)
Use Cases of Tuples:
Returning multiple values from a function:

def student():
return ("Alice", 20, "BCA")
name, age, course = student() # tuple unpacking
print(name) # Alice

Using as dictionary keys:

coordinates = {}
coordinates[(10, 20)] = "Point A"
coordinates[(30, 40)] = "Point B"
print(coordinates)
4. Mapping Data Types
In Python, mapping data types are used to store data in the form of key-value pairs.
Unlike sequences (lists, tuples, strings) which are indexed by a range of numbers, mappings
are indexed by unique keys. The most commonly used mapping type in Python is the
dictionary (dict).
A dictionary is an unordered, mutable, and indexed collection where each key is unique
and maps to a value. Keys must be immutable types (such as strings, numbers, or tuples), while
values can be of any data type.
4.1 Dictionary (dict)
A dictionary is used to store multiple values in a single variable, where each value is
accessed using a key rather than an index. It is represented using curly braces {} with key-
value pairs separated by a colon (:).
Example:

student = {
"name": "Arun",
"age": 21,
"department": "Computer Science",
"marks": [85, 90, 92]
}

Here:
• "name", "age", "department", "marks" → keys
• "Arun", 21, "Computer Science", [85, 90, 92] → values
Features of Dictionary
1. Unordered collection – The items are not stored in a specific order.
2. Mutable – Items can be added, modified, or deleted.
3. Key-based indexing – Each value is accessed using its unique key.
4. Keys must be immutable – Strings, numbers, or tuples can be used as keys, but lists
or dictionaries cannot.
5. Values can be of any type – int, str, list, tuple, dict, etc.
Creating Dictionaries

# Empty dictionary

d1 = {}

# Dictionary with integer keys

d2 = {1: "Apple", 2: "Banana"}

# Dictionary with mixed keys

d3 = {"name": "Kumar", 2: [1, 2, 3]}

# Using dict() function

d4 = dict(name="Kavi", age=25)

Accessing Dictionary Elements

student = {"name": "Arun", "age": 21}

print(student["name"]) # Arun
print([Link]("age")) # 21
Modifying Dictionary
Deleting Dictionary Elements
student = {"name": "Arun", "age": 21, "city": "Chennai"}

del student["city"] # Delete specific key


print(student) # {'name': 'Arun', 'age': 21}

[Link]() # Remove all items


print(student) # {}
Dictionary Methods

Method Description Example

[Link]() Returns all keys [Link]()

[Link]() Returns all values [Link]()

[Link]() Returns key-value pairs [Link]()

[Link](key) Returns value of a key [Link]("name")

[Link]() Updates dictionary with new items [Link]({"age": 22})

[Link](key) Removes a key-value pair [Link]("age")

[Link]() Removes all items [Link]()

[Link] in Python
In Python, a set is a built-in data type used to store a collection of items.
Unlike lists and tuples, sets are unordered and contain only unique elements.
For example, if you store duplicate values in a set, Python will automatically remove them.
A set is an unordered, mutable (changeable) collection of unique elements.
Creating Sets

# Creating a set using curly braces


s1 = {1, 2, 3, 4}
print(s1) # {1, 2, 3, 4}

# Creating a set using set() function


s2 = set([10, 20, 20, 30])
print(s2) # {10, 20, 30}

# Creating an empty set


s3 = set()
print(type(s3)) # <class 'set'>
Properties of Sets
• Unordered – Elements do not have a fixed position.
• Unique – Duplicates are removed automatically.
• Mutable – Elements can be added or removed.
• Unindexed – No indexing or slicing like lists.
s = {10, 20, 30, 30, 40}
print(s) # {40, 10, 20, 30} → duplicates removed, order not guaranteed
Accessing Elements in a Set
Since sets are unordered, elements cannot be accessed using an index.
Instead, we can use a loop.
fruits = {"apple", "banana", "cherry"}
for f in fruits:
print(f)
Set Operations
Python provides powerful set operations (similar to mathematical sets).
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
(a) Union: Combines all elements from both sets.
print(A | B) # {1, 2, 3, 4, 5, 6}
print([Link](B)) # {1, 2, 3, 4, 5, 6}
(b) Intersection : Returns only common elements.
print(A & B) # {3, 4}
print([Link](B)) # {3, 4}
(c) Difference: Elements present in one set but not in the other.
print(A - B) # {1, 2}
print(B - A) # {5, 6}
(d) Symmetric Difference: Elements present in either set but not in both.
print(A ^ B) # {1, 2, 5, 6}
print(A.symmetric_difference(B)) # {1, 2, 5, 6}
Method Description Example

add(x) Adds an element [Link](10)

update(iterable) Adds multiple elements [Link]([20,


30])

remove(x) Removes element, raises error if [Link](10)


not found
discard(x) Removes element, no error if not [Link](50)
found
pop() Removes and returns a random [Link]()
element
clear() Removes all elements [Link]()

copy() Returns a shallow copy new = [Link]()

Frozen Sets
• A frozenset is an immutable version of a set.
• Once created, elements cannot be added or removed.
fs = frozenset([1, 2, 3, 4])
print(fs) # frozenset({1, 2, 3, 4})
# [Link](5) Error (cannot modify)
Applications of Sets
Removing Duplicates
Membership Testing (fast lookup)
Mathematical Problems

Operators
An operator is a special symbol in Python that performs an operation on variables and
values.
For example:
a = 10
b=5
print(a + b) # 15
Here, + is an operator that adds two numbers.
Operators are the building blocks of expressions in Python.
Types of Operators in Python
Python supports the following categories of operators:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic Operators

Used for basic mathematical operations.

Operator Description Example Result


+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 3 3.333...
// Floor Division (quotient without decimal) 10 // 3 3
% Modulus (remainder) 10 % 3 1
** Exponentiation (power) 2 ** 3 8

Comparison (Relational) Operators


Used to compare two values. Returns a Boolean value (True/False).

Operator Meaning Example Result

== Equal to 5 == 5 True

!= Not equal to 5 != 3 True

> Greater than 10 > 7 True

< Less than 10 < 7 False

>= Greater than or equal 5 >= 5 True

<= Less than or equal 4 <= 6 True


Logical Operators
Used to combine conditional statements.

Operator Description Example Result

and True if both conditions are True (5 > 2 and 10 > 5) True

or True if at least one condition is True (5 > 10 or 2 < 5) True

not Negates the result not(5 > 2) False

Assignment Operators
Used to assign values to variables.

Operator Example Equivalent To

= x=5 Assign 5 to x

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

//= x //= 3 x = x // 3

%= x %= 3 x=x%3

**= x **= 3 x = x ** 3

x=5
x += 2
print(x) # 7
Bitwise Operators
Used for operations on binary numbers.

Operator Description Example Result

& Bitwise AND 5 & 3 → 0101 & 0011 0001 (1)

` ` Bitwise OR `5

^ Bitwise XOR 5 ^ 3 0110 (6)

~ Bitwise NOT ~5 -(5+1) = -6


<< Left Shift 5 << 1 10

>> Right Shift 5 >> 1 2

Membership Operators
Used to test if a value is present in a sequence (string, list, set, etc.).

Operator Example Result

in "a" in "apple" True

not in "x" not in "apple" True

Identity Operators
Used to test if two variables refer to the same object in memory.

Operator Example Result

is x is y True if both refer to same object

is not x is not y True if they are different objects

x = [1, 2, 3]
y=x
z = [1, 2, 3]

print(x is y) # True (same object)


print(x is z) # False (different objects, same content)
print(x == z) # True (values are equal)

Operator Precedence
When multiple operators are used in an expression, Python follows a priority order (just like
BODMAS in mathematics).
Order of Precedence (highest → lowest):
1. () → Parentheses
2. ** → Exponentiation
3. *, /, //, % → Multiplication & Division
4. +, - → Addition & Subtraction
5. ==, !=, >, <, >=, <= → Comparison
6. and, or, not → Logical operators
Example:
print(2 + 3 * 4) # 14 (multiplication first)
print((2 + 3) * 4) # 20 (parentheses first)

You might also like