Python

What is Python?

  • Python is an interpreted, object-oriented programming language designed to be easy to read and simple to implement. It is open source, which means it is free to use, even for commercial applications.
  • Python can run on Mac, Windows, and Unix systems and has also been ported to Java and .NET virtual machines.
  • Guido Van Rossum is known as the founder of python programming.

Features of Python-

python

 

Who uses Python?

  • Google
  • NASA
  • Dropbox
  • Quera
  • Instagram
  • Youtube
  • Yahoo! Map
  • Shopzilla
  • q& the list goes on…..

Application of Python

  • Web and Internet Development
  • Scientific and Numeric
  • Desktop GUIs
  • Software Development
  • Embedded Systems

 

Contents of Python-

1.Tokens

Integer

3.String

4.Decision Control

5.Loops

6.Sequences

  1. List
  2. Tuple
  3. Dictionary

7.Function

8.Modules

9.File Handling

10.OOPS concepts

Tokens-

Token is the smallest unit inside the given program.

There are following tokens in Python:

1.Keywords.

2.Identifiers.

3.Data Types.

4.Operators.

Keywords-

  • Keywords are special reserved words which convey a special meaning to the compiler/interpreter.
  • Each keyword have a special meaning and a specific operation. List of Keywords used in Python are:

True                    False                       None                and                asset

def                      class                        continue         break              else

finally               elif                            del                    except             global

for                     if                               from                import              raise

try                    or                              return             pass                   nonlocal

in                    not                              is                     lambda             as

 

Identifiers-

Identifiers are the names given to the fundamental building blocks in a program.

These can be variables ,class ,object ,functions , lists , dictionaries etc.

There are certain rules defined for naming i.e., Identifiers.

  1. An identifier is a long sequence of characters and numbers.
  2. No special character except underscore ( _ ) can be used as   an  identifier.
  3. Keyword should not be used as an identifier name.
  4. Python is case sensitive. So using case is significant.
  5. First character of an identifier can be character, underscore   ( _ ) but not digit.

Data types-

1.String :

  String  can be formed by enclosing a text in the quotes. We can use both single as well as double quotes for a String.

eg:”Aman” , ‘12345‘

2.Numeric:

a.Int :  Numbers that can be both positive and negative.

eg: 100

  1. Long : Integers of unlimited size followed by lowercase or uppercase L.

eg: 87032845L

  1. Float : Real numbers with both integer and fractional part.

eg: -26.2

d.Complex : In the form of a+bj where a forms the real part and b forms the imaginary part of complex number.

eg: 3.14j

3.Boolean :

  A Boolean datatype can have any of the two values: True or False.

  1. Special literals.

  Python contains one special data type i.e., None.

None is used to specify to that field that is not created.

  1.   Collections :

Collections such as tuples, lists and Dictionary are used in Python.

 

Operators-

Operators are particular symbols which operate on some values and produce an output.

  Python supports the following operators:

1.Arithmetic Operators.

2.Relational Operators.

3.Assignment Operators.

4.Logical Operators.

5.Membership Operators.

6.Identity Operators.

7.Bitwise Operators.

Arithmetic Operators : –

a.//      Perform Floor division(gives integer value after division)

b.+      To perform addition

c.-      To perform subtraction

d.*           To perform multiplication

e./              To perform division

f.%             To return remainder after division(Modulus)

g.**      Perform exponent(raise to power)

Relational Operators :-

a.<       Less than

b.>       Greater than

c.<=      Less than or equal to

d.>=      Greater than or equal to

e.==      Equal to

f.!=      Not equal to

Assignment Operators :-

a.=        Assignment

b./=       Divide and Assign

c.+=       Add and assign

d.-=        Subtract and Assign

e.*=        Multiply and assign

f.%=       Modulus and assign

g.**=         Exponent and assign

h.//=         Floor division and assign

Logical Operators :-

a.and  Logical AND(When both condn. are true output will be true)

b.or  Logical OR (If any one condn. is true output will be true)

c.not  Logical NOT(Compliment the condn. i.e., reverse)

Membership Operators :-

a.in  Returns true if a variable is in sequence of another   variable, else false.

b.not in  Returns true if a variable is not in sequence of another   variable, else false.

Identity Operators :-

a.is  Returns true if identity of two operands are same, else   false

b.is not  Returns true if identity of two operands are not same,   else false.

Numeric Coding Time

code

