0% found this document useful (0 votes)
14 views87 pages

UNIT - I Part 2 & 3

This document provides an overview of the Python programming language, covering its basic syntax, identifiers, reserved words, and variable types. It explains the use of different data types such as numbers, strings, lists, tuples, and dictionaries, along with their properties and examples. Additionally, it discusses operators, including arithmetic, assignment, comparison, and logical operators, with illustrative examples.
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)
14 views87 pages

UNIT - I Part 2 & 3

This document provides an overview of the Python programming language, covering its basic syntax, identifiers, reserved words, and variable types. It explains the use of different data types such as numbers, strings, lists, tuples, and dictionaries, along with their properties and examples. Additionally, it discusses operators, including arithmetic, assignment, comparison, and logical operators, with illustrative examples.
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/ 87

UNIT – I

PART - II

Parts of Python
Programming Language
Python - Basic Syntax
• Interactive Mode Programming:
>>> print ("Hello, Python!“)
Hello, Python!
>>> 3+4*5;
23
• Script Mode Programming :
Invoking the interpreter with a script parameter begins
execution of the script and continues until the script is
finished. When the script is finished, the interpreter is no
longer active.

For example, put the following in one test.py, and run,


print ("Hello, Python!“)
print ("I love COMP3050!”)

The output will be:


Hello, Python!
I love COMP3050!
Python Identifiers:
• A Python identifier is a name used to identify a variable,
function, class, module, or other object.

• An identifier starts with a letter A to Z or a to z or an underscore


(_) followed by zero or more letters, underscores, and digits (0 to
9).

• An identifier cannot start with a digit but it is allowed anywhere


else.

• Python does not allow punctuation characters such as @, $, and


% within identifiers.

• Python is a case sensitive programming language. Thus


Manpower and manpower are two different identifiers in
Python.
Python Identifiers (cont’d)

• Here are following identifier naming convention for Python:


– Class names start with an uppercase letter and all other
identifiers with a lowercase letter.

– Starting an identifier with a single leading underscore


indicates by convention that the identifier is meant to
be private.

– Starting an identifier with two leading underscores


indicates a strongly private identifier.

– If the identifier also ends with two trailing underscores,


the identifier is a language-defined special name.
Reserved Words:

Keywords contain lowercase letters


only.
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Lines and Indentation:
• One of the first caveats programmers encounter when
learning Python is the fact that there are no braces to
indicate blocks of code for class and function definitions or
flow control.

• Blocks of code are denoted by line indentation, which is


rigidly enforced.

• The number of spaces in the indentation is variable, but all


statements within the block must be indented the same
amount. Both blocks in this example are fine:
if True:
print ("Answer“)
print ("True“)
else:
print ("Answer“)
print (“False“)
Multi-Line Statements:

• Statements in Python typically end with a new line. Python


does, however, allow the use of the line continuation
character (\) to denote that the line should continue. For
example:
total = “item_one” + \
“item_two” + \
“item_three”
Print(total)

• Statements contained within the [], {}, or () brackets do not


need to use the line continuation character. For example:
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Quotation in Python:
• Python accepts single ('), double (") and triple (''' or """)
quotes to denote string literals, as long as the same type of
quote starts and ends the string.

• The triple quotes can be used to span the string across


multiple lines. For example, all the following are legal:

word = 'word'
sentence = "This is a sentence"
paragraph = """This is a paragraph. It is made up
of multiple lines and sentences"""
Comments in Python:

• A hash sign (#) that is not inside a string literal begins a


comment.

• All characters after the # and up to the physical line end


are part of the comment, and the Python interpreter
ignores them.
Using Blank Lines:

• A line containing only whitespace, possibly with a


comment, is known as a blank line, and Python totally
ignores it.

• In an interactive interpreter session, you must enter an


empty physical line to terminate a multiline statement.
Multiple Statements on a Single
Line:
• The semicolon ( ; ) allows multiple statements on the single
line given that neither statement starts a new code block.
Here is a sample snip using the semicolon:

x = 'Ram'; y="lakshman"; z="Seeta"


Multiple Statement Groups as
Suites:
• Groups of individual statements making up a single code
block are called suites in Python.
Compound or complex statements, such as if, while, def,
and class, are those which require a header line and a suite.
Header lines begin the statement (with the keyword) and
terminate with a colon ( : ) and are followed by one or more
lines which make up the suite.
if expression :
suite
elif expression :
suite
else :
suite
Python - Variable Types

• Variables are nothing but reserved memory locations to


store values. This means that when you create a variable
you reserve some space in memory.

• Based on the data type of a variable, the interpreter


allocates memory and decides what can be stored in the
reserved memory.

• Therefore, by assigning different data types to variables,


you can store integers, decimals, or characters in these
variables.
Assigning Values to Variables:

• Python variables do not have to be explicitly declared to


reserve memory space. The declaration happens
automatically when you assign a value to a variable. The
equal sign (=) is used to assign values to variables.

counter = 100 # An integer assignment


miles = 1000.0 # A floating point
name = "John" # A string
print (counter)
print (miles)
print (name)
Multiple Assignment:

• You can also assign a single value to several variables


simultaneously. For example:
a = b = c = 1
a, b, c = 1, 2, "john"
Standard Data Types:

Python has five standard data types:


• Numbers
• String
• List
• Tuple
• Dictionary
Python Numbers:

• Number data types store numeric values. They are immutable


data types (contents cannot be changed), which means that
changing the value of a number data type results in a newly
allocated object.
• Number objects are created when you assign a value to them.
For example:
var1 = 1
var2 = 10
Python supports four different numerical types:
• int (signed integers)
• long (long integers [can also be represented in octal and
hexadecimal])
• float (floating point real values)
• complex (complex numbers)
Number Examples:

int long float complex


10 51924361L 0 3.14j
100 -0x19323L 15.2 45.j
-786 0122L -21.9 9.322e-36j
80 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
-490 535633629843L -90 -.6545+0J
-0x260 -052318172735L -3.25E+101 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
Python Strings:

• Strings in Python are identified as a contiguous set of


characters in between quotation marks.

• Python allows for either pairs of single or double quotes.

• Subsets of strings can be taken using the slice operator


( [ ] and [ : ] ) with indexes starting at 0 in the beginning of
the string and working their way from -1 at the end.

• The plus ( + ) sign is the string concatenation operator,


and the asterisk ( * ) is the repetition operator.

• They are immutable


Example:
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 6th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST“) # Prints concatenated string

Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists:
• Lists are the most versatile of Python's compound data types. A
list contains items separated by commas and enclosed within
square brackets ([]).

• To some extent, lists are similar to arrays in C. One difference


between them is that all the items belonging to a list can be of
different data type.

• The values stored in a list can be accessed using the slice


operator ( [ ] and [ : ] ) with indexes starting at 0 in the beginning
of the list and working their way to end-1.

• The plus ( + ) sign is the list concatenation operator, and the


asterisk ( * ) is the repetition operator.

• They are mutable(contents can be changed)


list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print (list ) # Prints complete list


print (list[0] ) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:] ) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists

Output:
['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Python Tuples:
• A tuple is another sequence data type that is similar to the
list. A tuple consists of a number of values separated by
commas. Unlike lists, however, tuples are enclosed within
parentheses.

• The main differences between lists and tuples are: Lists are
enclosed in brackets ( [ ] ), and their elements and size can
be changed, while tuples are enclosed in parentheses ( ( ) )
and cannot be updated. Tuples can be thought of as read-
only lists.

• They are immutable


tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')

print (tuple) # Prints complete list


print (tuple[0]) # Prints first element of the list
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:] ) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints list two times
print (tuple + tinytuple) # Prints concatenated lists

OUTPUT:
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Python Dictionary:

• Python 's dictionaries are hash table type. They work like
associative arrays or hashes found in Perl and consist of key-
value pairs.

• Keys can be almost any Python type, but are usually numbers
or strings. Values, on the other hand, can be any arbitrary
Python object.

• Dictionaries are enclosed by curly braces ( { } ) and values


can be assigned and accessed using square braces ( [] ).

• They are mutable.


dict = {}
dict['one'] = "This is one"
dict[2] = "This is two“
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values

OUTPUT:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Data Type Conversion:
Function Description
int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
complex(real Creates a complex number.
[,imag])
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
Operators

Operators are symbols, such as +, –, =, >, and <,


that perform certain mathematical or logical operation
to manipulate data values and produce a result based
on some rules. An operator manipulates the data
values called operands.

Consider the expression,


>>> 4 + 6
where 4 and 6 are operands and + is the operator.
Operators

Python language supports a wide range of


operators. They are

1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
Operators
Operators
For example,
1. >>> 10+35 5. >>> 45/10
45 4.5

2. >>> −10+35 6. >>> 45//10.0


25 4.0

3. >>> 4*2 7. >>> 2025%10


8 5

4. >>> 4**2 8. >>> 2025//10


16 202
Assignment Operators
Assignment operators are used for assigning
the values generated after evaluating the right
operand to the left operand.

Assignment operation always works from


right to left.
Simple assignment is done with the equal
sign (=) and simply assigns the value of its
right operand to the variable on the left. For
example,
>>> x = 5
>>> x = x + 1
>>> print(x)
Assignment Operators
Assignment Operators
For example, 8. >>> q
1.>>> p = 10 22.0
2. >>> q = 12 9. >>> q %= p
3. >>> q += p 10. >>> q
2.0
4. >>> q
22 11. >>> q **= p
5. >>> q *= p 12. >>> q
1024.0
6. >>> q
220 13. >>> q //= p

7. >>> q /= p 14. >>> q


102.0
Comparison Operators
Comparison Operators
For example,
1. >>>10 == 12 5. >>>10 <= 12
False True
2. >>>10 != 12 6. >>>10 >= 12
True False
3. >>>10 < 12 7. >>> True == True
True True

4. >>>10 > 12
False
Logical Operators
Logical Operators
For example,
1. >>> True and False 5. >>> (10 < 0) and (10 >
False 2)
False
2. >>> True or False
True 6. >>> (10 < 0) or (10 > 2)
True
3. >>> not(True) and False
False 7. >>> not(10 < 0) or (10 >
2)
4. >>> not(True and False)True
True
8. >>> not(10 < 0 or 10 >
2)
Bitwise Operators
Bitwise Operators
Bitwise Operators
Precedence and Associativity

Consider the following code


1. >>> 2 + 3 * 6
20
2. >>> (2 + 3) * 6
30
3. >>> 6 * 4 / 2
12.0
Reading Input

In Python, input() function is used to gather data


from the user. The syntax for input function is,

variable_name = input([prompt])

>>> person = input("What is your name?")


What is your name? Carrey
>>> person
'Carrey'
Print Output

The print() function allows a program to display


text onto the console.

The print function will print everything as strings


and anything that is not already a string is
automatically converted to its string representation.
For example,

1. >>> print("Hello
World!!")
Hello World!!
str.format() method

Use str.format() method, if you need to insert the


value of a variable, expression or an object into
another string and display it to the user as a
single string. The format() method returns a new string
with inserted values.
Syntax: { }.format(value)

Parameters:

value : Can be an integer, floating point numeric


constant, string, characters or even variables.

Returntype: Returns a formatted string with the


value passed as parameter in the placeholder
country = input("Which country do you live in?")
print("I live in {0}”.format(country))

Output

Which country do you live in? India


I live in India
name = "Ram“

age = 22

message = "My name is {0} and I am {1} years \


old. {1} is my favorite \
number.".format(name, age)

print(message)

Output
My name is Ram and I am 22 years old. 22 is my favorite
number.
f-strings
A f-string is a string literal that is prefixed with “f”.

These strings may contain replacement fields, which


are expressions enclosed within curly braces {}.

The expressions are replaced with their values. In the


real world, it means that you need to specify the name
of the variable inside the curly braces to display its
value.

 An f at the beginning of the string tells Python to


allow any currently valid variable names within the
string.

f-strings are the most practical and straightforward


way of formatting strings unless some special case
country = input("Which country do you live in?")
print(f"I live in {country}")

Output

Which country do you live in? India


I live in India
radius = int(input("Enter the radius of a circle"))

area_of_a_circle = 3.1415 * radius * radius

circumference_of_a_circle = 2 * 3.1415 * radius

print(f"Area = {area_of_a_circle} and Circumference


= {circumference_of_a_circle}")

Output
Enter the radius of a circle 5

Area = 78.53750000000001 and Circumference


= 31.415000000000003
Write Python Program to Convert the Given Number of Days to
a Measure of Time Given in Years, Weeks and Days. For
Example, 375 Days Is Equal to 1 Year, 1 Week and 3 Days
(Ignore Leap Year).

number_of_days = int(input("Enter number of days"))


number_of_years = int(number_of_days/365)
number_of_weeks = int(number_of_days % 365 / 7)
remaining_number_of_days = int(number_of_days % 365 % 7)
print(f"Years = {number_of_years}, Weeks = {number_of_weeks}, \
Days ={remaining_number_of_days}")
Output
Enter number of days375
Years = 1, Weeks = 1, Days = 3
type() Function and Is Operator
The syntax for type() function is,
type(object)

The type() function returns the data type of the


given object.

1. >>> type(1)
<class 'int'>
2. >>> type(6.4)
<class 'float'>
3. >>> type("A")
<class 'str'>
4. >>> type(True)
<class 'bool'>
type() Function and Is Operator
The operators is and is not are identity operators.
Operator is evaluates to True if the values of
operands on either side of the operator point to the
same object and False otherwise. The operator is not
evaluates to False if the values of operands on either
side of the operator point to the same object and True
otherwise.

1. >>> x = "Seattle"
2. >>> y = "Seattle"
3. >>> x is y
True
UNIT – I

PART - III

Control Flow Statements


Control Flow Statements

Output
20 is greater than 10
Program 3.1: Program Reads a Number and
Prints a Message If It Is Positive

number = int(input("Enter a number"))


if number >= 0:
print(f"The number entered by the user is a
positive number")

Output
Enter a number 67
The number entered by the user is a positive number
If else
If else
Program to Find If a Given Number Is Odd or
Even

number = int(input("Enter a number"))


if number % 2 == 0:
print(f"{number} is Even number")
else:
print(f"{number} is Odd number")

Output
Enter a number: 45
45 is Odd number
if else ladder
Write a Program to Prompt for a Score between 0.0 and 1.0. If the
Score Is Out of Range, Print an Error. If the Score Is between 0.0
and 1.0, Print a Grade Using the Following Table
Score Grade
>= 0.9 A print('Your Grade is "C" ')
>= 0.8 B elif score >= 0.6:
>= 0.7 C print('Your Grade is "D" ')
>= 0.6 D else:
< 0.6 F print('Your Grade is "F" ')

score = float(input("Enter your score")) Output


if score < 0 or score > 1: Enter your score 0.92
print('Wrong Input') Your Grade is "A"
elif score >= 0.9:
print('Your Grade is "A" ')
elif score >= 0.8:
print('Your Grade is "B" ')
elif score >= 0.7:
Nested if Statement
Nested if Statement

Program to Check If a Given Year Is a Leap Year


year = int(input('Enter a year'))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f'{year} is a Leap Year')
else:
print(f'{year} is not a Leap Year')
else:
print(f'{year} is a Leap Year')
else:
print(f'{year} is not a Leap Year')
Output
Enter a year 2014
2014 is not a Leap Year
While Loop
Write a Program to Find the Average of n Natural
Numbers Where n Is the Input from the User

number = int(input("Enter a number up to which you want to find the


average"))
i=0
sum = 0
count = 0
while i < number:
i=i+1
sum = sum + i
count = count + 1
average = sum/count
print(f"The average of {number} natural numbers is {average}“)

Output
Enter a number up to which you want to find the average 5
The average of 5 natural numbers is 3.0
for loop
(Don’t need Initialization of variable,
condition checking, inrement/decrement)
Note:
 Normally works with sequence

Ex:
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

for i in list:
print(i)
Output:
abcd
786
2.23
john
70.2
for i in [‘ram’, 25, 15.0]:
print(i)

for i in range(10):
print(i)

for i in range(11,21):
print(i)

for i in range(11,21,2):
print(i)

for i in range(21,11,-1):
print(i)
Write a Program to Find the Factorial of a Number

number = int(input('Enter a number'))


factorial = 1
if number < 0:
print("Factorial doesn't exist for negative numbers")
elif number == 0:
print('The factorial of 0 is 1')
else:
for i in range(1, number + 1):
factorial = factorial * I
print(f"The factorial of number {number} is {factorial}")

Output
Enter a number 5
The factorial of number 5 is 120
The continue and break Statements

The break and continue statements provide greater


control over the execution of code in a loop.

Whenever the break statement is encountered,


the execution control immediately jumps to the
first instruction following the loop.

To pass control to the next iteration without


exiting the loop, use the continue statement.
Both continue and break statements can be used in
while and for loops.
The continue and break Statements

n=0
while True:
print(f"The latest value of n is {n}")
n=n+1
if n > 5:
print(f"The value of n is greater than 5")
break
Output
The latest value of n is 0
The latest value of n is 1
The latest value of n is 2
The latest value of n is 3
The latest value of n is 4
The latest value of n is 5
The value of n is greater than 5
n = 10
while n > 0:
print(f"The current value of number is {n}")
if n == 5:
print(f"Breaking at {n}")
n = 10
continue
n=n–1
Output
The current value of number is 10
The current value of number is 9
The current value of number is 8
The current value of number is 7
The current value of number is 6
The current value of number is 5
Breaking at 5
The current value of number is 10
The current value of number is 9
The current value of number is 8
The current value of number is 7
The current value of number is 6
The current value of number is 5
Catching Exceptions Using try and except Statement

There are at least two distinguishable kinds of errors:


1. Syntax Errors
2. Exceptions
Syntax Errors
Syntax errors, also known as parsing errors, are perhaps the most
common kind of complaint you get while you are still learning
Python.
For example,
while True
print("Hello World)
Output
File "<ipython-input-3-c231969faf4f>", line 1
while True
^
SyntaxError: invalid syntax
Catching Exceptions Using try and except Statement

Exceptions:
Exception handling is one of the most important
feature of Python programming language that allows
us to handle the errors caused by exceptions.

Even if a statement or expression is syntactically


correct, it may cause an error when an attempt is
made to execute it.

Errors detected during execution are called


exceptions.
Examples:

1. >>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

2. >>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined

3. >>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
Exception Handling Using try…except…finally

Handling of exception ensures that the flow of the


program does not get interrupted when an exception
occurs which is done by trapping run-time errors.

 Handling of exceptions results in the execution of all


the statements in the program.

It is possible to write programs to handle exceptions


by using try…except…finally statements.
If any statement within the try block throws an
exception, control immediately shifts to the catch
block.

 If no exception is thrown in the try block, the.


catch block is skipped

The try statement has another optional block which


is intended to define clean-up actions that must be
executed under all circumstances.

A finally block is always executed before leaving the


try statement, whether an exception has occurred or
not.
Normal statements Normal statements
a =5 a =5
b =2 b =2
Print(a/b) Print(a/b)
Print(“hello world”)
Output: Output:
2.5 2.5
hello world
Critical statements Critical statements
a =5 a =5
b =0 b =0
Print(a/b) Print(a/b)
Output:
Traceback (most recent call last): Print(“hello world”)
File "C:/Users/mnr/OneDrive/Desktop/try.py", line 3, in <module>
print(a/b)
ZeroDivisionError: division by zero
a =5 a =5
b =0 b =2
try: try:
Print(a/b) Print(a/b)
except Exception: except Exception:
print(“division by zero error”) print(“division by zero error”)
Print(“hello world”) Print(“hello world”)

Output: Output:
division by zero error 2.5
hello world hello world
a =5 a =5
b =2 b =0
try: try:
print(“resource open”) print(“resource open”)
Print(a/b) Print(a/b)
print(“resource closed”) print(“resource closed”)
except Exception: except Exception:
print(“division by zero error”) print(“division by zero error”)

Output: Output:
resource open resource open
2.5 division by zero error
resource closed
a =5 a =5
b =0 b =2
try: try:
print(“resource open”) print(“resource open”)
Print(a/b) Print(a/b)

except Exception: except Exception:


print(“division by zero error”) print(“division by zero error”)
print(“resource closed”) print(“resource closed”)

Output: Output:
resource open resource open
division by zero error 2.5
resource closed
a =5 a =5
b =0 b =2
try: try:
print(“resource open”) print(“resource open”)
Print(a/b) Print(a/b)

except Exception: except Exception:


print(“division by zero error”) print(“division by zero error”)
print(“resource closed”) print(“resource closed”)

Output: Output:
resource open resource open
division by zero error 2.5
resource closed
a =5 a =5
b =2 b =0
try: try:
print(“resource open”) print(“resource open”)
Print(a/b) Print(a/b)

except Exception: except Exception:


print(“division by zero error”) print(“division by zero error”)
finally: finally:
print(“resource closed”) print(“resource closed”)

Output: Output:
resource open resource open
2.5 division by zero error
resource closed resource closed
Program to Check for ValueError Exception

while True:
try:
number = int(input("Please enter a number: "))
print(f"The number you have entered is {number}")
break
except ValueError:
print("Oops! That was no valid number. Try again…“)

Output
Please enter a number: g
Oops! That was no valid number.
Try again…
Please enter a number: 4
The number you have entered is 4
Program to Check for ZeroDivisionError Exception
Output
x = int(input("Enter value for x: "))
Case 1
y = int(input("Enter value for y: "))
Enter value for x: 8
try:
Enter value for y: 0
result = x / y
Division by zero!
except ZeroDivisionError:
Executing finally clause
print("Division by zero!")
else:
Case 2
print(f"Result is {result}")
Enter value for x: p
finally:
ValueError Traceback (most recent
print("Executing finally clause")
call last)
<ipython-input-16-271d1f4e02e8>
in <module>()
ValueError: invalid literal for int()
with base 10: 'p'
Thank You

You might also like