0% found this document useful (0 votes)
35 views77 pages

Unit 1 Python

UNIT1 PYTHON

Uploaded by

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

Unit 1 Python

UNIT1 PYTHON

Uploaded by

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

Prepared By

P.SARAVANAKUMAR
Assistant Professor
History of Python
Python, created by Guido van Rossum, is a high-
level, interpreted programming language known
for its readability ( Python's syntax is designed to be clear and
concise, making it easy to learn and write code ) and
adaptability (Flexible Syntax).
It was first released in 1991, and its design
emphasizes(Provides) code clarity and developer
productivity (how effectively and efficiently software developers
complete their tasks and deliver high-quality software solutions).
Python supports multiple programming
paradigms, including object oriented, imperative
vital, and functional efficient programming.

Python is Object-oriented programming.
key concepts:
 Objects:
These are instances of classes, representing specific entities in the
program. For example, an object could be a "car," a "customer," or a
"widget".
 Classes:
Classes act as blueprints or templates for creating objects. They
define the attributes (data) and methods (functions) that all
objects of that class will share.
 Encapsulation:
This principle hides the internal details of an object and exposes only
what's necessary to interact with it. It bundles data and methods
together, preventing external code from directly manipulating the
object's internal state.
 Inheritance:
Classes can inherit properties and behaviors from other classes,
creating a hierarchical relationship. For example, a "sports car" class
could inherit from a more general "car" class, adding specific
attributes and methods related to sports cars.
 Polymorphism:
This allows objects of different classes to respond to the same
method call in their own unique way. For instance, a "speak" method
could produce different sounds for a "dog" object and a "cat" object.
Cont…
Created in 1990 by Guido van Rossum
Named after Monty Python
First public release in 1991
comp.lang.python founded in 1994
Open source from the start ( Every one can
access)
Python Overview
 Scripting Language (programming language designed for
specific tasks, often automating or controlling other software or
systems. Unlike traditional programming languages, scripting
languages are typically interpreted rather than compiled,
meaning they are translated into machine code line by line
during runtime, rather than all at once before execution.)
 Object-Oriented(that means paradigm(pattern) that uses
objects and classes to structure and organize code. It's a way of
thinking about software design that models real-world entities
and their interactions. Instead of focusing on procedures, this
centers around data (attributes) and the operations (methods)
that can be performed on that data, all bundled together within
objects)
 Portable (capable of being transported or conveyed)
 Powerful (simplicity, versatility, and extensive libraries,
making it a favorite for beginners and experts )
 Easy to learn and use
 Mixes good features from Java, Perl and Scheme
Major Uses of Python
System Utilities -software programs that help manage, maintain, and
optimize a computer system's functionality.
GUIs (Tkinter, gtk, Qt, Windows) - allows users to interact with
computers and other electronic devices through visual elements like icons,
buttons, and windows, rather than just text-based commands) .
Internet Scripting - process of embedding scripts within web pages to
add dynamic and interactive elements that change based on user input or other
factors, rather than just displaying static content)
Embedded Scripting - practice of including a scripting language
within a larger application or system to provide dynamic functionality or
customization)
Database Programming - process of interacting with and managing
data stored in databases using specialized programming languages and
techniques.
Artificial Intelligence way in which computers can be made to copy
the way humans think.
Image Processing - manipulation of digital images using computational
algorithms to enhance, analyze, or extract information from them
Language Features
Object-Oriented
Interpreted
Interactive
Dynamic
Functional
Highly readable
Comparsions
Java
Typically 3-5 times shorter than equivalent
Java programs
Run-time works harder than Java’s
Components can be developed in Java and
combined to form applications in Python
Python can be used to prototype components
into Java implementation
Comparsions, cont’d
Perl
Come from similar backgrounds
Python is more applicable than Perl
Perl emphasizes support for common
application-oriented tasks
Python emphasizes support for common
programming methodologies
Comparsions, cont’d
C++
Differences are similar to Java’s
Often 5-10 times shorter than equivalent C+
+ code
Python shines as a glue language; used to
combine components written in C++
Thrust Areas of Python
Python is the most versatile programming
language amongst developers today.
There are 7 application areas of Python
programming language.
1. Data Science
2. Automation
3. Application Development
4. AI & Machine Learning
5. Audio/Video Applications
6. Console Applications
7. Desktop GUI
Cont…
1.Data Science
Data science is an interdisciplinary domain that
comprises of two distinct and overlapping areas:
 How to model and summarize data like a