1.Write Program to Exchange the Values of Two Numbers Without Using a Temporary Variable

2.Write a Program for computing area and circumference of circle.

3.Write a Program for note denomination in 2000 , 500 and 100.

4.Write a Program to calculate the simple interest given in all the required values.

5.Write a Program to calculate the total and average of 5 subject marks.

 

String-

Strings are the simplest and easy to use in Python.

Accessing Strings:-

a.In Python, Strings are stored as individual characters in a contiguous memory location.

b.The benefit of using String is that it can be accessed from both the directions in forward and backward.

c.Indexing are provided using Strings in Python.

  • Forward indexing starts with 0,1,2,3,….
  • Backward indexing starts with -1,-2,-3,-4,….

Example

index

String operation-

There are basically 3 types of Operators supported by String:

a.Basic Operators.

b.Membership Operators.

c.Relational Operators.

Basic Operators :-

  • + String Concatenation
  • * String Repetition

Membership Operators :-

  • in substring in string true otherwise false.
  • not in substring is not in string is true otherwise false.

Relational Operators :-

  • All the comparison operators i.e., (<,><=,>=,==,!=,<>) are also applicable to strings

String Slicing-

  • String slice can be defined as substring which is the part of string. Therefore further substring can be obtained from a string.
  • There can be many forms to slice a string. As string can be accessed or indexed from both the direction and hence string can also be sliced from both the direction that is left and right.

  Syntax:-

<string_name>[startIndex:endIndex],

<string_name>[:endIndex],

<string_name>[startIndex:]

String Functions-

capitalize()  It capitalizes the first character of the   String.

count(string)  Counts number of times substring   occurs in a String between begin and   end

endswith(suffix)  Returns a Boolean value if the string   terminates with given suffix between   begin and end.

find(substring)  It returns the index value of the   string where substring is found   between begin index and end   index.

index(subsring)  Same as find() except   it raises an   exception if string is not found.

isalnum()  It returns True if characters in the   string are alphanumeric i.e.,   alphabets or numbers and   there is at least 1 character.   Otherwise it returns False.

isalpha()  It returns True when all the   characters are alphabets and there   is at least one character, otherwise   False. Even space is not allowed

replace(old,new)  it replace the old substring with new   substring.

isdigit()  It returns True if all the characters are   digit and there is at least one character,   otherwise False.

islower()  It returns True if the characters of a   string are in lower case, otherwise False.

isupper()  It returns False if characters of a string   are in Upper case, otherwise False.

isspace()  It returns True if the characters of a   string are whitespace, otherwise false.

len(string)  len() returns the length of a string.

lower()  Converts all the characters of a string to   Lower case.

upper()  Converts all the characters of a string to   Upper Case.

startswith(str )  Returns a Boolean value if the string   starts with given str between begin  and end.

swapcase()  Inverts case of all characters in a   string.

lstrip()  Remove all leading whitespace of a   string. It can also be used to remove   particular character from leading.

rstrip()  Remove all trailing whitespace of a   string. It can also be used to remove   particular character from trailing.

split()  it split the string by mentioned   character or integer.

 

String Coding Time

code2

1.Write a program takes a string and replaces every blank space with a hyphen.

2.Write a program takes a string and swaps the first character and the last character of the string.

3.Write a program takes a string and replaces all occurrences of ‘a’ with ‘$’.

4.Write a program to calculate the no. of character in string given by user.

5.Write a program to count a char (‘i’) in given string by user.

6.Write a program to split the string given by user by the space.

Decision Control-

a.if Statement :-

The if statement in python which is used test a condition. If condition is true, statement of if block is executed otherwise it is skipped.

 

  syntax :-

 if(condition):                                                                                             
decision1        statements

        

 

 

 

 

b.if-else Statement :-

  The if statement in python which is used test a condition. If condition is true, statement of if block is executed otherwise else block is

executed.

 

syntax :-

  if(condition):                                     condition 2

           statements  

  else:

      statements

 

 

 

 

c.Ladder If statements :-

  In case of multiple if condition haves then we use elif.

syntax :-

  if(condition): 

           statements  

  elif(condition):   condition3

      statements

  else:

      statements

 

 

 

d.Nested if-else statements :-

syntax :-

  if(condition): 

        if(condition):

                  statements

        else:

             statements  

  else:

        if(condition):

             statements

       else:

           statements

 

Decision control Coding Time-

cd3

