Python Tutorial

Introduction Python Features Python Applications System requirements for Python Python Installation Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Anonymous/Lambda Function in Python

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor

Python Iterators

Iterators in Python Yield Statement In Python

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Calendar Module  

Python MySQL

Python MySQL Python MySQL Update Operation Python MySQL Delete Operation

Python MongoDB

Python MongoDB

Python Data Structure Implementation

Python Stack Python Queue Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Collections in python Python Enumerate Python Debugger Python DefaultDict

Misc

Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering List Comprehension in Python3 NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Logical Operators Python Multiprocessing Python History Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Design patterns in python Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python Abstract design pattern in python Builder design pattern in python

How to

How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python Singleton design pattern in python

Python Errors and exceptions

Exceptions and errors are the obstacles a programmer constantly faces while writing a program. Firstly, we need to understand what are errors and exceptions and the difference between these two similar yet different words.

Errors are of two types – syntax errors and logical errors. Errors generally occur at the compilation time due to the programmer's mistake. Syntactical errors occur when the programmer misses following the syntax rules, whereas logical errors occur when he makes a mistake in the logic of the code. Logical errors are not raised but are found when the output is incorrect. On the other hand, when a syntax error occurs, the interpreter will not execute the program.

Exceptions, on the other hand, are runtime errors. These occur at the run time. When exceptions are raised, the normal flow of the program will not be stopped, but altered and disturbs the whole flow of the program and sometimes terminates at the statement with an exception.

Syntax errors

Every single entity or a statement in Python has its predefined syntax. It is like the spelling of words in English. If we make a mistake in the spelling, it is no longer a correct word. In the same way, if we do not follow the syntax rules in Python, the statement is not correct. A syntax error is raised, and the program execution halts.

Syntax error can occur when:

  1. The syntax of statements is not followed
  2. Due to a missing colon
  3. Wrong indentation
  4. Missing a required keyword
  5. Misspelling a keyword or the name of a method.

Example code:

1. #Missing colon in if statement

a = int (input ("Enter the value of a: "))
if (a%2 == 0)
# if (a%2 == 0): -> correct use -> colon
    print (a, "is an even number")
else:
    print (a, "is not an even number")

Output:

  File "D:\Programs\python\syntaxerror1.py", line 2
    if (a%2 == 0)
                 ^
SyntaxError: invalid syntax

2. #Wrong indentation

a = int (input ("Enter the value of a: "))
if (a%2 == 0):
print (a, "is an even number")
    #print (a, “is an even number”) -> correct indentation
else:
    print (a, "is not an even number")

Output:

File "D:\Programs\python\syntaxerror2.py", line 3
    print (a, "is an even number")
    ^
IndentationError: expected an indented block.

3. #Misspelling a keyword (if)

a = int (input ("Enter the value of a: "))
iff (a%2 == 0): #if -> correct spelling
    print (a, "is an even number")
else:
    print (a, "is not an even number")

Output:

  File "D:\Programs\python\syntaxerror3.py", line 2
    iff (a%2 == 0):
                         ^
SyntaxError: invalid syntax

4. #Missing a keyword (if)

a = int (input ("Enter the value of a: "))
(a%2 == 0): #if (a%2==0) -> if keyword is missed
    print (a, "is an even number")
else:
    print(a, "is not an even number")

Output:

File "D:\Programs\python\syntaxerror4.py", line 2
     (a%2 == 0):
                         ^
SyntaxError: invalid syntax

5. #Syntax not followed

All the above conditions come under syntax not followed too.

a = int (input ("Enter the value of a: "))
if: #if (condition): -> correct syntax
    print (a, "is an even number")
else:
    print(a, "is not an even number")

Output:

File "D:\Programs\python\syntaxerror5.py", line 2
     if:
      ^
SyntaxError: invalid syntax

Understanding:

Here, we missed the condition for the if statement.

Logical Errors

After passing the syntax test, if the code is not giving the accurate and expected output, it means it is flawed and there is a logical error. These errors are not detected. The programmer needs to use different sample test cases to check if the logic is right and the result is correct. Finding logical errors can be very hard in vast and complicated codes. Finding such huge bugs after writing the code is called debugging.

These occur when the program runs without crashing but produces an incorrect result.

These types of errors can occur due to:

  1. Using the wrong variable name
  2. Flawed indentation
  3. Using integer division where floating-point division is to be used.
  4. Not verifying operator precedence, etc.

Examples:

1. #Using wrong variable name