statistician.
 How to design and use algorithms to store,
process, and visualize data like a computer
scientist.
Cont…
2. Automation
Python allows developers to script custom
automation and bring efficiency in tasks in
less time. Automating repetitive tasks
such as sending emails & voicemails,
organizing files & folders, launching
programs, filling out forms, etc. can be
automated through scripting.
Cont…
3. Application Development
Python is a favorable choice for web
application development. Python integrates
well with other programming languages and
has some amazing web frameworks that boost
the application development cycle.
Python Web Frameworks basically make it
easy to build common backend logic. For
example, it helps to deal with the databases,
map URLs with the codebase, generate HTML
files, and more.
Cont…
4. AI & Machine Learning
Python’s pre-built libraries are the reason why it is
preferred for AI & machine learning development.
 Numpy for scientific computation, Pybrain for machine
learning tasks.
 Scipy for technical and scientific computing are some of
the python libraries that make it a supportive technology
for AI and ML development.
 Moreover, there are python libraries for Natural Language
& Text Processing. The Natural Language Toolkit (NLTK)
contains open-source Python modules, linguistic data &
documentation for R&D in natural language processing and
text analytics.
 In addition to this, there are some general python libraries
for Artificial Intelligence. AIMA, SimpleAI, EasyAI,
pyDatalog are a few of them.
Cont…
5. Audio/Video Applications
Python is a sought-after programming language
for creating audio/video applications. An example
of this is the Spotify app that’s built using Python
programming language. Some of the python
libraries such as PyDub, OpenCV support
building audio/video streaming.
Cont…
6. Console Applications
A console application is a computer
program that’s designed for the text-only
interfaces, such as the command-line
interface of Unix, DOS operating system.
For building console applications, there
are advanced python libraries that help in
the development of fully-fledged apps for
the command-line interface.
Cont…
7.DesktopGUI

Python is known for its huge collection of


libraries. Just like the areas mentioned above.
Python has libraries for building desktop GUI
applications as well. Camelot, Kivy, PyGTK are
some of the amazing libraries and tool-kits
available for building desktop GUI.
Installing Anaconda Python
Distribution
To install Anaconda, first download the
installer from the Anaconda website, then run
the installer, and follow the on-screen
instructions. Choose the appropriate installer
for your operating system (Windows, macOS,
or Linux) and Python version (Python 3.7 or
later).
Installing and using jupyter
notebook
To install and use Jupyter Notebook, you can
either use Anaconda, a Python distribution
that includes Jupyter, or install it directly
using pip, the Python package installer. Once
installed, Jupyter Notebook can be launched
from your command line, allowing you to
create and run Python code in a browser-
based environment.
Comments, Reading Input, Print Output,
Type Conversions, the type () Function and Is
Operator, Dynamic and Strongly Typed
Language
Parts of Python Programming
Language : Identifiers
In Python, an identifier is a name used to identify an
entity such as a variable, function, class, module, or
other object. They serve to uniquely distinguish one
entity from another within a program.
Rules for Python Identifiers:
Starting Character:
An identifier must begin with either a letter (A-Z or
a-z) or an underscore (_). It cannot start with a digit.
Subsequent Characters:
Following the initial character, an identifier can
contain any combination of letters (A-Z or a-z), digits
(0-9), and underscores (_).
Identifiers Cont…
Case Sensitivity:
Python is case-sensitive, meaning
that myVariable and myvariable are treated as
two distinct identifiers.
No Special Characters (except underscore):
Identifiers cannot contain special characters
like !, @, #, $, %, etc., other than the
underscore (_).
Not Keywords:
Identifiers cannot be Python keywords
(reserved words) that have predefined
meanings in the language
(e.g., if, for, while, class, def).
Identifiers Cont…
Valid Identifiers:

my_variable, calculateSum, _private_data, ClassName12