1.Write a Program to check whether a number is positive or Negative.

2.Write a Program to take in the marks of 5 subjects and Display the grade.

3.Write a Program to check user name and password take by user is correct or not.

4.Write a Program to check given no is leap year or not.

5.Write a Program to check given no is even or odd.

6.Write a Program to check the largest no in 3 no given by user.

7.Write a Program to take 3 subjects marks from user and then check all individual mark are should be greater then 35.

 

Loops-

  • To keep doing useful work we need repetition, looping back over the same block of code again and again.

Types of loops-

–While

–For

–Nested loop

a.while Statement :-

The while loop tells the computer to do something as long as the condition is met it’s construct consists of a block of code and a condition. It works like this: “while this is true, do this“.

 

syntax :-

 

  initialization                                                                loop1

  while(condition): 

           statements  

      updation

 

 

 

 

While loop Coding Time-

cde2

1.Write a Program to find the sum of digits in a number.

2.Write a Program to count the number of digits in a number.

3.Write a program to calculate reverse number.

4.Write a program to calculate the factorial number.

5.Write a program to print table.

6.Write a program for zero termination.

7.Write a program to find out odd number in 0 to 100.

1.for Statement :-

The for loop that is used to iterate over elements of a sequence, it is often used when you have a piece of code which you want to repeat “n” number of time.

syntax :-                                                                    for

  for<var> in <sequence>: 

       statements  

 

 

 

For loop Coding Time-

code4

1.Write a Program to print all numbers in a range divisible by a given number.

2.Write a Program to calculates the length of the string without using library functions.

3.Write a program to print the character or alphabet in given string : “DUCAT_PYTHON”.

4.Write a print to change character in string into upper case.

5.Write a program to make the encryption and decryption of string.

6.Write a program to change character ‘A’ to ‘#’ in string.

c.Nested while :-

syntax :

while (condition1) :

while(condition 2) :

statement

statement(optional)

d.Nested for :-

syntax :

for <var> in <sequence>:

for <var> in <sequence>:

statement

statement

Miscellenous condition :

übreak

ücontinue

üelse

a.break :   break is used to exit a for loop or a while loop.

b.continue :  continue is used to skip the current block, and   return to the “for” or “while” statement.

c.else :  we can use else for loops. When the loop condition   of “for” or “while” statement fails then code part in   “else” is executed.

 

Nested looping Coding Time-

code5

 

1.Write a program of digital clock using nested looping.

2.Write a program to make table from 2 to 100 using looping.

3.Write a program to make decision table with ‘yes’ or ‘no’.

Sequences-

  • An sequence is an object that holds multiple items of data, stored one after another.
  • You can perform operations on a sequence to examine and manipulate the items stored in it.
  • Its is the most basics type of data structure in python.
  • Each element of a sequences is assigned a no of position or index.
  • The first index is 0, second index is 1 and so on.

Types of Sequence:

  • String
  • List
  • Tuple
  • Dictionary

List-

  • List is the most versatile collection available in python which can be written as a list of data type or items between the square brackets.
  • Important thing is that ,items in list not need to be same type.
  • Lists are mutable, which means that, the contents can be change during program execution.
  • Lists are dynamic in nature, items in list can be added or removed from them.

Syntax :-

<list_name>=[value1,value2,value3,…,valuen]

There are Various Operators supported by List:

  • Adding of two lists.
  • Replicating lists.
  • List slicing.
  • Updating element in list.
  • Deleting element in list.

List Functions-

  • min(list)  Returns the min value from the list given.
  • max(list)  Returns the max value from the given list.
  • len(list)  Returns number of elements in a list.
  • cmp(list1,list2)  Compares the two list.
  • list(seq)  Converts the sequence into list.
  • index(object)  Returns the index value of the object.
  • count(object)  It returns the number of times an object is   repeated in list.
  • sort()  It is used to sort the elements of the List.
  • reverse()  Reverse the position of all the elements of a   list.
  • pop()/pop(index)  Returns the last object or the specified   indexed object. It removes the popped   object.
  • insert(index,obj)  Insert an object at the given index.
  • extend(seq)  It adds the sequence to existing list.
  • remove(object)  It removes the object from the given List.
  • append(object)  Insert an object at the last index of List.

List Coding time

code6

1.Write a Program to Find the Largest Number in a List.

2.Write a Program to Merge Two Lists and Sort it.

3.Write a Program to Swap the First and Last Value of a List.