a = int (input ("Enter the first number: "))
b = int (input ("Enter the second number: "))
sum = a + b
print ("The sum of a and b is", a);
#print ("The sum of a and b is", sum); -> correct variable name

Output:

Expected output:
Enter the first number: 20
Enter the second number: 30
The sum of a and b is 50


Observed output due to the use of a in the place of sum:
Enter the first number: 20
Enter the second number: 30
The sum of a and b is 20

2. #Flawed indentation

a = int (input ("Enter the value of a: "))
if (a%2 == 0):
    print (a)
print ("is an even number")
    #print (“is an even number”) -> correct indentation
if (a%2!=0):
    print(a, "is not an even number")

Output:

Expected output:
Enter the value of a: 5
5 is not an even number


Observed output due to flawed indentation of the print statement after the first if statement:
Enter the value of a: 5
is an even number
5 is not an even number

3. # using integer division where floating-point division is to be used.

a = float (input ("Enter the value of a: "))
b = float (input ("Enter the value of b: "))
print (a//b)
#print (a/b) -> correct use -> floating point division

Output

Expected output:
Enter the value of a: 4
Enter the value of b: 5.6
0.7142857142857143


Observed output due to use of integer division when we want float quotient
Enter the value of a: 4
Enter the value of b: 5.6
0.0

4. #Not checking operator precedence

a = int (input ("Enter the value of a: "))
b = int (input ("Enter the value of b: "))
print (a/ b+3)
#print (a/ (b+3))  -> correct use of operators.

Output:

Expected output:
Enter the value of a: 4
Enter the value of b: 3
0.6666666666666666


Observed output:
Enter the value of a: 4
Enter the value of b: 3
4.333333333333333

Exceptions

Exceptions are run time errors, which mean that the code has passed the syntax test, and when the interpreter runs it, it is crashed unexpectedly due to some internal problem in the code that is not detected at the start. The interpreter will crash the program once it reaches the line with the error.

Such programs work well for some sample test cases, but the program might get crashed for some. Hence, we need to consider every possible set of inputs for the program and check.

Exceptions can occur when:

  1. We try to divide by 0
  2. We try to do operations on incompatible data type variables
  3. We try to access a variable that is not defined
  4. We try to access an index in a list or a dictionary that does not exist
  5. We try to access an un-existing file.

Note: The program will be executed until the line with the exception and crashes once the line is reached, unlike errors where the program won't execute.

Examples:

1. #Division by zero

a = int (input ("Enter the value of a: "))
b = int (input ("Enter the value of b: "))
print (a/b)

Output:

Enter the value of a: 4
Enter the value of b: 0
Traceback (most recent call last):
  File "D:\Programs\python\divisionby0.py", line 3, in <module>
    print(a/b)
ZeroDivisionError: division by zero

2. #Operations on incompatible datatypes

a = int (input ("Enter the value of a: "))
b = input ("Enter the value of b: ") #string
print (a/b)

Output:

Enter the value of a: 4
Enter the value of b: 3
Traceback (most recent call last):
  File "D:\Programs\python\uncompatibility.py", line 3, in <module>
    print(a/b)
TypeError: unsupported operand type(s) for /: 'int' and 'str'

3. #Accessing an undefined variable

a = int (input ("Enter the value of a: "))
print (a/b)

Output:

Enter the value of a: 3
Traceback (most recent call last):
  File "D:\Programs\python\undefined.py", line 2, in <module>
    print (a/b)
NameError: name 'b' is not defined

4. # Accessing a no existing index in a list

a = [1, 2, 3]
print ("The list is: ",a)
print (a[3])

Output:

The list is:  [1, 2, 3]
Traceback (most recent call last):
  File "D:\Programs\python\index.py", line 3, in <module>
    print (a[3])
IndexError: list index out of range

5. #Accessing a file that does not exist

print ("opening a non existing file")
file1 = open ("textfile.txt")
print(file1.read())
file1.close()

Output:

opening a non-existing file
Traceback (most recent call last):
  File "D:\Programs\python\nofile.py", line 2, in <module>
    file1 = open ("textfile.txt")


FileNotFoundError: [Errno 2] No such file or directory: 'textfile.txt'

These are some common situations the programmer might run into errors and exceptions. Errors and exceptions need to be handled after finding, and Python has a special process to handle exceptions. Using try and except blocks, we can handle unexpected exceptions. The concept is called Exception handling.



ADVERTISEMENT
ADVERTISEMENT