Python Unit 1 Notes
Python Unit 1 Notes
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.
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.7 2018 Data classes (dataclass), context variables, time functions with
nanosecond precision.
Python 3.10 2021 Structural pattern matching (match statement), precise error
messages.
Python 3.13 2024 Further speed improvements, better Unicode, improved type
hints and modules.
• 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
x = 10 # Positive integer
y = -25 # Negative integer
z=0 # Zero
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)
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
numbers = [1, 2, 3, 4, 5]
mixed = [10, "Python", 3.14, True]
2. Accessing Elements
3. Modifying Elements
numbers[2] = 30
print(numbers) # Output: [1, 2, 30, 4, 5]
4. Adding Elements
6. Slicing Lists
[Link] Lists
# 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,)
# 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
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 = {}
d4 = dict(name="Kavi", age=25)
print(student["name"]) # Arun
print([Link]("age")) # 21
Modifying Dictionary
Deleting Dictionary Elements
student = {"name": "Arun", "age": 21, "city": "Chennai"}
[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
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
== Equal to 5 == 5 True
and True if both conditions are True (5 > 2 and 10 > 5) True
Assignment Operators
Used to assign values to variables.
= 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.
` ` Bitwise OR `5
Membership Operators
Used to test if a value is present in a sequence (string, list, set, etc.).
Identity Operators
Used to test if two variables refer to the same object in memory.
x = [1, 2, 3]
y=x
z = [1, 2, 3]
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)