4.Write a Program to Read a List of Words and Return the Length of the Longest One.

5.Write a Program to Put Even and Odd elements in a List into Two Different Lists.

6.Write a program to sum of all list elements and print.

7.Write a Python program to print a specified list after removing the 0th, 4th and 5th elements.

List : [‘Red’, ‘Green’, ‘White’, ‘Black’, ‘Pink’, ‘Yellow’]

8.Write a Program Takes two lists and returns True if they have at least one common member.

Tuples-

  • Tuples, which can be written as a list of data type or items between the parentheses and separated by comma.
  • Important thing is that ,items in list not need to be same type.
  • Tuples are immutable, which means that, the contents can not be changed.
  • To writing a tuple containing a single value you have to include a ’ , ’. Even though there is only one value.

Syntax :-

<Tuple_name>=(value1,value2,value3,…,valuen)

There are Various Operators supported by Tuples:

  • Adding of two tuples.
  • Replicating tuples.
  • Tuple slicing.

Tuple Functions-

  • min(tuple)  Returns the min value from a tuple.
  • max(tuple)  Returns the max value from the tuple.
  • len(tuple)  Gives the length of a tuple
  • cmp(t1,t2)  Compares the two Tuples.
  • tuple(seq)  Converts the sequence into tuple

Why Use Tuple?

  • Processing of Tuples are faster than Lists.
  • It makes the data safe as Tuples are immutable and hence cannot be changed.
  • Tuples are used for String formatting.

Tuple Coding Time

code7

1.Write a Python program to find the repeated items of a tuple, item is given by user.

tuple_1 = (2, 4, 5, 6, 2, 3, 4, 4, 7 ).

2.Write a Python program to check whether an element exists within a tuple.

tuple_2 = (‘D’,’u’,’c’,’a’,’t’,’ ’,’I’,’n’,’d’,’i’,’a’).

3.Write a Python program to convert a tuple to a list.

4.Write a Python program to remove an item from a tuple.

5.Write a Python program to convert a tuple to a string.

tuple_3 = (‘e’, ‘x’, ‘e’, ‘r’, ‘c’, ‘i’, ‘s’, ‘e’, ‘s’)

Dictionary

  • A dictionary is an object that stores a collection of data.
  • Each element in dictionary has two parts : a key and a value.
  • We can use the key to locate the specific value.
  • Key are unique within dictionary while values may be not.
  • The value of dictionary can be of any type.
  • Keys must be of an immutable datatype such as string, number or tuples.
  • The key and the value is separated by a colon(:). This pair is known as item. Items are separated from each other by a comma(,).
  • Different items are enclosed within a curly brace and this forms Dictionary.
  • Syntax :

<Dict_name>={‘key1’:‘value1′ ,’Key2’:‘value2′ ,’key3’:’value3′}

Operation & Functions-

There are Various Operators supported by Dictionary:

  1. Updation
  2. Deletion
  • len(dict)  Gives number of items in a dictionary.
  • cmp(dict1,dict2)  Compares the two dictionaries.
  • str(dict)  Gives the string representation of a string.
  • keys()  Return all the keys element of a dictionary.
  • values()  Return all the values element of a dictionary.
  • items()  Return all the items(key-value pair) of   a dictionary
  • clear()  It is used to remove all items of a dictionary.   It returns an empty dictionary.
  • fromkeys(seq,val1)/ fromkeys(seq)  It is used to create a new dictionary from   the sequence.
  • copy()  It returns an ordered copy of the data.
  • has_key(key)  It returns a boolean value. True in case if   key is present in the dictionary ,else false.
  • get(key)  Returns the value of the given key. If key   is not present it returns none.
  • update(dict2)  It is used to add items of dictionary2 to   first dictionary.

Dictionary Coding Time

code8

1.Write a Program to Remove the Given Key from a Dictionary.

2.Write a Program to Multiply All the values in a Dictionary.

3.Write a Program to Check if a Given Key Exists in a Dictionary or Not.

4.Write a Program to Concatenate Two Dictionaries Into One.

5.Write a Python script to print a dictionary where the keys are numbers between 1 and 10 (both included) and the values are square of keys.

6.Write a Python program to combine two dictionary adding values for common keys.

7.Write a Python program to create a dictionary from a string.

Sets

  • A set contains a collection of unique values and works as mathematical set.
  • All elements in set must be unique. no two elements can have the same value.
  • Sets are unordered, which means that the elements in a set are not stored in any particular order.

