Python UNIT.1
Python UNIT.1
Python program structure supports concepts of polymorphism, operation overloading and The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
. Page 1 . Page 2
Python Programming Python Programming
. Page 3 . Page 4
Python Programming Python Programming
An IDE (or Integrated Development Environment) is a program dedicated to software One cannot use spaces and special symbols like !, @, #, $, % etc. as identifiers.
development. As the name implies, IDEs integrate several tools specifically designed for software Identifier can be of any length.
development.
These tools usually include: Keywords
An editor designed to handle code (with, for example, syntax highlighting and auto- Keywords are a list of reserved words that have predefined meaning. Keywords are cannot be
completion) used by programmers as identifiers for variables, functions, constants or with any identifier name.
Build, execution, and debugging tools. The following shows the Python keywords.
Some form of source control.
. Page 5 . Page 6
Python Programming Python Programming
Expression is an arrangement of values and operators which are evaluated to make a new value. Ex: number =100 // integer type value is assigned to a variable number
Expressions are statements as well. A value is the representation of some entity like a letter or a miles =1000.0 // float type value has been assigned to variable miles
number that can be manipulated by a program. name ="Python" // string type value is assigned to variable name
Ex: A single value >>> 20
A single variable >>> z In Python, not only the value of a variable may change during program execution but also the
A combination of variable, operator and value >>> z + 20 type of data that is assigned. We can assign an integer value to a variable, use it as an integer for a
while and then assign a string to the variable. A new assignment overrides any previous
VARIABLE assignments.
Variable is a named placeholder to hold any type of data which the program can use to assign and Ex: century = 100
modify during the course of execution. In Python, there is no need to declare a variable explicitly century = "hundred"
by specifying whether the variable is an integer or a float or any other type. To define a new An integer value is assigned to century variable and then in second expression assigning a string
variable in Python, simply assign a value to a name. value to century variable.
Legal Variable Names Python allows to assign a single value to several variables simultaneously.
Variable names can consist of any number of letters, underscores and digits. Ex: a = b = c =1
Variable should not start with a number. An integer value is assigned to variables a, b and c simultaneously. Values for each of these
Python Keywords are not allowed as variable names. variables are 1.
Python variables use lowercase letters with words separated by underscores Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively and
Avoid naming a variable where the first character is an underscore. This is legal in Python, one string object with the value “Python” is assigned to the variable c. Values for a is 1 b is 2 and
it can limit the interoperability of your code with applications built by using other c is “Python.
programming languages.
Variable names are descriptive and clear enough. 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
Assigning Values to Variables
The general format for assigning values to variables is as follows: manipulates the data values called operands.
Python language supports a wide range of operators. They are
variable_name = expression 1. Arithmetic Operators
2. Assignment Operators
Where variable_name is name of the variable, the equal sign (=) also known as simple
3. Comparison Operators
assignment operator is used to assign values to variables.
4. Logical Operators
. Page 7 . Page 8
Python Programming Python Programming
. Page 9 . Page 10
Python Programming Python Programming
4. Logical Operators 0 1 0 1 1 1
The logical operators are used for comparing or negating the logical values of their operands 1 0 0 1 1 0
and to return the resulting logical value. The values of the operands on which the logical 1 1 1 1 0 0
operators operate evaluate to either True or False. The result of the logical operator is always a
Boolean value, True or False. The following tables show Boolean logic truth table and all the Operator Operator Name Description Example
Result is 1, If the corresponding bits of both If p = 60, q=30
logical operators. & Binary AND
operands are 1. p & q is 12
Result is 1, if the corresponding bits of If p= 60, q=30
| Binary OR
either or both operands are 1. p | q is 61
P Q P and Q P or Q not P
Result is 1 If the corresponding bits of either If p = 60, q=30
^ Binary XOR
True True True True False but not both operands are 1. p ^ q is 61
Binary Ones If p= 60
True False False True ~ Inverts the bits of its operand.
Complement ~ p is -61
False True False True True The left operands value is moved left by the
Binary Left If p= 60, q=30
<< number of bits specified by the right
False False False Shift p << q is 240
False operand.
Binary Right The left operands value is moved right by If p= 60, q=30
>> the number of bits specified by the right
Shift p >> q is 15
operand.
. Page 11 . Page 12
Python Programming Python Programming
6. Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location.
. Page 13 . Page 14
Python Programming Python Programming
Numbers
Integers, floating point numbers and complex numbers are python numbers category. They are
defined as int, float and complex class in Python. Integers can be of any length; it is only limited
by the memory available. A floating point number is accurate up to 15 decimal places. 1 is an
integer, 1.0 is floating point number. Complex numbers are written in the form, x + yj, where x is
the real part and y is the imaginary part.
Boolean
In the above diagram, Block 2 and Block 3 are nested under Block 1. Usually, four whitespaces are
Booleans are useful for conditional statements. Boolean values are either True or False. The
used for indentation and are preferred over tabs. Incorrect indentation will result in
Boolean values True and False are treated as reserved words.
IndentationError.
Strings
A string consists of a sequence of one or more characters, which can include letters, numbers, COMMENTS
and other types of characters. A string can also contain spaces. You can use single quotes or A comment is a text that describes what the program or a particular part of the program is trying
double quotes to represent strings and it is also called a string literal. Multiline strings can be to do and is ignored by the Python interpreter. Comments are used to help you and other
denoted using triple quotes, ''' or " " ". programmers understand, maintain, and debug the program. Python uses two types of comments:
Ex: s = ' This is single quote string’ single-line comment and multiline comments.
s = “ This is double quote string "
Single Line Comment
In Python, the hash (#) symbol is used for Single Line Comment. Hash (#) symbol makes all text
None
following it on the same line into a comment.
None is another special data type in Python. None is frequently used to represent the absence
Ex: # This is single line Python comment
of a value.
Ex: money = None // None value is assigned to variable money
. Page 15 . Page 16
Python Programming Python Programming
Multiline Comments It prints the string Hello World!! on to the console. There are different ways to print values in
If the comment extends multiple lines, then one way of commenting those lines is to use hash (#) Python, there are two major string formats which are used inside the print () function to display
symbol at the beginning of each line. the contents onto the console. They are
Ex: # This is str.format()
# multiline comments f-strings
# In Python
Another way of doing this is to use triple quotes, either ''' or """. These triple quotes are used as a str.format() Method
multiline comment. str.format() method is to insert the value of a variable, expression or an object into another
Ex: ''' This is string and display it to the user as a single string. The format() method returns a new string with
multiline comment inserted values.
in Python using triple quotes''' Syntax: str.format (p0, p1, ..., k0=v0, k1=v1, ...)
Where p0, p1,... are called as positional arguments and, k0, k1,... are keyword arguments with
BUILT IN FUNCTIONS
their assigned values of v0, v1,... respectively.
CONSOLE INPUT
Positional arguments are a list of arguments that can be accessed with an index of argument inside
1. input (): This function is used to get data from the user.
curly braces like {index}. Index value starts from zero.
Syntax: variable_name = input ([prompt])
Keyword arguments are a list of arguments of type keyword = value, that can be accessed with the
Where prompt is a string written inside the parenthesis that is printed on the screen. The prompt
name of the argument inside curly braces like {keyword}.
statement gives an indication to the user of the value that needs to be entered through the
Here, str is a mixture of text and curly braces of indexed or keyword types. The indexed or
keyboard.
keyword curly brace are replaced by their corresponding argument values and is displayed as a
Ex: person = input ("What is your name?")
single string to the user.
The input() function prints the prompt statement on the screen. The input() function reads the line
from the user and converts the line into a string. The line typed by the user is assigned to the Program to Demonstrate input() and print() Functions
person variable in the above example. country = input("Which country do you live in?")
print("I live in {0}".format(country))
CONSOLE OUTPUT
Output
1. print () : The print() function allows a program to display text onto the console. The print
Which country do you live in? India
function will print everything as strings and anything that is not already a string is
I live in India
automatically converted to its string representation.
The 0 inside the curly braces {0} is the index of the first (0th) argument, where country is a
Syntax: print (“String”) variable
. Page 17 . Page 18
Python Programming Python Programming
Program to Demonstrate the Positional Change of Indexes of Arguments Write Python Program to Find the Area and Circumference of a Circle
a = 10 radius = int(input("Enter the radius of a circle"))
b = 20 area_of_a_circle = 3.1415 * radius * radius
print("The values of a is {0} and b is {1}".format(a, b)) circumference_of_a_circle = 2 * 3.1415 * radius
print("The values of b is {1} and a is {0}".format(a, b)) print(f "Area = {area_of_a_circle} and Circumference = {circumference_of_a_circle}")
Output
The values of a is 10 and b is 20 Output
The values of b is 20 and a is 10 Enter the radius of a circle
5
f-strings Area = 78.53750000000001 and Circumference = 31.415000000000003
Formatted strings or f-strings were introduced in Python 3.6. An 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. Specify the name TYPE CONVERSIONS
of the variable inside the curly braces to display its value. An f at the beginning of the string tells Type conversion is explicitly cast, or converts a variable from one type to another.
Python to allow any currently valid variable names within the string.
. Page 19 . Page 20
Python Programming Python Programming
The str() function returns a string which is fairly human readable. complex_with_string = complex("1")
complex_with_number = complex(5, 8)
Program to demonstrate str() Casting Function print(f"Result after using string in real part {complex_with_string}")
s = str(8) print(f"Result after using numbers in real and imaginary part {complex_with_number}")
r = str(3.5)
print (f "After Integer to String Casting the result is {s}") Output
print (f "After Float to String Casting the result is {r}") Result after using string in real part (1+0j)
Result after using numbers in real and imaginary part (5+8j)
Output
After Integer to String Casting the result is 8 The ord() Function
After Float to String Casting the result is 3.5 The ord() function returns an integer representing Unicode code point for the given Unicode
character.
The chr() Function
Program to demonstrate ord() Casting Function
It convert an integer to a string of one character whose ASCII code is same as the integer. The
I = ord('4')
integer value should be in the range of 0–255.
A = ord("Z")
C = ord("#")
Program to demonstrate chr() Casting Function
con = chr(100) print(f" Unicode code point for integer value of 4 is {I}")
print(f 'Equivalent Character for ASCII value of 100 is {con}') print(f" Unicode code point for alphabet 'Z' is {A}")
print(f" Unicode code point for character '$' is {C}")
. Page 21 . Page 22
Python Programming Python Programming
The if decision control flow statement starts with if keyword and ends with a colon. The
The type() Function
expression in an if statement should be a Boolean expression. If the Boolean expression evaluates
The syntax for type() function is,
to True then statements in the if block will be executed; otherwise the result is False then none of
type(object) the statements are executed.
The type() function returns the data type of the given object.
In Python, the if block statements are determined through indentation and the first unindented
Ex: type(1) // It is of type <class 'int'> statement marks the end.
. Page 23 . Page 24
Python Programming Python Programming
if Expression: statement_3
statement_1 :
else: :
statement_2 :
If the Expression evaluates to True, then statement_1 is executed, otherwise it is evaluated to else:
False then statement_2 is executed. Indentation is used to separate the blocks. After the execution statement_last
of either statement_1 or statement_2, the control is transferred to the next statement Also, if and
else keywords should be aligned at the same column position. This if…elif…else decision control statement is executed as follows:
In the case of multiple expressions, only the first logical expression evaluates to True will
print(f"{number} is Even number") If Expression_1 and Expression_2 are False and Expression_3 is True, then statement_3 is
print(f"{number} is Odd number") If none of the Boolean_Expression is True, then statement_last is executed.
. Page 25 . Page 26
Python Programming Python Programming
Write a Program to Prompt for a Score between 0.0 and 1.0. If the Score Is Out of Range, The syntax of the nested if statement is,
Print an Error. If the Score Is between 0.0 and 1.0, Print a Grade Using the Following Table
if Expression_1:
Score Grade
if Expression_2:
>= 0.9 A
statement_1
>= 0.8 B
else:
>= 0.7 C
statement_2
>= 0.6 D
else:
< 0.6 F
statement_3
If the Expression_1 is evaluated to True, then the control shifts to Expression_2 and if the
score = float(input("Enter your score")) expression is evaluated to True, then statement_1 is executed, if the Expression_2 is evaluated to
if score < 0 or score > 1: False then the statement_2 is executed. If the Expression_1 is evaluated to False, then
print('Wrong Input') statement_3 is executed.
elif score >= 0.9:
print('Your Grade is "A" ') Program to Check If a Given Year Is a Leap Year
elif score >= 0.8:
year = int(input('Enter a year'))
print('Your Grade is "B" ')
if year % 4 = = 0:
elif score >= 0.7:
if year % 100 = = 0:
print('Your Grade is "C" ')
if year % 400 = = 0:
elif score >= 0.6:
print(f'{year} is a Leap Year')
print('Your Grade is "D" ')
else:
else:
print(f'{year} is not a Leap Year')
print('Your Grade is "F" ')
else:
print(f'{year} is a Leap Year')
OUTPUT
else:
Enter your score 0.92
print(f'{year} is not a Leap Year')
Your Grade is "A"
4. Nested if Statement
Output
An if statement that contains another if statement either in its if block or else block is called a
Enter a year 2014
Nested if statement.
2014 is not a Leap Year
. Page 27 . Page 28
Python Programming Python Programming
5. The for Loop Program to demonstrate for Loop Using range() Function
The syntax for the for loop is, print("Only ''stop'' argument value specified in range function")
for iteration_variable in sequence: for i in range(3):
statement(s) print(f"{i}")
The for loop starts with for keyword and ends with a colon. iteration_variable can be any valid print("Both ''start'' and ''stop'' argument values specified in range function")
variable name and first item in the sequence gets assigned to the iteration variable. This process of for i in range(2, 5):
assigning items from the sequence to the iteration_variable and then executing the statement print(f"{i}")
continues until all the items in the sequence are completed. print("All three arguments ''start'', ''stop'' and ''step'' specified in range function")
Ex: for each_character in "Blue": for i in range(1, 8, 3):
print(f "Iterate through character {each_character} in the string 'Blue'") print(f"{i}")
Output OUTPUT
Iterate through character B in the string 'Blue' Only ''stop'' argument value specified in range function
Iterate through character l in the string 'Blue' 0
Iterate through character u in the string 'Blue' 1
Iterate through character e in the string 'Blue' 2
Both ''start'' and ''stop'' argument values specified in range function
range() function 2
It is a built-in function, it is useful in for loop. The range() function generates a sequence of 3
numbers which can be iterated through using for loop. 4
All three arguments ''start'', ''stop'' and ''step'' specified in range function
The syntax for range() function is,
1
range([start ,] stop [, step])
4
Both start and step arguments are optional and the range argument value should always be an 7
integer. exit() function
start → value indicates the beginning of the sequence. If the start argument is not specified, then The exit() is defined in site module. It is built-in function to quit and come out of the execution
the sequence of numbers starts from zero by default. loop of the program.
stop → Generates numbers up to this value but not including the number itself.
Ex: for i in range(10):
step → indicates the difference between every two consecutive numbers in the sequence. The step
if i = = 5:
value can be both negative and positive but not zero.
exit()
print(i)
. Page 29 . Page 30
Python Programming Python Programming
OUTPUT Write a Program to Find the Average of n Natural Numbers Where n Is the Input from the
0 User
1 number = int(input("Enter a number up to which you want to find the average"))
2 i=0
3 sum = 0
4 count = 0
while i < number:
6. The while Loop i=i+1
The syntax for while loop is, sum = sum + i6
while Expression: count = count + 1
statement(s) average = sum/count
The while loop starts with the while keyword and ends with a colon. A while statement expression print(f"The average of {number} natural numbers is {average}")
is evaluated, if the expression evaluates to True, the statement in while loop block is executed and
loop is iterated till the condition becomes false. Execution then continues with the first statement OUTPUT
after the while loop. Enter a number up to which you want to find the average 5
The average of 5 natural numbers is 3.0
Ex: i = 0
while i < 5: 7. The continue and break Statements
print(f"Current value of i is {i}") The break and continue statements provide greater control over the execution of code in a
i=i+1 loop. Both continue and break statements can be used in while and for loops.
break
. Page 31 . Page 32
Python Programming Python Programming
continue statement is useful to skip the execution of the current iteration of the loop and continue import calendar
Write a python program to print absolute value, square root and cube of a number. OUTPUT
import math Absolute value of -20 is: 20
def cube(x):
A Few Built-in Functions in Python are as shown in table below.
return x**3
a= -100
Function
print(“a = ”,a) Syntax Explanation
a=abs(a) Name
print(a) abs(x), where x is an integer or The abs() function returns the absolute
abs()
print("Square root of",a,"=", math.sqrt(a)) floating-point number. value of a number. Ex: abs(-3) = 3
print("Cube of", a,"=", cube(a)) min(arg_1, arg_2, arg_3,…, arg_n) The min () function returns the smallest of
min() where arg_1, arg_2, arg_3 are the two or more arguments.
OUTPUT
arguments. Ex: min(1, 2, 3, 4, 5) = 1
a = -100
max(arg_1, arg_2, arg_3,…,arg_n) The max () function returns the largest of
100
max() where arg_1, arg_2, arg_3 are the two or more arguments.
Square root of 100 = 10.0
arguments. Ex: max(4, 5, 6, 7, 8) = 8
Cube of 100 = 1000000
The pow(x, y) function returns x to the
pow() pow (x, y) where x and y are numbers.
PYTHON FUNCTIONS power y. Ex: pow(3, 2) = 9
Function is a group of related statements that perform a specific task. Functions help break our The len() function returns the length or
len(s) where s may be a string, byte,
program into smaller and modular chunks. As our program grows larger and larger, functions len() the number of items in an object.
list, tuple, range, dictionary or a set.
make it more organized and manageable. It avoids repetition and makes code reusable. Ex: len("Japan") = 5
Basically, we can divide functions into the following two types: The divmod() function takes two numbers
divmod(a, b) where a and b are
1. Built-in Function as arguments and return a pair of numbers
divmod() numbers representing numerator and
2. User defined Function consisting of their quotient and remainder.
denominator.
Ex: divmod (5, 2) = (2, 1)
1. Built-in functions
Functions that are built or predefined into Python.
2. User-defined functions - User-defined functions are reusable code blocks created by users to
Ex: abs (), all (), asci (), bool () etc.
perform some specific task in the program.
The syntax for function definition is,
Ex:
integer = -20 def function_name(parameter_1, parameter_2, …, parameter_n):
The function’s name is same naming rules as variables: use letters, numbers, or an underscore, variable to have a string value "__main__". Block of statements in the function definition is
but the name cannot start with a number. Also, you cannot use a keyword as a function name. executed when the function is called.
A list of parameters to the function are enclosed in parentheses and separated by commas.
if __name == "__main__":
Functions may have one or more parameters or any parameters.
statement(s)
A colon is required at the end of the function header. The first line of the function definition
which includes the name of the function is called the function header. The special variable, __name__ with "__main__", is the entry point to your program. When
Block of statements that define the body of the function start at the next line of the function Python interpreter reads the if statement and sees that __name__ does equal to "__main__", it will
header and they must have the same indentation level. execute the block of statements present there.
Arguments or parameters are the actual value that is passed into the calling function. There must main()
be a one to one correspondence between the formal parameters in the function definition and the
actual arguments of the calling function. A function should be defined before it is called and the PASSING PARAMETER/ARGUMENTS
block of statements in the function definition are executed only after calling the function. A function can take parameters nothing but some values that are passed to it so that function can
manipulate them to produce the desired result. These parameter are normal variables are defined
Ex : def my_function():
when we call the function and passed to the function.
print("Hello from a function")
my_function() //Function Call Parameters are specified within the pair of parenthesis in the function definition.
The function name and number of parameter in the function call must be same that given
Function definitions do not alter the flow of execution of the program. When you call a function,
in the function definition otherwise error will be returned.
the control flows from the calling function to the function definition. Once the block of statements
in the function definition is executed, then the control flows back to the calling function and Ex: def area_trapezium(a, b, h):
. Page 37 . Page 38
Python Programming Python Programming
THE RETURN STATEMENT Program to Check If a 3 Digit Number Is Armstrong Number or Not
The function to perform its specified task to calculate a value and return the value to the calling user_number = int(input("Enter a 3 digit positive number to check for Armstrong number"))
function so that it can be stored in a variable and used later. This can be achieved using the def check_armstrong_number(number): //Function Definition
optional return statement in the function definition. result = 0
The syntax for return statement is, temp = number
while temp != 0:
return [expression_list]
last_digit = temp % 10
The return statement terminates the execution of the function definition in which it appears and result += pow(last_digit, 3)
returns control to the calling function. A function can return only a single value, but that value can temp = int(temp / 10)
be a list or tuple. if number = = result:
print(f"Entered number {number} is a Armstrong number")
Program to write sum, different, product and mod using arguments with return value else:
function. print(f"Entered number {number} is not a Armstrong number")
def calculate(a,b): def main():
total = a+b check_armstrong_number(user_number) //Function Call
diff = a-b if __name__ == "__main__":
prod = a*b main()
div = a/b
mod = a%b DEFAULT PARAMETERS
return total, diff, prod, div, mod //return statement It is useful to set a default value to the parameters of the function definition. Each default
a = int(input("Enter a value")) parameter has a default value as part of its function definition. Any calling function must provide
b = int(input("Enter b value")) arguments for all required parameters in the function definition but can omit arguments for
s,d,p,q,m = calculate(a,b) // function call with parameter default parameters. If no argument is sent for that parameter, the default value is used.
print("Sum=",s,"diff= ",d,"mul= ",p,"div= ",q,"mod= ",m) Usually, the default parameters are defined at the end of the parameter list, after any required
parameters and non-default parameters cannot follow default parameters. The default value is
OUTPUT evaluated only once.
Enter a value 6
Enter b value 8 Program to Demonstrate the Use of Default Parameters
Sum= 14 diff= -2 mul= 48 div= 0.75 mod= 6 def area(a, b=30):
print(f"{a} {b}")
area(10, 20)
area(10)
. Page 39 . Page 40
Python Programming Python Programming
using commands. import sys module is used to access command line arguments. All the command so changing the value of the local variable has no effect on the global variable. Only the
line arguments in Python can be printed as a list of string by executing sys.argv. local variable has meaning inside the function in which it is defined.
. Page 41 . Page 42
Python Programming Python Programming
. Page 43 . Page 44
Python Programming Python Programming
EXCEPTION HANDLING USING TRY…EXCEPT…FINALLY The try…except statement has an optional else block, which, when present, must follow all except
Handling of exception ensures that the flow of the program does not get interrupted when an blocks. It is useful for code that must be executed if the try block does not raise an exception.
exception occurs which is done by trapping run-time errors. Handling of exceptions results in the
Instead of having multiple except blocks with multiple exception names for different exceptions,
execution of all the statements in the program.
we can combine multiple exception names together separated by a comma (also called
It is possible to write programs to handle exceptions by using try…except…finally statements.
parenthesized tuples) in a single except block.
The syntax for try…except…finally are as follows
The syntax for combining multiple exception names in an except block is,
try:
try:
statement_1
statement_1
except Exception_Name_1:
except (Exception_Name_1, Exception_Name_2, Exception_Name_3):
statement_2
statement(s)
If any statement within the try block throws an exception, control immediately shifts to except where Exception_Name_1, Exception_Name_2 and Exception_Name_3 are different exception
block. If no exception is thrown in the try block, the except block is skipped. names
try block with multiple exception: Multiple except blocks with different exception names can be A finally block is always executed before leaving the try statement, whether an exception has
chained together. The except blocks are evaluated from top to bottom in code, but only one except occurred or not. When an exception has occurred in the try block and has not been handled by an
block is executed for each exception that is thrown. The first except block that specifies the exact except block, it is re-raised after the finally block has been executed. The finally clause is also
exception name of the thrown exception is executed. executed “on the way out” when any other clause of the try statement is left via a break, continue
If no except block specifies a matching exception name then an except block that does not have or return statement.
an exception name is selected, if one is present in the code. Program to Check for ValueError Exception
while True:
try:
try:
statement_1
number = int(input("Please enter a number: "))
except Exception_Name_1:
print(f"The number you have entered is {number}")
statement_2
break
except Exception_Name_2:
except ValueError:
statement_3
print("Oops! That was no valid number. Try again…")
OUTPUT
else:
Please enter a number: g
statement_4
Oops! That was no valid number. Try again…
finally:
Please enter a number: 4
statement_5
The number you have entered is 4
. Page 45 . Page 46
Python Programming
OUTPUT
Case 1
Enter value for x: 8
Enter value for y: 0
Division by zero!
Executing finally clause
Case 2
Enter value for x: p
Enter value for y: q
Executing finally clause
. Page 47