3
Invalid Identifiers:
1st_variable (starts with a digit),
my-variable (contains a hyphen),
for (is a keyword),
total$ (contains a special character)
Best Practices:
Choose descriptive and meaningful names for identifiers
to enhance code readability.
Follow Python's naming conventions
(e.g., snake_case for variables and
functions, PascalCase for classes).
Parts of Python Programming
Language : Keywords
Keywords in Python are predefined, reserved words
that hold special meaning and serve specific
purposes within the language's syntax. They are
fundamental building blocks that control the flow,
structure, and functionality of Python programs.
Key characteristics of Python keywords:
Reserved words:
Keywords cannot be used as identifiers (e.g.,
variable names, function names, class names)
because they have a predefined meaning for the
Python interpreter.
Case-sensitive:
Most keywords are in lowercase, with the
exceptions of True, False, and None.
Keywords Cont…
Essential for syntax:
Keywords are crucial for defining program
structures like conditional statements
(if, else, elif), loops (for, while), function
definitions (def), class definitions (class), and
exception handling (try, except, finally).
Specialized functions:
Each keyword has a specific role, such
as import for importing modules, return for
returning values from functions, yield for
creating generators, and async/await for
asynchronous programming
Examples of common Python keywords:
Keywords Function
if, else, elif For conditional execution.
for, while For creating loops.
def, class For defining functions and
classes.
import, from For importing modules and
specific components.
True, False, None Boolean values and a null
value
and, or, not Logical operators
try, except, finally For handling exceptions
return, yield For controlling function
output
and generator behavior
Expressions
In Python, the fundamental distinction between
statements and expressions lies in whether they
produce a value.
Expressions:
Expressions are units of code that evaluate to a
value.
They can be simple, like a literal (e.g., 5, "hello"),
a variable (e.g., x), or a function call that returns
a value (e.g., len("world")).
Expressions can also be complex combinations of
variables, operators, and function calls (e.g., x +
5 * y).
When an expression is evaluated, it yields a
result.
Statements:
 Statements:
 Statements are larger units of code that perform actions
or make something happen within a program.
 They do not necessarily produce a value when executed.
 Examples of statements include: Assignment
statements: x = 10 (assigns a value to a variable).
 Conditional statements: if x > 5:
print("Greater") (controls program flow based on a
condition).
 Looping statements: for i in range(5):
print(i) (repeatedly executes a block of code).
 Function definitions: def my_function(): pass (defines a
new function).
 Import statements: import math (brings in external
modules).
Variable:
In Python, variables are used as named containers
for storing data values. They allow you to store and
reuse data throughout your program, making your
code more readable and maintainable.
Key characteristics of Python variables:
No explicit declaration:
Unlike some other programming languages, you do
not need to explicitly declare the data type of a
variable before using it. Python automatically infers
the type based on the value assigned.
Dynamic typing:
A Python variable can be assigned a value of one
type and then later reassigned a value of a different
type.
Cont…
Assignment:
Variables are created and assigned values using
the assignment operator (=). The variable name
is on the left, and the value is on the right.
Example:
# Assigning an integer to a variable
age = 30
# Assigning a string to a variable
name = "Alice“
# Assigning a float to a variable
price = 19.99
# Reassigning a variable with a different type
age = "thirty"
Variable Cont…
Rules for naming variables:
Must start with a letter (a-z, A-Z) or an
underscore (_).
Cannot start with a number.
Can contain letters, numbers, and
underscores.
Case-sensitive (e.g., age and Age are
different variables).
Cannot be a Python keyword
(e.g., if, for, while).
Variable Cont…
Types of variables (based on scope):
Local variables: Defined within a function
and accessible only within that function.
Global variables: Defined outside of any
function and accessible throughout the entire
program.
Instance variables: Associated with specific
instances of a class.
Class variables: Associated with the class
itself, shared by all instances.
Operators :
Python utilizes various operators to perform
operations on variables and values. These
operators are categorized based on their
functionality.
1. Arithmetic Operators: Used for mathematical
calculations.
a = 10
b=3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division (float): 3.333...
print(a // b) # Floor Division (integer): 3
print(a % b) # Modulus (remainder): 1
print(a ** b) # Exponentiation: 1000
Operators Cont…
2. Assignment Operators: Used to assign
values to variables.
x = 5
x += 3 # Equivalent to x = x + 3; x is now 8
x -= 2 # Equivalent to x = x - 2; x is now 6
x *= 4 # Equivalent to x = x * 4; x is now 24
Operators Cont…
3. Comparison (Relational) Operators: Used
to compare two values and return a boolean
(True/False) result.
p = 7
q=5
print(p == q) # Equal to: False
print(p != q) # Not equal to: True
print(p > q) # Greater than: True
print(p <= q) # Less than or equal to: False
Operators Cont…
 Logical Operators: Used to combine
conditional statements.
is_sunny = True
is_warm = False
print(is_sunny and is_warm) # AND: False
(both must be True)
print(is_sunny or is_warm) # OR: True (at
least one must be True)
print(not is_sunny) # NOT: False (inverts the
boolean value)
Operators Cont…
5. Identity Operators: Used to compare the
memory locations of two objects.
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(list1 is list2) # False (different memory
locations)
print(list1 is list3) # True (same memory
location)
Operators Cont…
6. Membership Operators: Used to test if a
sequence contains a specific value.
my_string = "Hello Python"
print("Python" in my_string) # True
print("Java" not in my_string) # True
Operators Cont…
7. Bitwise Operators: Used to perform
operations on individual bits of integers.
# Example for understanding, less common in
general programming
val1 = 5 # Binary: 0101
val2 = 3 # Binary: 0011
print(val1 & val2) # Bitwise AND: 1 (0001)
print(val1 | val2) # Bitwise OR: 7 (0111)
Operator precedence
Operator precedence and associativity
determine the order in which operations are
performed in an expression in Python.
Operator Precedence:
For example, multiplication and division have
higher precedence than addition and
subtraction.
result = 10 - 5 + 3 * 2
print(result)
# Output: 11
Operator associativity
Operator associativity defines the direction of evaluation
when multiple operators of the same precedence appear
in an expression. Most operators in Python have left-to-
right associativity, meaning they are evaluated from left
to right. The notable exception is the exponentiation
operator (**), which has right-to-left associativity.

 # Left-to-right associativity (addition and subtraction)