Operation & Functions

There are Various Operators supported by Set:

add(ele)  an element will only be added, if it is not   already contained in the set.

clear()  All elements will removed from a set.

copy()  Creates a shallow copy, which is returned.

difference()    This method returns the difference of two   or more sets as a new set.

discard(ele)  An element el will be removed from the   set, if it is contained in the set.

intersection(set)  A set with all the elements which are   contained in both sets is returned.

issubset(set)  returns True, if x is a subset of y.

issuperset(set)  returns True, if x is a superset of y.

pop()  remove and return an arbitrary set element

Set Coding Time

code9

1.Write a Program to Count the Number of Vowels Present in a String using Sets.

2.Write a Program to Check Common Letters in Two Input Strings.

3.Write a Program that Displays which Letters are in the First String but not in the Second.

4.Write a Python program to find the length of a set.

What is Function?

  • A function is a piece of code that performs a task of some kind.
  • Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. Also functions are a key way to define interfaces so programmers can share their code.
  • A programming approach in which functions are used is know as structured programming.

There are two kinds of functions in python:

1.Built-in function that are provided to the user by the programming lang. just for making programming easier.

2.User-defined function that the user code itself to obtain some custom functionality which is not already provided by the language.

A function has a name that is used when we need for the task to be executed.function to do something is known as calling the function.

  • Function may take one, many or no inputs to perform operations is known as arguments.
  • Some functions give back the value, others do not. If a function gives back a value, is called returning the value.
  • Syntax :

def function_name(arguments):

statements

Types of functions

  1. Without return type, without arguments

syntax :   def fun():

            statements

  1. Without return type, with arguments

  syntax :   def fun(arguments):

            statements

  1. With return type, without arguments

  syntax :   def fun():

            statements

      return  statement

  1. With return type, with arguments

  syntax :   def fun(arguments):

            statements

       return statement

Recursive and lambda function

  • Recursion is a way of programming or coding a program, in which function calls itself one or more time in its body.
  • It keeps returning the value until some condition met.
  • There must be some condition to terminate the recursion , other wise program will become infinite loop.
  • Syntax:

  def fun(arg):

  return (fun(arg))

  • Anonymous Functions are the functions that are not bond to name.
  • Anonymous Functions are created by using a keyword “lambda”.
  • Lambda takes any number of arguments and returns an evaluated expression.
  • Lambda is created without using the def keyword.
  • Syntax:

  lambda arg1,args2,?,argsn: expression

Function Coding Time

code10

1.Write a Program to take two input form user and make decision calculator using function.

2.Write a program for amount calculation given by user.

3.Write a Program to find the factorial of a number given by user.

4.Write a Program to reserve a string given by user.

5.Write a program to calculated sum of all element in a list given by user.

6.Write a program to append tuple by the element given by user.

7.Write a Program Takes two lists and returns True if they have at least one common member.

8.Write a Python program to find the repeated items of a tuple, item is given by user.

tuple_1 = (2, 4, 5, 6, 2, 3, 4, 4, 7 ).

9.Write a Program to Multiply All the Items in a Dictionary.

10.Write a Program to Count the Number of Vowels Present in a String using Sets.

11.Write a Program to reserve a number given by user using recursive function.

File Handling

  • File handling is used to generate the output of the program to the particular file.
  • Python provides basic functions and methods necessary to manipulate files by default.
  • In Python, a file is categorized as either text or binary.
  • Text files are structured as a sequence of lines, where each line includes a sequence of characters. This is what you know as code or syntax.
  • Binary files can only be processed by an application that know or understand the file’s structure. In other words, they must be applications that can read and interpret binary.

How to manipulate file handling

Python allows its user to process files for various applications. like:

  • Read data from file.
  • Write data into the file.

Performing this operations on file involves these steps.

  • Opening the file.
  • Read/write data from/into the file.
  • Closing the file.

Closing is necessary, not closing it may result in loss of data file.

Function and Mode

function_mode

File handling Coding Time

  • Write a python Program to Count the Number of Words in a Text File
  • Write a python program to Count the Occurrences of a Word in a Text File
  • Write a python program to Read a Text File and Print all the Numbers Present in the Text File
  • Write a python program to Copy the Contents of One File into Another
  • Write a python program to Append the Contents of One File to Another File

 

