[go: up one dir, main page]

0% found this document useful (0 votes)
28 views9 pages

Lesson No 1 (Shreya)

Uploaded by

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

Lesson No 1 (Shreya)

Uploaded by

Janhavi Jadhav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

1. What is Python?

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:

1. Basic Data Types:

 int: Represents integers (whole numbers).


x = 10
 float: Represents floating-point numbers (numbers with decimal points).
y = 3.14
 str: Represents strings, which are sequences of characters enclosed in single or double
quotes.
name = "Alice"
str in Python means "string," which is just a bunch of letters, numbers, or symbols put
together to make words or sentences. It's how you store text in Python.
Examples:
 "Hello" is a string.
 '123' is also a string, even though it looks like a number because it’s inside quotes.
Here are a few examples in Python:
name = "John" # This is a string
age = "25" # This is also a string, even though it's a number inside quotes
greeting = 'Good morning!'
If it’s inside quotes (either single ' ' or double " "), it’s a string!
 bool: Represents Boolean values True or False.
is_active = True

2. Composite Data Types:

 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}

B. Types of Functions in Python

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.

Example of a User-Defined Function:

# Define the function

def add_nos(a, b):

return a + b

# Call the function with two numbers

result = add_nos(3, 5)

# Print the result

print("The sum is:", result)

output will be –

The sum is: 8

Advantages of User-Defined Functions:

o Code Reusability: Functions allow you to reuse code multiple times.

o Modularity: Functions break the program into smaller, manageable parts.

o Debugging: Functions make the code easier to debug and maintain.

Library Functions (Built-in Functions):

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:

1. print() – Prints the output to the console.

print("Hello, World!")
2. len() – Returns the length (number of items) in an object like a string, list, etc.

length = len("Hello") # Output: 5

3. max() – Returns the largest element from a list, string, or tuple.

maximum = max([1, 2, 3, 4]) # Output: 4

4. sum() – Returns the sum of all the elements in a list or tuple.

total = sum([1, 2, 3]) # Output: 6

5. type() – Returns the type of an object.

t = type(10) # Output: <class 'int'>

6. input() – Reads input from the user as a string.

user_input = input("Enter your name: ")

Advantages of Library Functions:

 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.

Data Structures in Python

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).

Key Characteristics of Lists:

 Ordered: Items in a list have a defined order.

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.

Methods used in strings are - .lower()

.upper()

.isalpha()

.count()

.isdigit()

.isnumeric()

Key Characteristics of Strings:

 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

 Indexed: Characters in a string can be accessed using their position.

 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.

Key Characteristics of Tuples:


 Ordered: Tuples maintain the order of elements.

 Immutable: After a tuple is created, its elements cannot be modified (no adding, changing,
or removing items).

my_tuple = ('a', 'b', 'c', 'd', 'e')

my_tuple[0] = 'p' #throws error as individual tuple elements can not be altered

 Heterogeneous: Tuples can contain elements of different types.

 Indexable: Like lists, tuple elements can be accessed by their index.

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.

Key Characteristics of Dictionaries:

 Unordered: The items in a dictionary do not have a defined order (although in modern
Python versions, they maintain insertion order).

 Mutable: Dictionary elements can be added, modified, or removed.

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).

Key Characteristics of Sets:

 Unordered: The items in a set do not have a defined order.

 Mutable: Elements can be added or removed from a set.

 Unique Elements: Sets only store unique items, meaning no duplicates.

 No Indexing: Since sets are unordered, items cannot be accessed by index.

Exception Handling in Python

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.

Python provides various built-in exceptions, such as:

 ZeroDivisionError: Raised when division by zero occurs.

 FileNotFoundError: Raised when an attempt to open a file that does not exist is made.

 TypeError: Raised when an operation is applied to an object of inappropriate type.

3. try-except Blocks (Try-Catch in Other Languages)

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.

Key Components of try-except:

 try block: Contains the code that may throw an exception.

 except block: Handles the exception if it occurs. You can specify which exception to catch, or
use a general except to catch all exceptions.

 else block (optional): Runs if no exception occurs in the try block.

 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.

 If no exception occurs, the else block (if present) will execute.

 The finally block always runs, whether or not an exception occurred, allowing resource
management.

4. The finally Block

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:

 The finally block is optional.

 It runs even if an exception is raised or not.

 It is commonly used for tasks like freeing up resources (closing files, network connections,
etc.).

5. Difference Between finally and final

 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.

Steps to Create a User-Defined Exception:

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.

3. Use the raise keyword to raise the exception when needed.

User-defined exceptions are helpful when specific error handling is required for a particular
application domain, making error messages more meaningful.

7. Example Flow of Exception Handling (Without Code)

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.

You might also like