PYTHON
PROGRAMMING
BASICS
Learn Python Programming
Comprehensive
Master the guide to Python fundamentals
Fundamentals
Perfect for Your
Start beginners andJourney
Python aspiring Today
developers
✓ Easy to understand ✓ Practical examples ✓ Step-by-step learning
PYTHON PROGRAMMING BASICS
Complete Learning Resource for All Beginners
PYTHON PROGRAMMING BASICS
Complete Guide with Examples & OOP Concepts
1. History of Python
Overview:
Python is a high-level, interpreted, general-purpose programming language created by
Guido van Rossum. Since its first release in February 1991, Python has evolved into one of
the most influential and widely-used programming languages in the world. The language is
known for its emphasis on code readability, simplicity, and elegance, making it a favorite
among beginners and experienced developers alike. Interestingly, the name “Python” was
not inspired by the snake, but rather by the British comedy series “Monty Python’s Flying
Circus.” This whimsical naming choice reflects the language’s philosophy of being fun and
approachable while maintaining professional capabilities. Today, Python is the dominant
language in artificial intelligence, data science, scientific computing, and is rapidly gaining
popularity in web development and automation.
1.1 The Birth of Python (1989-1991):
The story of Python begins in December 1989 when Guido van Rossum, a Dutch
programmer working at the Centrum Wiskunde & Informatica (CWI) in Amsterdam, started
developing Python as a hobby project during his Christmas break. Van Rossum had
previously worked on the ABC programming language and saw opportunities to create a
language that would be easier to use while maintaining the power of Unix/C development
tools. He sought to bridge the gap between shell scripting languages and more powerful
languages like C, creating something that was both accessible and capable.
Python drew inspiration from multiple sources. The clean syntax was influenced by ABC,
while functional programming concepts came from Lisp and Scheme. The result was a
language with a unique design philosophy that emphasized readability and elegance. The
first public release, Python 0.9.0, came out on February 20, 1991, on the Usenet newsgroup
[Link]. Remarkably, this early version already included many core features that remain
fundamental to Python today, including classes with inheritance, exception handling,
functions, and the modular design with modules. The early Python community was small but
enthusiastic, and the language quickly attracted interest from programmers seeking a more
readable alternative to Perl and C.
1.2 The Python 1.x Era (1994-2000):
As Python matured, it began to gain mainstream recognition. Python 1.0 was officially
released in January 1994, representing the first stable release and marking Python’s
transition from a hobby project to a serious programming language. This version introduced
several important features that significantly enhanced Python’s functional programming
capabilities. Lambda functions, which allow the creation of anonymous functions, were
added. The map(), filter(), and reduce() functions provided powerful functional programming
tools for working with collections. These additions made Python attractive to programmers
coming from languages like Lisp and Scheme.
Python 1.5, released in December 1997, introduced list comprehensions, a feature that
would become one of Python’s most beloved and characteristic syntactic elements. List
comprehensions provide a concise and readable way to create lists based on existing lists,
quickly becoming the preferred Python idiom for this operation. During this period, Python
began to gain significant traction in the open-source community. The first PythonConference
was held in 1997 (not PyOhio as commonly misremembered), attracting early adopters and
contributors. Universities began incorporating Python into computer science curricula. The
language expanded its reach into web development, system administration, automation
scripting, and data processing. Python’s gentle learning curve and practical focus made it
increasingly popular with non-computer scientists in fields like biology, physics, and finance.
1.3 The Python 2.x Era (2000-2010):
Python 2.0 was released in October 2000 and represented a major milestone in the
language’s development. One of the most significant additions was garbage collection for
handling cyclic references, which improved memory management. List comprehensions from
Python 1.5 were complemented by dictionary comprehensions. The release included
improvements to the type system and better support for Unicode, though Unicode support
would remain a source of complexity throughout Python 2.x.
Subsequent 2.x releases brought a wealth of new features. Decorators (Python 2.4, 2004)
provided an elegant way to modify function and class behavior. Generators (Python 2.2,
2001) enabled the creation of memory-efficient iterables for processing large datasets. The
‘with’ statement (Python 2.5, 2006) introduced context managers, making resource
management cleaner and safer. These features made Python increasingly versatile and
powerful. During this era, Python became the dominant language in scientific computing with
the emergence of NumPy and SciPy libraries. Web frameworks like Zope (early 2000s),
Django (2005), and Flask (2010) demonstrated Python’s suitability for web development.
Major technology companies began adopting Python: Google used it extensively, YouTube
was built with Python components, and Instagram used Django. The ecosystem flourished,
with PyPI (Python Package Index) growing to host thousands of third-party libraries.
However, over time, Python 2.x accumulated various inconsistencies and design quirks. The
print statement (print “hello”) was considered inelegant compared to other functions. String
and Unicode handling remained confusing. The lack of enforced indentation in some edge
cases caused issues. These limitations gradually became apparent to the core development
team.
1.4 The Python 3.x Era (2008-Present):
Python 3.0, released in December 2008, represented a fundamental redesign of the
language. Also known as “Py3k” or “Python 3000,” this version made breaking changes to
the language for the first time, prioritizing correctness and consistency over backward
compatibility. All text strings became Unicode by default, solving long-standing
internationalization issues. The print statement was replaced with the print() function, making
it consistent with other built-in functions. Old-style classes were removed in favor of new-
style classes. The syntax was cleaned up in numerous ways, and the standard library was
reorganized and streamlined, removing redundant modules and deprecated features. These
changes made Python 3 stricter and more consistent, though they required existing code to
be modified.
The transition from Python 2 to Python 3 was gradual and sometimes contentious. Python
2.7, released in July 2010, was positioned as the final Python 2 release. It received
continued security updates and bug fixes for a decade, with official support ending on
January 1, 2020. This extended support period allowed organizations time to migrate their
codebases. By 2020, the Python community had largely transitioned to Python 3, though
some legacy systems still relied on Python 2. Today, Python 3 is the only officially supported
version, with the version number continuing sequentially: 3.6, 3.7, 3.8, 3.9, 3.10, 3.11, 3.12,
and newer versions released annually.
Modern Python 3 has introduced numerous advanced features. F-strings (Python 3.6, 2016)
revolutionized string formatting with a concise and readable syntax. Async/await (Python 3.5,
2015) brought first-class support for asynchronous programming, enabling the development
of high-performance concurrent applications. Type hints (Python 3.5+) allow developers to
annotate their code with type information, improving IDE support and enabling better error
detection. The ‘walrus operator’ (:=, Python 3.8, 2019) and positional-only parameters
improved code expressiveness. Pattern matching, introduced in Python 3.10, brings more
expressive conditional logic. Python continues to evolve, with the Python Enhancement
Proposal (PEP) process ensuring community input on major changes. New versions are
released annually (typically in October), balancing new features with stability.
1.5 Why Python Became the Dominant Language:
1.5.1 Readable and Elegant Syntax:
Python’s syntax is clean and intuitive, closely resembling natural English. The enforced
indentation (unlike languages where it’s optional) makes code visually clear and encourages
readable programs. This accessibility makes Python an ideal language for beginners while
remaining powerful enough for experts. Code written in Python is often more concise than
equivalent programs in languages like Java or C++.
1.5.2 Rich Ecosystem and Libraries:
Python comes with an extensive standard library (often called “batteries included”) covering
file I/O, system calls, networking, data structures, and more. The Python Package Index
(PyPI) hosts millions of third-party packages for specialized tasks. This ecosystem means
that solutions to most programming problems already exist, allowing developers to focus on
their unique challenges rather than reinventing the wheel.
1.5.3 Versatility and Flexibility:
Python supports multiple programming paradigms: imperative (procedural), object-oriented,
functional, and aspect-oriented programming. This flexibility allows developers to use the
approach best suited to their problem. Python can be used for a tremendous range of
applications: web development, data analysis, artificial intelligence, scientific computing,
automation, system administration, desktop applications, and more. This versatility has
contributed to its widespread adoption across diverse industries.
1.5.4 Dominance in Artificial Intelligence and Data Science:
Python has become the de facto language for machine learning and artificial intelligence.
Libraries like TensorFlow and PyTorch (developed by Google and Facebook respectively)
are built for Python. Scikit-learn provides classical machine learning algorithms. NumPy and
Pandas are industry standards for numerical computing and data manipulation. Jupyter
notebooks have revolutionized interactive data analysis and scientific computing. As AI and
data science have become increasingly central to business and research, Python’s
dominance in these fields has driven its overall popularity. Every major technology company
invests heavily in Python tools and libraries for these applications.
1.5.5 Free and Open Source:
Python is completely free to use and modify. Its open-source nature means the community
can contribute improvements, report bugs, and propose new features. There are no licensing
costs or vendor lock-in, making it accessible to individuals, startups, and enterprises alike.
This freedom has been crucial to Python’s adoption in educational institutions and
developing countries.
1.5.6 Strong Community and Documentation:
The Python community is enormous, welcoming, and highly active. There are millions of
Stack Overflow answers, countless blogs, books, and online courses covering Python. The
official Python documentation is comprehensive and well-written. Online platforms like
PyCharm, Visual Studio Code, and Jupyter provide excellent development environments.
This abundance of learning resources makes Python an excellent choice for beginners.
1.6 Python in Industry:
Today, Python is used by virtually every major technology company: Google uses Python
extensively for internal tools and services; Netflix uses Python for machine learning and data
analysis; Spotify uses it for backend services; Uber, Instagram, Pinterest, Dropbox, and
Slack all rely on Python for critical components of their platforms. In academia, Python is the
standard language taught in computer science programs worldwide. In scientific research,
from biology to astronomy to climate science, Python is the lingua franca. Financial
institutions use Python for quantitative analysis and risk modeling. The rise of data science,
artificial intelligence, and machine learning has cemented Python’s position as the most
important programming language of our time.
1.7 Conclusion:
Python’s journey from a hobby project in 1989 to the world’s most influential programming
language is a testament to thoughtful language design and community-driven development.
Starting from Guido van Rossum’s vision of creating a language that emphasized readability
and elegance, Python has grown to serve billions of lines of code across every sector of the
technology industry and beyond. Whether you’re a beginner learning programming for the
first time or an experienced developer building sophisticated systems, Python offers the right
balance of simplicity and power. Understanding Python’s history helps appreciate the
thought behind its design choices and prepares you to master this remarkable language.
2. Variables
Variables are containers that store data values. In Python, you don't need to declare the
data type explicitly—Python determines it automatically based on the assigned value.
Understanding variables is fundamental to programming as they allow you to store, retrieve,
and manipulate data throughout your program.
2.1 Definition:
A variable is a named location in memory that holds a value. Think of it as a labeled box
where you can store information. Variable names must start with a letter or underscore,
followed by letters, numbers, or underscores. Python is case-sensitive, meaning 'Name' and
'name' are different variables. Valid variable names follow the snake_case convention
(lowercase with underscores) in Python.
2.2 Example with Detailed Explanation:
CODE OUTPUT
name = "Alice" # String Alice
variable
age = 25 # Integer 25
variable
height = 5.7 # Float 5.7
variable
is_student = True # Boolean True
variable
print(name, age, height, is_student) Alice 25 5.7 True
3. Data Types
Data types define the type of value a variable can hold. Different data types occupy different
amounts of memory and support different operations. Python is dynamically typed, meaning
the interpreter automatically determines the data type based on the value assigned.
3.1 String (str)
Strings are sequences of characters enclosed in single, double, or triple quotes. They are
used to store text and are immutable, meaning they cannot be changed after creation. You
can use various string methods like .upper(), .lower(), .replace(), .split(), etc. to manipulate
strings.
CODE OUTPUT
text = "Hello, Python!" Hello, Python!
print(len(text)) # Length 14
print(text[0:5]) # Slicing Hello
print([Link]()) # HELLO, PYTHON!
Uppercase
3.2 Integer (int)
Integers are whole numbers without decimal points. They can be positive, negative, or zero.
Python supports arbitrary precision integers, meaning you can work with very large numbers
without overflow. Integers are useful for counting, indexing, and mathematical operations.
CODE OUTPUT
num1 = 10 10
num2 = -5 -5
num3 = 0 0
print(num1 + num2) # Addition 5
print(num1 * num2) # -50
Multiplication
3.3 Float (float)
Floats are numbers with a decimal point. They are used for more precise numerical values
and are particularly useful in scientific and financial calculations. However, they have limited
precision due to how computers store decimal numbers in binary format.
CODE OUTPUT
price = 19.99 19.99
temperature = 36.5 36.5
print(price + temperature) 56.49
print(round(temperature, 1)) 36.5
3.4 Boolean (bool)
Booleans represent one of two values: True or False. They are crucial for conditional logic
and control flow. Any expression that evaluates to a truthy or falsy value can be used in a
boolean context.
CODE OUTPUT
is_adult = True True
is_married = False False
print(not is_married) # Logical True
NOT
print(5 > 3) # True
Comparison
3.5 Type Conversion (Casting):
You can convert one data type to another using built-in functions. This is useful when
reading input (always strings) or performing type-specific operations. Be careful with
conversions that may fail (e.g., converting non-numeric strings to integers).
CODE OUTPUT
num_str = "123" 123
num_int = int(num_str) # 123
String to Int
num_float = float("45.67") # 45.67
String to Float
str_num = str(100) # 100
Int to String
4. Operators
Operators are special symbols that perform operations on variables and values. Python
supports various types of operators for arithmetic, comparison, logical operations, and more.
Understanding operator precedence is important for correct results.
4.1 Arithmetic Operators
These operators perform mathematical calculations. The symbols include: + (addition), -
(subtraction), * (multiplication), / (division), // (floor division), % (modulus/remainder), and **
(exponentiation). Operator precedence follows standard mathematical rules (PEMDAS).
CODE OUTPUT
a = 10, b = 3
print(a + b) # Addition 13
print(a - b) # Subtraction 7
print(a * b) # 30
Multiplication
print(a / b) # Division 3.333...
print(a // b) # Floor 3
Division
print(a % b) # Modulus 1
print(a ** b) # 1000
Exponentiation
4.2 Comparison Operators
These operators compare two values and return a boolean (True or False). They are
essential for conditional statements and loops. The operators include ==, !=, >, <, >=, <=.
Note that == checks value equality while 'is' checks object identity.
CODE OUTPUT
x = 5
print(x == 5) # Equal to True
print(x != 3) # Not equal to True
print(x > 3) # Greater than True
print(x < 10) # Less than True
print(x >= 5) # Greater or True
equal
print(x <= 4) # Less or False
equal
4.3 Logical Operators
Logical operators combine boolean expressions. 'and' returns True if both conditions are
True, 'or' returns True if at least one is True, and 'not' negates the boolean value. These are
crucial for building complex conditional logic.
CODE OUTPUT
a = True, b = False
print(a and b) # Both True? False
print(a or b) # At least one True
True?
print(not a) # Negation False
print((5 > 3) and (2 < 4)) True
5. Conditional Statements
Conditional statements control the flow of execution based on conditions. They allow your
program to make decisions and execute different code blocks depending on whether
conditions are true or false. This is fundamental to creating dynamic, responsive programs.
5.1 if Statement
The 'if' statement executes a block of code only if a condition is True. Indentation is crucial in
Python—all code that should execute conditionally must be indented. The colon (:) marks
the beginning of an indented block.
CODE OUTPUT
age = 18
if age >= 18:
print("You are an adult") You are an adult
5.2 if-else Statement
The 'else' clause provides an alternative block to execute if the condition is False. It ensures
that one of the two blocks will always execute. Use it when you have exactly two possible
paths based on a condition.
CODE OUTPUT
marks = 45
if marks >= 50:
print("Pass") Fail
else:
print("Fail)
5.3 if-elif-else Statement
Use 'elif' (else-if) for multiple conditions. Each condition is checked in order, and only the first
True condition's block executes. This is more efficient than multiple separate 'if' statements
and makes the code cleaner.
CODE OUTPUT
grade = 75
if grade >= 90:
print("A Grade") C Grade
elif grade >= 80:
print("B Grade")
elif grade >= 70:
print("C Grade")
else:
print("D Grade")
6. Loops
Loops are used to execute a block of code repeatedly. They are essential for processing
collections of data, repeating operations, and automating tasks. Python supports two main
types of loops: 'for' and 'while'.
6.1 for Loop
The 'for' loop iterates through a sequence (list, string, range, etc.). It's perfect when you
know exactly how many times you want to iterate. The variable after 'for' takes the value of
each element in the sequence.
CODE OUTPUT
for i in range(1, 4):
print(f"Number: {i}") Number: 1
Number: 2
Number: 3
6.2 while Loop
The 'while' loop executes a block as long as a condition is True. It's useful when you don't
know the exact number of iterations needed. Be careful to ensure the condition becomes
False eventually, or you'll have an infinite loop.
CODE OUTPUT
count = 1
while count <= 3:
print(f"Count: {count}") Count: 1
count += 1 Count: 2
Count: 3
6.3 break and continue
'break' exits the loop immediately, while 'continue' skips the current iteration and moves to
the next. These are useful for controlling loop flow based on specific conditions.
CODE OUTPUT
# break example
for i in range(5): 0
if i == 3: 1
break 2
print(i)
7. Functions
A function is a reusable block of code that performs a specific task. Functions help you
organize code, reduce duplication, and make programs more modular. Functions are defined
using the 'def' keyword and can accept parameters and return values.
7.1 Basic Function
The simplest function takes no parameters and returns no value. It executes the same code
each time it's called.
CODE OUTPUT
def greet():
print("Hello, World!")
greet() Hello, World!
7.2 Function with Parameters
Functions can accept parameters (inputs) and return values (outputs). Parameters make
functions flexible and reusable. The 'return' statement sends a value back to the caller.
CODE OUTPUT
def add(a, b):
return a + b
result = add(5, 3)
print(f"Sum: {result}") Sum: 8
7.3 Default Parameters
You can specify default values for parameters. If a caller doesn't provide a value, the default
is used. This makes functions more flexible.
CODE OUTPUT
def power(base, exponent=2):
return base ** exponent
print(power(5)) # Uses 25
default
print(power(5, 3)) # Override 125
default
8. Data Structures
Data structures are containers for organizing and storing multiple values efficiently. Python
provides several built-in data structures, each with unique properties and use cases.
Choosing the right data structure is crucial for writing efficient code.
8.1 List
Lists are ordered, mutable collections of items enclosed in square brackets. Items can be of
different types, and you can modify lists after creation using methods like append(),
remove(), insert(), etc. Lists are zero-indexed, meaning the first element is at index 0. They
are perfect for storing sequences of data that you need to modify.
CODE OUTPUT
fruits = ["Apple", "Banana",
"Cherry"]
print(fruits[0]) # Apple
First item
print(len(fruits)) # 3
Length
[Link]("Date")
print(fruits) [..., "Date"]
List Methods and Functions:
append(item): Adds an item to the end of the list. Modifies the list in-place.
CODE OUTPUT
fruits = ["Apple", "Banana"]
[Link]("Cherry")
print(fruits) ["Apple", "Banana", "Cherry"]
extend(iterable): Adds multiple items from an iterable to the end of the list.
CODE OUTPUT
numbers = [1, 2, 3]
[Link]([4, 5, 6])
print(numbers) [1, 2, 3, 4, 5, 6]
insert(index, item): Inserts an item at a specific position. Items at that position and after
shift right.
CODE OUTPUT
numbers = [1, 2, 4, 5]
[Link](2, 3) # Insert 3
at index 2
print(numbers) [1, 2, 3, 4, 5]
remove(item): Removes the first occurrence of a specified item. Raises error if not found.
CODE OUTPUT
fruits = ["Apple", "Banana",
"Cherry"]
[Link]("Banana")
print(fruits) ["Apple", "Cherry"]
pop(index): Removes and returns the item at the specified index. Default is last item (-1).
CODE OUTPUT
numbers = [1, 2, 3, 4, 5]
last = [Link]() #
Remove last
print(last, numbers) 5, [1, 2, 3, 4]
index(item): Returns the index of the first occurrence of an item. Raises error if not found.
CODE OUTPUT
fruits = ["Apple", "Banana",
"Cherry"]
position = [Link]("Banana")
print(position) 1
count(item): Returns the number of times an item appears in the list.
CODE OUTPUT
numbers = [1, 2, 2, 3, 2, 4]
count_2 = [Link](2)
print(count_2) 3
sort(): Sorts the list in ascending order (or by a key function). Modifies list in-place.
CODE OUTPUT
numbers = [3, 1, 4, 1, 5]
[Link]()
print(numbers) [1, 1, 3, 4, 5]
reverse(): Reverses the order of items in the list. Modifies list in-place.
CODE OUTPUT
numbers = [1, 2, 3, 4, 5]
[Link]()
print(numbers) [5, 4, 3, 2, 1]
clear(): Removes all items from the list, making it empty.
CODE OUTPUT
numbers = [1, 2, 3, 4, 5]
[Link]()
print(numbers) []
copy(): Returns a shallow copy of the list. Useful to avoid modifying the original.
CODE OUTPUT
original = [1, 2, 3]
copied = [Link]()
[Link](4)
print(original, copied) [1, 2, 3], [1, 2, 3, 4]
8.2 Tuple
Tuples are ordered, immutable collections enclosed in parentheses. Once created, they
cannot be modified, making them useful for protecting data that shouldn't change. Use
tuples as dictionary keys or function return values. Their immutability also makes them
slightly faster than lists.
CODE OUTPUT
colors = ("Red", "Green", "Blue")
print(colors[0]) # Red
Red
print(len(colors)) 3
# colors[0] = "Yellow" # Error!
Tuple Methods and Functions:
count(item): Returns the number of times an item appears in the tuple.
CODE OUTPUT
numbers = (1, 2, 2, 3, 2, 4)
count_2 = [Link](2)
print(count_2) 3
index(item): Returns the index of the first occurrence of an item. Raises error if not found.
CODE OUTPUT
colors = ("Red", "Green", "Blue")
position = [Link]("Green")
print(position) 1
len(tuple): Built-in function that returns the number of items in the tuple.
CODE OUTPUT
colors = ("Red", "Green", "Blue")
print(len(colors)) 3
tuple() constructor: Converts other iterables into tuples. Useful for converting lists to
immutable tuples.
CODE OUTPUT
numbers = [1, 2, 3]
tuple_numbers = tuple(numbers)
print(tuple_numbers) (1, 2, 3)
8.3 Dictionary
Dictionaries are unordered, mutable collections of key-value pairs. They are optimized for
fast lookups by key and are useful for storing related data. Keys must be unique and
immutable (usually strings or numbers), while values can be any type. Starting from Python
3.7, dictionaries maintain insertion order.
CODE OUTPUT
student = {"name": "Alice", "age":
20, "city": "NYC"}
print(student["name"]) Alice
student["age"] = 21
student["major"] = "CS" # Add new
key
Dictionary Methods and Functions:
keys(): Returns a view of all the keys in the dictionary. Useful for iterating over keys.
CODE OUTPUT
student = {"name": "Alice", "age":
20}
keys = [Link]()
print(keys) dict_keys([...])
for key in [Link](): name
print(key) age
values(): Returns a view of all the values in the dictionary. Useful for iterating over values.
CODE OUTPUT
student = {"name": "Alice", "age":
20}
values = [Link]()
print(values) dict_values([...])
for value in [Link](): Alice
print(value) 20
items(): Returns a view of all key-value pairs as tuples. Perfect for iterating over both keys
and values.
CODE OUTPUT
student = {"name": "Alice", "age":
20}
for key, value in [Link]():
print(f"{key}: {value}") name: Alice
age: 20
get(key, default): Returns the value for a key if it exists, otherwise returns the default value.
CODE OUTPUT
student = {"name": "Alice", "age":
20}
print([Link]("name")) Alice
print([Link]("city", Unknown
"Unknown"))
pop(key, default): Removes and returns the value for a key. Returns default if key doesn't
exist.
CODE OUTPUT
student = {"name": "Alice", "age":
20}
age = [Link]("age")
print(age, student) 20, {"name": "Alice"}
update(other_dict): Updates the dictionary with key-value pairs from another dictionary or
iterable.
CODE OUTPUT
student = {"name": "Alice", "age":
20}
[Link]({"city": "NYC",
"age": 21})
print(student) {"name": "Alice", "age": 21, "city":
"NYC"}
clear(): Removes all key-value pairs from the dictionary, making it empty.
CODE OUTPUT
student = {"name": "Alice", "age":
20}
[Link]()
print(student) {}
copy(): Returns a shallow copy of the dictionary. Useful to avoid modifying the original.
CODE OUTPUT
original = {"name": "Alice", "age":
20}
copied = [Link]()
copied["city"] = "NYC"
print(original, copied) {...}, {...}
setdefault(key, default): Returns the value if key exists, otherwise sets it to default and
returns default.
CODE OUTPUT
student = {"name": "Alice", "age":
20}
city = [Link]("city",
"NYC")
print(student) {..., "city": "NYC"}
8.4 Set
Sets are unordered collections of unique items. Duplicates are automatically removed. Sets
are useful for removing duplicates from lists and performing set operations like union,
intersection, and difference. Sets are mutable but can only contain immutable items.
CODE OUTPUT
numbers = {1, 2, 3, 2, 1} #
Duplicates removed
print(numbers) {1, 2, 3}
print(len(numbers)) 3
4 in numbers # Check membership False
Set Methods and Functions:
add(item): Adds a single item to the set. If item already exists, the set remains unchanged.
CODE OUTPUT
numbers = {1, 2, 3}
[Link](4)
[Link](2) # Already exists
print(numbers) {1, 2, 3, 4}
remove(item): Removes a specific item from the set. Raises error if item doesn't exist.
CODE OUTPUT
numbers = {1, 2, 3, 4}
[Link](3)
print(numbers) {1, 2, 4}
discard(item): Removes an item if it exists. Does not raise error if item doesn't exist.
CODE OUTPUT
numbers = {1, 2, 3, 4}
[Link](5) # No error
[Link](3)
print(numbers) {1, 2, 4}
pop(): Removes and returns an arbitrary item from the set. Raises error if set is empty.
CODE OUTPUT
numbers = {1, 2, 3, 4}
item = [Link]() # Removes
random item
print(item, numbers) # Varies
clear(): Removes all items from the set, making it empty.
CODE OUTPUT
numbers = {1, 2, 3, 4}
[Link]()
print(numbers) set()
union(other_set): Returns a new set with all items from both sets.
CODE OUTPUT
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = [Link](set2)
print(result) {1, 2, 3, 4, 5}
intersection(other_set): Returns a new set with items common to both sets.
CODE OUTPUT
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = [Link](set2)
print(result) {3}
difference(other_set): Returns items in the first set but not in the second set.
CODE OUTPUT
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = [Link](set2)
print(result) {1, 2}
copy(): Returns a shallow copy of the set. Useful to avoid modifying the original.
CODE OUTPUT
original = {1, 2, 3}
copied = [Link]()
[Link](4)
print(original, copied) {1, 2, 3}, {1, 2, 3, 4}
9. Object-Oriented Programming (OOP)
OOP is a programming paradigm based on objects and classes. It helps organize code in a
modular, reusable way. OOP supports inheritance, encapsulation, polymorphism, and
abstraction, making code more maintainable and scalable.
9.1 Classes and Objects
A class is a blueprint for creating objects. An object is an instance of a class. Classes define
the structure (attributes) and behavior (methods) that objects will have. The '__init__' method
is the constructor, called when an object is created.
CODE OUTPUT
class Car:
def __init__(self, brand,
color):
[Link] = brand
[Link] = color
car = Car("Toyota", "Red") Brand: Toyota, Color: Red
9.2 Attributes and Methods
Attributes are variables inside a class (data), and methods are functions inside a class
(behavior). Use 'self' to access attributes and methods within a class. Instance attributes
belong to individual objects, while class attributes are shared among all instances.
CODE OUTPUT
class Student:
def __init__(self, name, age):
[Link] = name #
Attribute
def study(self): # Method
print(f"{[Link]} is Bob is studying
studying")
9.3 Inheritance
Inheritance allows a class (child/derived class) to inherit attributes and methods from another
class (parent/base class). This promotes code reuse and establishes a hierarchy. Use the
'super()' function to call parent class methods.
CODE OUTPUT
class Animal:
def speak(self):
return "makes a sound"
class Dog(Animal): # Inherits
from Animal
def speak(self):
return "barks" Buddy barks
9.4 Encapsulation
Encapsulation is bundling data (attributes) and methods together and hiding internal details.
Use private attributes (prefixed with underscore) to restrict direct access. This protects data
integrity and allows controlled access through methods.
CODE OUTPUT
class BankAccount:
def __init__(self, balance):
self._balance = balance #
Private
def deposit(self, amount):
self._balance += amount New balance: 1500
9.5 Polymorphism
Polymorphism allows different classes to use methods with the same name. Each class
implements the method in its own way. This enables writing generic code that works with
objects of different types.
CODE OUTPUT
class Cat: #
Different classes
def sound(self):
return "Meow" Meow
class Dog:
def sound(self):
return "Woof" Woof
Summary
Variables & Data Types: Fundamental building blocks for storing and managing data in your
programs.
Operators: Used for arithmetic, comparison, and logical operations to manipulate data and
make decisions.
Control Flow: Conditionals and loops control the order and repetition of program execution.
Functions: Reusable blocks of code that promote modularity and reduce duplication.
Data Structures: Lists, tuples, dictionaries, and sets organize data efficiently with
comprehensive methods for manipulation.
OOP Concepts: Classes, inheritance, encapsulation, polymorphism, and abstraction enable
modular, scalable design.