Lesson No 1 (Shreya)
Lesson No 1 (Shreya)
Python is a high-level, interpreted programming language known for its simplicity, readability, and
flexibility. It was created by Guido van Rossum and first released in 1991. Python is widely used in
various fields like web development, data science, automation, artificial intelligence, and more.
2. Key Features of Python:
Simplicity: Python has a simple, easy-to-understand syntax that mimics English, making it
beginner-friendly.
Interpreted Language: Python is interpreted, meaning you can run each line of code as soon
as you write it, making debugging easier.
Dynamically Typed: You don’t need to declare the type of a variable in Python. The
interpreter infers the type at runtime.
Object-Oriented: Python supports object-oriented programming (OOP), allowing code to be
more modular and reusable.
Portability: Python code can be run on different operating systems without modification.
Extensive Libraries and Frameworks: Python has a vast range of libraries and frameworks,
which make it ideal for various tasks, from data manipulation to machine learning.
3. Popular Libraries and Frameworks:
NumPy, Pandas: For data manipulation and numerical analysis.
Matplotlib, Seaborn: For data visualization.
4. Applications of Python:
Web Development: Python frameworks like Django and Flask are widely used for backend
development.
Data Science and Machine Learning: Python is a go-to language for data analysis, modeling,
and prediction due to libraries like Pandas, NumPy.
Automation: With simple scripts, Python can automate repetitive tasks like file handling,
web scraping, and more.
Game Development: Python can be used for simple 2D game development using libraries
like Pygame.
5. Why Learn Python?
Versatility: Python can be used in multiple domains like web development, AI, data science,
and more.
Strong Community Support: A large number of developers use Python, ensuring abundant
resources and tutorials for learners.
Cross-platform: Code written in Python can run across different operating systems without
modification.
A. Data Types in Python
Data types specify the kind of data that can be stored and manipulated within a program. Python
supports a variety of data types, which can be classified into the following categories:
list: Lists are ordered collection of elements. The elements can be of any type like strings,
numbers, booleans, lists, tuples etc. Index is the location where the list element is present in
the list(starts from 0)
my_mixed_list = [1, 1.1, 'a', True]
my_mixed_list
functions used in list : type() , len() ,
tuple: Represents an ordered, immutable collection of items. Once defined, the values in a
tuple cannot be changed.
coordinates = (10, 20)
Think of a tuple like a container that holds different items, but after you pack the container,
you can't take things out or add new ones.
dict: Represents a collection of key-value pairs. Dictionaries are unordered and mutable.
my_dict = {"name": "Alice", "age": 25}
set: Represents an unordered collection of unique elements.
unique_numbers = {1, 2, 3}
Functions are a block of reusable code that performs a specific task. Python functions can be
categorized into two main types: user-defined functions and library functions (or built-in functions).
User-Defined Functions:
These are the functions defined by the user to perform specific tasks as needed in their programs. A
user-defined function is declared using the def keyword, followed by the function name,
parentheses, and a colon.
return a + b
result = add_nos(3, 5)
output will be –
Python comes with several built-in functions that are readily available to perform common tasks. You
don't need to define these functions; you can use them directly. Some of the commonly used built-in
functions include:
print("Hello, World!")
2. len() – Returns the length (number of items) in an object like a string, list, etc.
No Need for Implementation: Library functions are pre-written, so you don’t need to write
them from scratch.
Time-Saving: They help save development time by performing common operations
efficiently.
Standardized and Reliable: These functions are thoroughly tested and optimized, making
them reliable to use.
Python provides several built-in data structures, which are essential for organizing and storing data
efficiently. These include Lists, Strings, Tuples, Dictionaries, and Sets. Each has distinct
characteristics and serves different purposes in programming.
1. List
A List is an ordered, mutable (changeable) collection of items in Python. Lists can contain items of
different data types (e.g., integers, strings, or even other lists). Lists are indexed, meaning each
element can be accessed using its position (starting from 0).
my_list=["mad","sad","dad","pad"]
my_list[3]
output: ‘pad’
Mutable: Items in a list can be changed after the list is created (i.e., elements can be added,
modified, or removed).
my_list=["mad","sad","dad","pad"]
my_list.append("so glad")
my_list
output: ['mad', 'sad', 'dad', 'pad', 'so glad', 'so glad'].
Heterogeneous: Lists can contain elements of different types (e.g., numbers, strings, other
lists)
My_list=[“madhura”, 1.45]
Indexable: Each item has a unique index, allowing access to individual elements.
2. String
A String is a sequence of characters enclosed in single, double, or triple quotes. Although strings are
collections of characters, they are immutable, meaning their values cannot be changed after they are
created.
.upper()
.isalpha()
.count()
.isdigit()
.isnumeric()
Immutable: Once a string is created, it cannot be modified. However, operations like slicing
can return new strings derived from the original.
my_str={"mad","sad","dad","pad"}
my_str.append("so glad")
my_str
output : error
Sequence: Strings are sequences, allowing operations like concatenation, repetition, and
slicing.
3. Tuple
A Tuple is similar to a list, but it is immutable, meaning once created, the elements of a tuple cannot
be changed. Tuples are often used when data should remain constant throughout the program.
Immutable: After a tuple is created, its elements cannot be modified (no adding, changing,
or removing items).
my_tuple[0] = 'p' #throws error as individual tuple elements can not be altered
4. Dictionary
A Dictionary is an unordered collection of key-value pairs, where each key is unique. The values can
be of any type, and a key can be used to access the corresponding value. Dictionaries are mutable,
allowing modification of the key-value pairs.
Unordered: The items in a dictionary do not have a defined order (although in modern
Python versions, they maintain insertion order).
my_dict={"name":"madhura","age":19,"clg":"bmcc"}
my_dict
to add an element :
my_dict["cgpa"]=8
print(my_dict)
output: {'name': 'madhura', 'age': 19, 'clg': 'bmcc', 'cgpa': 8}
Key-Value Pairs: Each entry in a dictionary consists of a key and a corresponding value.
Unique Keys: No duplicate keys are allowed, but values can be duplicated.
5. Set
A Set is an unordered collection of unique elements, meaning duplicates are not allowed. Sets are
useful for mathematical operations like union, intersection, and difference, and are also mutable
(except for frozensets, which are immutable versions of sets).
Exception Handling in Python is a mechanism that allows programmers to handle runtime errors in a
controlled way. When an error occurs during the execution of a program, an exception is raised,
which interrupts the normal flow of the program. By using exception handling, developers can catch
and handle these errors to prevent the program from crashing.
1. What is an Exception?
An exception is an event that occurs during the execution of a program and disrupts its normal flow.
FileNotFoundError: Raised when an attempt to open a file that does not exist is made.
The try block is used to wrap code that might raise an exception. If an exception occurs, it is caught
by the except block, and the program can handle it gracefully.
except block: Handles the exception if it occurs. You can specify which exception to catch, or
use a general except to catch all exceptions.
finally block (optional): Runs regardless of whether an exception occurred or not, used for
cleanup actions like closing files or releasing resources.
Example Flow:
If an error occurs in the try block, the control is transferred to the corresponding except
block.
The finally block always runs, whether or not an exception occurred, allowing resource
management.
The finally block is used to define a block of code that will always execute, whether an exception
occurs or not. It is typically used for cleanup actions, such as closing a file or releasing a network
connection, ensuring that these actions happen regardless of the outcome.
Characteristics of finally:
It is commonly used for tasks like freeing up resources (closing files, network connections,
etc.).
finally: As described, this is used in exception handling to ensure that a block of code runs
after a try or except block, whether or not an exception occurred.
final: Python does not have a keyword final like in other programming languages (e.g., Java),
where it is used to define constants or prevent inheritance of classes. Python typically
achieves such behavior through conventions or specific programming patterns.
6. User-Defined Exceptions
In addition to Python’s built-in exceptions, developers can create their own exceptions. A User-
Defined Exception is created by subclassing the Exception class or one of its subclasses.
1. Define a new class that inherits from the Exception class (or any other appropriate exception
class).
2. Optionally, define an __init__ method to accept any custom arguments or error messages.
User-defined exceptions are helpful when specific error handling is required for a particular
application domain, making error messages more meaningful.
Imagine a scenario where you are trying to open a file and read its contents:
1. In the try block, you attempt to open a file.
2. If the file doesn’t exist, Python will raise a FileNotFoundError, and the control will go to the
except block to handle it, perhaps printing an error message or taking alternative actions.
3. If the file opens successfully, the else block (if present) will run, proceeding with reading the
file.
4. Finally, regardless of the outcome (whether the file was found or not), the finally block will
close the file to ensure resources are freed.