result = 10 - 5 + 3
print(result)
# Output: 8 (Evaluated as (10 - 5) + 3)
# Right-to-left associativity (exponentiation)
result = 2 ** 3 ** 2
print(result)
# Output: 512 (Evaluated as 2 ** (3 ** 2), which is 2 ** 9)
Data Types :
Numeric :
Numeric Types: Used to represent numerical
values.
 int (Integer): Whole numbers, positive or negative,
without decimal points.
age = 30
negative_number = -10
float (Floating-point number): Numbers with a
decimal point.
price = 19.99
temperature = 25.5
complex (Complex number): Numbers with a real
and an imaginary part, represented as x + yj.
complex_num = 3 + 4j
String
Text Type:
str (String): Sequences of characters enclosed
in single quotes (' '), double quotes (" "), or
triple quotes (''' ''' or """ """).
name = "Alice"
message = 'Hello, World!'
paragraph = """This is a multi-line string."""
List and tuple
Sequence Types: Ordered collections of items.
list: Ordered, mutable (changeable) collections,
enclosed in square brackets [].
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
tuple: Ordered, immutable (unchangeable)
collections, enclosed in parentheses ().
Pythoncoordinates = (10, 20)
colors = ("red", "green", "blue")
range: Represents an immutable sequence of
numbers, often used in loops.
r = range(5) # Represents numbers from 0 to 4
Dictionary
Mapping Type:
 dict (Dictionary): Unordered collections of key-
value pairs, enclosed in curly braces {}. Keys must
be unique and immutable.
person = {"name": "Bob", "age": 25, "city":
"New York"}
Set Types: Unordered collections of unique items.
 set: Mutable, unordered collections of unique
