What is Python?
Python is a high-level, interpreted, general-purpose programming language. It was
created by Guido van Rossum and released in 1991. Python is known for its clear syntax,
readability, and versatility, making it ideal for beginners and experienced programmers
alike.
Today, Python is widely used in various fields, including:
• Web development (e.g., Django, Flask)
• Data science and machine learning (e.g., Pandas, NumPy, Scikit-learn)
• Automation and scripting
• Software development
• Artificial Intelligence
• Game development
• Internet of Things (IoT)
Features of Python
1. Easy to Learn and Use
Python has a simple syntax similar to English, which makes it easy for beginners to learn
and understand quickly.
Example:
print("Hello, World!")
No need for complex syntax or semicolons; the code is readable and clean.
2. Interpreted Language
Python is an interpreted language, which means the code is executed line-by-line. It does
not need to be compiled before execution like C or Java.
Benefits:
• Easier debugging
• Faster testing and development
• Platform-independent code execution
3. Dynamically Typed
In Python, you do not need to declare data types for variables. The type is automatically
inferred at runtime.
Example:
x = 10 # Integer
x = "Hello" # Now a String
This allows flexibility, but also requires care to avoid type errors at runtime.
4. High-Level Language
Python abstracts away low-level details like memory management and hardware operations,
letting developers focus on problem-solving and application logic.
Example: You don’t need to manage memory allocation or garbage collection manually.
5. Extensive Standard Library
Python comes with a large library of built-in modules for tasks like file handling, regular
expressions, networking, and more.
Examples of standard libraries:
• math – mathematical functions
• datetime – date and time operations
• os – interacting with the operating system
• re – regular expressions
6. Platform Independent
Python code can be written once and run on multiple operating systems (Windows, Linux,
macOS) without modification.
Example:
# cross-platform file operations
open("myfile.txt", "r")
Just make sure the required Python interpreter is installed.
7. Object-Oriented Programming (OOP) Support
Python supports classes, objects, inheritance, polymorphism, and encapsulation, making it
suitable for structured and modular programming.
8. Automatic Memory Management
Python has a built-in garbage collector that handles memory allocation and deallocation
automatically.
This eliminates memory leaks and makes the code cleaner and more efficient.
9. Portable and Embeddable
Python programs can be moved from one machine to another without modification
(platform-independent). Python can also be embedded in other languages like C or C++.
Example: You can run a .py file on Windows, Linux, or macOS with the same result.
10. Extensive Community and Support
Python has a massive global community of developers, educators, and researchers, providing:
• Tutorials and forums
• Free tools and resources
• Open-source libraries
What Are Identifiers?
In Python, identifiers are the names used to identify:
• Variables
• Functions
• Classes
• Modules
• Objects
They are the user-defined names that help us label and refer to data or functions in a program.
Purpose of Identifiers
Identifiers allow us to:
• Store data in variables (name = "Alice")
• Reuse code with functions (def greet():)
• Build custom logic with classes (class Student: )
In short, identifiers are fundamental building blocks for writing Python programs.
Rules for Naming Identifiers
To define a valid identifier in Python, follow these rules:
Rule # Description Example
1 Must start with a letter (A–Z or a–z) or an underscore (_) only name, _value
2 Can contain letters, digits (0–9), and underscores marks_123 , data_2
3 Cannot start with a digit 1name
4 Cannot use keywords (reserved words in Python) for, if, class
5 Case-sensitive – Total and total are different Name ≠ name
Keywords vs Identifiers
• Keywords: Reserved by Python, cannot be used as identifiers.
o Examples: if , else, for, while, def, class, return , etc.
o Use import keyword; print(keyword.kwlist) to view all keywords.
• Identifiers: User-defined names following the above rules.
Valid and Invalid Identifier Examples
✅ Valid Identifiers:
student_name = "Alice"
_age = 25
marks1 = 95
Roll_No = 101
❌ Invalid Identifiers:
1name = "Bob" # starts with a digit
class = "Math" # 'class' is a keyword
student-name = "John" # contains hyphen
@data = 99 # contains special character
Single Leading Underscore
_variable
This is a "protected" variable.
• Meant to be internal use only.
• Signals to other programmers: “Don’t use this outside of the class/module.”
• Not enforced by Python (still accessible).
2. __variable Double Leading Underscore
Name mangling for class attributes.
• Python changes the name internally to _ClassName__variable.
• Used to avoid name clashes in subclasses (stronger privacy).
What is a Data Type?
A data type is a classification that specifies which type of value a variable holds and what
operations can be performed on it. In Python, everything is an object, and every object has:
• An identity
• A type
• A value
Python uses dynamic typing, meaning you don’t have to declare the type of a variable
explicitly — the interpreter assigns it at runtime.
Categories of Data Types in Python
Python provides several built-in data types, which can be grouped into:
1. Numeric Types
2. Text Type
3. Sequence Types
4. Set Types
5. Mapping Type
6. Boolean Type
7. Binary Types
8. None Type
1️ Numeric Data Types
Used to store numerical values.
A. int (Integer)
• Represents whole numbers without a decimal point.
• No limit to the size (bounded by memory).
a = 10
b = -250
B. float (Floating-point number)
• Represents real numbers with a decimal.
• Precision depends on system architecture (typically 64-bit).
pi = 3.14159
C. complex
• Used to represent complex numbers of the form a + bj, where a is the real part and b
is the imaginary part.
z = 2 + 3j
2 Text Type
str (String)
• Represents a sequence of Unicode characters.
• Enclosed in single ' ', double " ", or triple quotes ''' ''' / """ """ for multi-line.
• Supports slicing, indexing, concatenation, and many string methods.
name = "Python"
print(name[0]) # Output: 'P'
print(name.upper()) # Output: 'PYTHON'
3️ Sequence Types
Sequence types store ordered collections of items.
A. list
• Mutable (can change items)
• Ordered and allows duplicate elements
• Items can be of mixed types
colors = ['red', 'green', 'blue']
colors.append('yellow')
B. tuple
• Immutable (cannot change after creation)
• Faster than lists due to immutability
coordinates = (10, 20)
C. range
• Represents a sequence of numbers, mostly used in loops
r = range(0, 10, 2) # 0, 2, 4, 6, 8
4️ Set Types
Sets are unordered collections of unique elements.
A. set
• Mutable, unordered, no duplicates
= {1, 2, 3, 3}
print(s) # Output: {1, 2, 3}
B. frozenset
• Immutable version of a set (cannot be changed after creation)
fs = frozenset([1, 2, 3])
Set Operations:
• union(), intersection(), difference(), symmetric_difference()
5️ Mapping Type
dict (Dictionary)
• Stores data as key-value pairs
• Keys must be unique and immutable
• Values can be of any type
student = {'name': 'Alice', 'age': 21}
print(student['name']) # Output: Alice
Dictionary Methods:
• get(), update(), keys(), values(), items(), pop()
6️ Boolean Type
bool
• Represents one of two values: True or False
• Used in conditions and logic
• Subclass of int (True == 1 , False == 0 )
x = True
y = False
print(x + y) # Output: 1
7️ Binary Types
Used for handling binary data like images, files, etc.
• bytes: immutable sequence of bytes
• bytearray: mutable version of bytes
• memoryview: memory-efficient view of binary data
b = bytes([65, 66, 67]) # Output: b'ABC'
ba = bytearray([65, 66, 67]) # Mutable
8️ NoneType
None
• Represents a null or no value.
• Commonly used as a default return value or placeholder.
x = None
print(type(x)) # Output: <class 'NoneType'>
Types of Control Structures
Control structures in Python can be classified into:
1. Conditional (Decision-Making)
2. Looping (Repetition/Iteration)
3. Branch Control (Jump statements)
1️ Conditional Statements (Decision-Making)
Used to make decisions based on conditions.
🔸 A. if Statement
Executes a block of code if the condition is true.
x = 10
if x > 0:
print("Positive number")
🔸 B. if-else Statement
Provides two branches: if the condition is true, execute one block; otherwise, another.
if x % 2 == 0:
print("Even")
else:
print("Odd")
🔸 C. if-elif-else Ladder
Used when multiple conditions are checked in sequence.
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 60:
print("Grade C")
else:
print("Fail")
🔸 D. Nested if Statements
An if statement inside another if .
age = 20
if age > 18:
if age < 25:
print("Young adult")
2️ Looping Structures (Iteration)
Loops are used to execute a block of code repeatedly.
A. while Loop
Executes as long as the condition is True.
count = 0
while count < 5:
print(count)
count += 1
Use case: when the number of iterations is not known in advance.
B. for Loop
Used to iterate over a sequence (list, string, range, etc.).
for i in range(1, 6):
print(i)
Use case: when the number of iterations is known or iterable is provided.
C. Nested Loops
A loop inside another loop.
for i in range(1, 4):
for j in range(1, 3):
print(i, j)
3️ Loop Control Statements (Branching)
Used to alter the normal flow of a loop.
🔸 A. break
Terminates the loop prematurely.
for i in range(10):
if i == 5:
break
print(i)
🔸 B. continue
Skips the current iteration and goes to the next.
for i in range(5):
if i == 2:
continue
print(i)
🔸 C. pass
A null statement. Used when a statement is syntactically required but no action is needed.
for i in range(5):
if i == 3:
pass # Do nothing
print(i)
Python List
A list is a built-in Python data structure that represents an ordered, mutable, and indexable
collection of elements. Lists are one of the most commonly used data types in Python.
🔹 Key Characteristics of a List
Property Description
Ordered Items are stored in the order you insert them.
Mutable You can add, remove, or change elements after creation.
Allows Duplicates Lists can contain the same item multiple times.
Indexable You can access elements using their position (starting from index 0).
Mixed Data Types A list can contain different types: integers, strings, even other lists.
Example:
fruits = ['apple', 'banana', 'cherry']
Built-in List Functions
These are global functions that operate on lists but are not methods of the list object.
1. len(list)
• Returns: The number of items in the list.
fruits = ['apple', 'banana', 'cherry']
print(len(fruits)) # Output: 3
2. max(list)
• Returns: The largest item in the list.
• All elements must be of comparable types (e.g., all numbers or all strings).
numbers = [10, 20, 5]
print(max(numbers)) # Output: 20
3. min(list)
• Returns: The smallest item.
print(min(numbers)) # Output: 5
4. sum(list)
• Returns: The sum of all numeric elements.
print(sum(numbers)) # Output: 35
5. sorted(list)
• Returns: A new list containing all items in ascending order.
• Original list is not modified.
numbers = [3, 1, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # [1, 2, 3]
print(numbers) # [3, 1, 2] — original unchanged
6. list(iterable)
• Creates a list from any iterable (string, tuple, etc.)
s = "abc"
print(list(s)) # ['a', 'b', 'c']
List Methods
These are functions attached to list objects, used as list.method().
1. append(x)
• Adds an item to the end of the list.
• Operates in-place (modifies original list).
fruits = ['apple']
fruits.append('banana')
print(fruits) # ['apple', 'banana']
2. extend(iterable)
• Adds all elements from another iterable (list, tuple, string) to the current list.
• Extends the list, doesn't nest it.
fruits = ['apple']
fruits.extend(['banana', 'cherry'])
print(fruits) # ['apple', 'banana', 'cherry']
3. insert(index, element)
• Inserts an element at a specific index.
• Shifts existing elements right.
fruits = ['apple', 'cherry']
fruits.insert(1, 'banana')
print(fruits) # ['apple', 'banana', 'cherry']
4. remove(value)
• Removes the first occurrence of the specified value.
• Raises ValueError if the value is not present.
fruits = ['apple', 'banana', 'banana']
fruits.remove('banana')
print(fruits) # ['apple', 'banana']
5. pop([index])
• Removes and returns item at given index.
• If index is not provided, removes last item.
• Raises IndexError if list is empty or index is out of range.
fruits = ['apple', 'banana', 'cherry']
item = fruits.pop(1)
print(item) # 'banana'
print(fruits) # ['apple', 'cherry']
6. clear()
• Removes all items from the list.
fruits = ['apple', 'banana']
fruits.clear()
print(fruits) # []
7. index(value[, start[, end]])
• Returns the index of the first matching value.
• Optional start/end restrict the search.
• Raises ValueError if not found.
fruits = ['apple', 'banana', 'cherry']
print(fruits.index('banana')) # 1
8. count(value)
• Returns the number of occurrences of the given value.
fruits = ['banana', 'apple', 'banana']
print(fruits.count('banana')) # 2
9. sort(reverse=False, key=None)
• Sorts the list in-place (modifies the original).
• Accepts optional reverse=True or key function.
numbers = [3, 1, 2]
numbers.sort()
print(numbers) # [1, 2, 3]
numbers.sort(reverse=True)
print(numbers) # [3, 2, 1]
10. reverse()
• Reverses the list in-place.
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits) # ['cherry', 'banana', 'apple']
11. copy()
• Returns a shallow copy of the list.
original = [1, 2, 3]
copied = original.copy()
print(copied) # [1, 2, 3]
What is a Set?
A set is a built-in Python data type that represents an unordered, mutable collection of
unique elements.
🔹 Key Characteristics of a Set
Property Description
The items do not maintain insertion order (though in CPython 3.7+, insertion
Unordered
order is preserved, but this is not guaranteed behavior).
Mutable You can add or remove elements after the set is created.
No Duplicates All elements in a set are unique.
Unindexed You cannot access elements using an index like in lists or tuples.
Only Hashable Elements must be hashable (e.g., numbers, strings, tuples). Lists or other sets
Elements cannot be set elements.
Set Functions
1. len(set)
• Returns the number of elements in the set.
s = {1, 2, 3}
print(len(s)) # 3
2. set(iterable)
• Converts iterable to a set, removing duplicates.
s = set([1, 2, 2, 3])
print(s) # {1, 2, 3}
Set Methods
Method Modifies Set? Description
1. add(elem)
• – Adds an element (if not already present).
s = {1, 2}
s.add(3)
print(s) # {1, 2, 3}
2. remove(elem)
• Removes element. ❗ Raises KeyError if not found.
s.remove(2)
3. discard(elem)
• Removes element if present. No error if not found.
python
CopyEdit
s.discard(10) # No error
4. pop()
• – Removes and returns an arbitrary element.
s = {1, 2, 3}
s.pop() # Removes random item
5. clear()
• – Empties the set.
s.clear()
6. copy()
• Returns a shallow copy.
s2 = s.copy()
7. update(other_set)
• Adds elements from another set or iterable.
s = {1}
s.update([2, 3])
# s becomes {1, 2, 3}
8. union(other_set)
• Returns a new set with all elements from both.
s1 = {1, 2}
s2 = {2, 3}
print(s1.union(s2)) # {1, 2, 3}
9. intersection(other_set)
• Returns new set of common elements.
s1 = {1, 2, 3}
s2 = {2, 3, 4}
print(s1.intersection(s2)) # {2, 3}
10. difference(other_set)
• Returns new set of elements in s1 but not in s2 .
s1 = {1, 2, 3}
s2 = {2, 4}
print(s1.difference(s2)) # {1, 3}
11. symmetric_difference(other_set)
• Returns new set of elements in either set but not both.
{1, 2, 3}.symmetric_difference({2, 3, 4}) # {1, 4}
12. issubset(other_set)
• Checks if all elements of set are in other_set .
python
CopyEdit
{1, 2}.issubset({1, 2, 3}) # True
13. issuperset(other_set)
• Checks if set contains all elements of other_set .
14. isdisjoint(other_set)
• Returns True if sets have no common elements.
{1, 2}.isdisjoint({3, 4}) # True
🔸 In-place Versions (Modify original set):
• intersection_update()
• difference_update()
• symmetric_difference_update()
What is a Dictionary?
A dictionary (or dict) in Python is a built-in data type that stores data as key-value pairs. It is
like a real-world dictionary, where a word (key) maps to its definition (value).
🔹 Key Characteristics of a Dictionary
Property Description
Unordered (pre-3️.7️) / Ordered From Python 3.7 onward, dictionaries maintain the
(Python 3️.7️+) insertion order.
Mutable You can add, update, or delete key-value pairs.
Keys must be unique A key cannot appear more than once.
Key types must be hashable Strings, numbers, and tuples are common key types.
Values can be any type Values can be lists, strings, numbers, other dicts, etc.
Dictionary Functions
1. len(dict)
• Number of key-value pairs.
len(person) # 2
2. dict() – Constructor
• Creates a new dictionary from mappings or keyword args.
dict(name="Bob", age=30)
Dictionary Methods
1. get(key[, default])
• Returns value for key. Returns default if key not found.
person.get('age') # 25
person.get('gender', 'N/A') # 'N/A'
2. keys()
• Returns a view object of all keys.
person.keys() # dict_keys(['name', 'age'])
3. values()
• Returns view object of all values.
4. items()
• Returns view object of (key, value) pairs.
5. pop(key[, default])
• Removes key and returns value.
• Returns default or raises KeyError if key not found.
person.pop('age') # 25
6. popitem()
• Removes and returns the last inserted key-value pair (LIFO).
person.popitem()
7. update([other])
• Adds or updates from another dict or iterable of pairs.
person.update({'age': 26, 'gender': 'Female'})
8. clear()
• Removes all items from the dictionary.
9. copy()
• Shallow copy of dictionary.
10. setdefault(key[, default])
• Returns value of key if exists. If not, inserts with default .
d = {}
d.setdefault('name', 'John') # {'name': 'John'}
Mutable vs Immutable Objects in Python
In Python, everything is an object, and every object has a type. One of the most important
distinctions between objects is whether they are mutable or immutable.
Term Meaning
Mutable Can be changed after it's created (in-place modification is allowed).
Immutable Cannot be changed after it's created (any "change" creates a new object).
Examples of Mutable and Immutable Types
Mutable Types Immutable Types
list int , float
dict str
set tuple
bytearray frozenset
user-defined class (by default) bool , complex
Mutable Example
my_list = [1, 2, 3]
my_list[0] = 100
print(my_list) # [100, 2, 3] — modified in place
• The object my_list is changed without creating a new list.
• Its memory address (id) stays the same.
print(id(my_list))
Immutable Example
my_str = "hello"
my_str = my_str.upper()
print(my_str) # 'HELLO'
• Strings are immutable: my_str.upper() returns a new string.
• The original "hello" is not modified.
• id(my_str) before and after would be different.