OOPS concepts

 

  • Object Oriented Programmingis a popular methodology of programming any application.
  • Object Oriented programming is a programming style that is associated with the concept of Class, Objects and various other concepts revolving around these two, like Inheritance, Polymorphism, Abstraction, Encapsulation etc.
  • An object can be anything that we see around us. It can be a human (that has some properties like – name, address, DOB and so on), a chair (portrayed by size, material, cost etc), a school (depicted by place, student strength, results) etc.
  • Object oriented programming brings programming close to real life, as we are always dealing with an object, performing operations on it, using it’s methods and variables etc.

Major principles of object-oriented programming system are:

  • Object
  • Class
  • Inheritance
  • Polymorphism
  • Data Abstraction
  • Encapsulation

Object : Object is an entity that has state and behavior. It may be anything. It may be physical and logical. For example: mouse, keyboard, chair, table, pen etc.

Class : A class is a blueprint for the object. It is a logical entity that has some specific attributes and methods. For example: if you have an employee class then it should contain an attribute and method i.e. an email id, name, age, salary etc.

Inheritance : Inheritance is a feature of object-oriented programming. It specifies that one object acquires all the properties and behaviours of parent object. By using inheritance you can define a new class with a little or no changes to the existing class. The new class is known as derived class or child class and from which it inherits the properties is called base class or parent class.

It provides re-usability of the code.

Polymorphism : Polymorphism is a concept, which allows us to redefine the way something works, by either changing how it is done or by changing the parts using which it is done. Both the ways have different terms for them.

Encapsulation : Encapsulation is also the feature of object-oriented programming. It is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together within a single unit from being modified by accident.

Abstraction : Abstraction means, showcasing only the required things to the outside world while hiding the details.  Abstracting something means to give names to things, so that the name captures the core of what a function or a whole program does.

OOPs Coding Time

code11

  1. Write a python program to Find the Area of a Rectangle Using Classes
  2. Write a python program to Append, Delete and Display Elements of a List Using Classes
  3. Write a python program to Create a Class which Performs Basic Calculator Operations
  4. Write a python program to Create a Class in which One Method Accepts a String from the User and Another Prints it
  5. Write a python program to share value using inheritance
  6. Write a python program to add to object values using operator overloading.

  Modules & packages

I.Modules are used to categorize code in Python into smaller part. A module is simply a file, where classes, functions and variables are defined. Grouping similar code into a single file makes it easy to access.

II.Python provides the following advantages for using module:

I.1) Reusability: Module can be used in some other python code. Hence it provides     the facility of code reusability.

II.2) Categorization: Similar type of attributes can be placed in one module.

Importing a Module

There are different ways by which you we can import a module. These are

as follows:

Using import statement: 

  “import” statement can be used to import a module.

  Syntax:

   import <file_name1, file_name2,…file_name(n)=””> </file_name1,>

Using from.. import statement:

from..import statement is used to import particular attribute from a module. In case you do not want whole of the module to be imported then you can use from ?import statement.

  Syntax:

  from<module_name> import <attribute1,attribute2,…attributen>

Packages

A Package is simply a collection of similar modules, sub-packages etc.

Steps to create and import Package:

Create a directory, say Info

Place different modules inside the directory. We are placing 3 modules msg1.py, msg2.py and msg3.py respectively and place corresponding codes in respective modules. Let us place msg1() in msg1.py, msg2() in msg2.py and msg3() in msg3.py.

Create a file __init__.py which specifies attributes in each module.(__init__.py is simply a file that is used to consider the directories on the disk as the package of the Python. It is basically used to initialize the python packages.)

Import the package and use the attributes using package.

 Coding Time

code12

Exception Handling

  • Exception can be said to be any abnormal condition in a program resulting to the disruption in the flow of the program.
  • Whenever an exception occurs the program halts the execution and thus further code is not executed. Thus exception is that error which python script is unable to tackle with.
  • Exception in a code can also be handled. In case it is not handled, then the code is not executed further and hence execution stops when exception occurs.
  • Hierarchy Of Exception:

–ZeroDivisionError: Occurs when a number is divided by zero.

–NameError: It occurs when a name is not found. It may be local or global.

–IndentationError: If incorrect indentation is given.  etc..

exception

  • Syntax:
  • try:
  • Code
  • finally:

code which is must to be executed.

Coding Time

last

Leave a comment

Create a free website or blog at WordPress.com.

Up ↑

Design a site like this with WordPress.com
Get started