elements, enclosed in curly braces {}.
unique_numbers = {1, 2, 3, 2, 1} #
Result: {1, 2, 3}
frozenset: Immutable version of a set.
immutable_set = frozenset({"a", "b",
"c"})
Boolean and None
Boolean Type:
bool (Boolean): Represents truth
values, either True or False.
is_active = True
has_permission = False
None Type:
None Type: Represents the
absence of a value.
result = None
Indentation
Indentation in Python defines code blocks to
indicate the scope of control flow statements,
functions, classes, and other code structures.
Examples of Indentation in Python:
1.Conditional Statements (if-elif-else).
Statements belonging to an if, elif,
or else block are indented.
age = 25 if age < 18: print("You are a
minor.") elif age >= 18 and age < 65:
print("You are an adult.") else: print("You
are a senior citizen.") print("This line is
outside the if-elif-else block.")
Cont…
2.Loops (for and while).
The body of for and while loops is indented.
for i in range(3):
print(f"Loop iteration: {i}")

count = 0
while count < 2:
print(f"While loop count: {count}")
count += 1
Cont…
3.Function Definitions.
The code within a function is indented.
def greet(name):
print(f"Hello, {name}!")
print("Welcome to the function.")
greet("Alice")
Cont…
4.Class Definitions.
The methods and attributes within a class are
indented.
class Dog:
def __init__(self, name):
self.name = name

def bark(self):
print(f"{self.name} says Woof!")

my_dog = Dog("Buddy")
my_dog.bark()
Comments
 Comments in Python are lines within the code that are
ignored by the Python interpreter during program
execution.
 There are two main types of comments in Python:
 Single-line Comments:
 These comments begin with the hash symbol (#).
 Everything from the # to the end of the line is considered
a comment.
 They are typically used for brief explanations of a single
line of code or a small block.
 # This is a single-line comment
x = 10 # This is an inline comment explaining the
variable assignment
print(x)
Multi-line Comments:
 Python does not have a specific syntax for multi-line comments
like some other languages.
 However, multi-line comments are commonly simulated by
placing multiple single-line comments consecutively, with each
line starting with a #.
 Alternatively, triple quotes ("""Docstrings""" or '''Docstrings''')
are often used for multi-line comments, particularly for
documenting functions, classes, or modules (these are
technically docstrings, but serve a similar purpose of providing
documentation).
 # This is the first line of a multi-line comment
# This is the second line
# And this is the third line
""" This is a multi-line comment using triple quotes. It's often used
for docstrings to explain functions or classes. """
def greet(name):
""" This function takes a name as input and prints a greeting. """
print(f"Hello, {name}!")
Reading Input:
In Python, user input is primarily obtained using
the built-in input() function. This function reads a
line of text entered by the user from standard
input (usually the keyboard) and returns it as a
string.
1. Basic String Input:
The most common use of input() is to get a string
from the user. You can provide a prompt
message as an argument to guide the user.
name = input("Enter your name: ")
print("Hello,", name)
Cont…
2. Taking Integer Input:
Since input() always returns a string, if you
need to work with numbers, you must convert
the input string to the desired numeric type
using typecasting functions like int() for
integers or float() for floating-point numbers.
age_str = input("Enter your age: ")
age_int = int(age_str)
print("You are", age_int, "years old.")
Cont…
3. Taking Float Input:
Similarly, for decimal numbers, use float().
price_str = input("Enter the price: ")
price_float = float(price_str)
print("The price is:", price_float)
Cont…
Reading Multiple Inputs on a Single Line:
You can read multiple values separated by a
specific delimiter (like space) on a single line
and then split them into individual variables
using the split() method.
data_str = input("Enter your name, age, and
city (separated by spaces): ")
name, age_str, city = data_str.split()
age_int = int(age_str)
print(f"Name: {name}, Age: {age_int}, City:
{city}")
Print Output :
In Python, the print() function is used to display
output to the console. It can handle various data
types and offers several options for formatting the
output.
Basic Usage:
The simplest way to use print() is to pass a string
literal or a variable directly to it.
# Printing a string literal
print("Hello, Python!")

# Printing the value of a variable


name = "Alice"
print(name)
Cont…
Printing Multiple Items:
Multiple items can be passed to print(), separated
by commas. By default, these items will be
separated by a space in the output.
age = 30
print("Name:", name, "Age:", age)
Controlling Separators (sep):
The sep argument allows modification of the
separator used between multiple items.
# Using a hyphen as a separator
print("H", "e", "l", "l", "o", sep="-") # Output: H-e-l-
l-o
# Using an empty string as a separator
print("No", "spaces", sep="") # Output: Nospaces
Cont…
Formatted Output (f-strings and format()):
For more complex formatting, f-strings (formatted
string literals) or the str.format() method can be used.
# Using an f-string
item = "apple"
price = 1.50
print(f"The {item} costs ${price:.2f}.")

# Using str.format()
product = "banana"
quantity = 5
print("You bought {} {}s.".format(quantity, product))
Explicit and Implicit Data Type
Conversion
 Data conversion can happen in two ways in Python
1. Explicit Data Conversion (we saw this earlier with the int,
float, and str
built-in functions)

2. Implicit Data Conversion


 Takes place automatically during run time between ONLY
numeric values
 E.g., Adding a float and an integer will automatically
result in a float value
 E.g., Adding a string and an integer (or a float) will
result in an error since string is not numeric
 Applies type promotion to avoid loss of information
 Conversion goes from integer to float (e.g., upon
adding a float and an integer) and not vice versa so as
the fractional part of the float is not lost
Data Type Conversion
As a matter of fact, we can do various kinds
of conversions between strings, integers and
floats using the built-in int, float, and str
functions
>>> x = 10 >>> y = "20" >>> z = 30.0
>>> float(x) >>> float(y) >>> int(z)
10.0 20.0 30
>>> str(x) >>> int(y) >>> str(z)
'10' 20 '30.0'
>>> >>> >>>

integer  float string  float float  integer


integer  string string  integer float  string
Control flow statements
Control flow statements in Python dictate the
order in which code is executed, enabling
programs to make decisions and perform
repetitive tasks.
Conditional Statements
if statement: Executes a block of code only if
a specified condition is True.
age = 20
if age >= 18:
print("You are an adult.")
if-else statement: Executes one block of code
if the condition is True and another block if
the condition is False.
number = 7
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
if...elif...else statement:
Allows for checking multiple conditions
sequentially. The first True condition's block
is executed, and
subsequent elif and else blocks are skipped.
score = 85
if score >= 90:
print("Grade A")
elif score >= 75:
print("Grade B")
elif score >= 60:
print("Grade C")
else:
print("Grade D")
Nested if statement
: An if statement placed inside
another if (or elif/else) statement, allowing for
more complex decision-making based on
multiple layers of conditions.
num = 10
if num > 0:
print("Number is positive.")
if num % 2 == 0:
print("Number is also even.")
else:
print("Number is odd.")
else:
print("Number is not positive.")
Loop Statements while Loop:

 Repeatedly executes a block of code as long


as a condition remains True.
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1
for i in range(3): # Iterates from 0 to 2
print(f"Iteration {i}")
for Loop:
Iterates over a sequence (like a list, tuple,
string, or range) and executes a block of code
for each item in the sequence.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
1.Break statement
In Python, Break and continue are loop
control statements used to alter the normal
flow of a loop's execution.
1. The break Statement:
The break statement is used to terminate the
loop entirely.
When break is encountered inside a loop
(either for or while), the loop immediately
stops, and the program's control moves to the
statement immediately following the loop.
It is typically used when a specific condition
is met, and further iterations of the loop are
no longer necessary.
Cont…
Example:
for i in range(5):
if i == 3:
break # Exit the loop when i is 3
print(i)
# Output:
#0
#1
#2
2. The continue Statement:
The continue statement is used to skip the
current iteration of the loop and proceed to
the next iteration.
When continue is encountered inside a loop,
the remaining statements in the current
iteration are skipped, and the control returns
to the beginning of the loop for the next
iteration.
It is useful when you want to bypass certain
conditions or values within a loop without
terminating the entire loop.
Cont…
Example:
for i in range(5):
if i == 2:
continue # Skip printing when i is 2
print(i)
# Output:
#0
#1
#3
#4
Try statement
In Python, the try and except statements are
used for handling exceptions, which are
errors that occur during the execution of a
program. This mechanism allows a program to
gracefully handle errors instead of crashing.
Syntax:
try:
# Code that might raise an exception
except ExceptionType:
# Code to execute if ExceptionType occurs in
the try block
try block:
This block contains the code that is expected to
potentially raise an exception. If an exception
occurs within this block, the execution of
the try block is immediately stopped, and Python
looks for a matching except block.
except block:
This block is executed only if an exception of the
specified ExceptionType occurs in the
corresponding try block. You can have
multiple except blocks to handle different types
of exceptions. If no ExceptionType is specified
after except, it will catch any type of exception
Example:
Consider a program that asks the user for two
numbers and performs division. This operation can
lead to a ZeroDivisionError if the user enters 0 as
the divisor, or a ValueError if they enter non-
numeric input.
try:
dividend = int(input("Enter the dividend: "))
divisor = int(input("Enter the divisor: "))
result = dividend / divisor
print(f"The result is: {result}")
except ZeroDivisionError:
print("Error: You cannot divide by zero!")
except ValueError:
print("Error: Invalid input. Please enter valid
integers.")
except Exception as e: # Catching a general
exception and printing its message
UNIT I :

END

You might also like