×

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.


Related Topics

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Python Lexicographic Order

Python lexicographic order Before we discuss the lexicographic order in Python, we should understandwhat is lexicographic order and sort according to lexicographic order. Lexicographic order In mathematics, the generalization of the alphabetical order...

5 minutes read.

Python email utils

Python is a popular programming language in this growing world. There are many resources to learn python online without spending a single penny. In this article, we will talk about a...

4 minutes read.

How to run Python code from the command prompt

The Windows operating system's command-line interpreter is CMD or Command Prompt. The "MS-DOS Prompt" is comparable to Command.com, used in DOS and Windows 9x computers. It is similar to Unix...

3 minutes read.

Comments in the Python Programming Language

In this tutorial, we will learn how to comment in multiple lines and paragraphs in the python programming language. Commenting a Paragraph in Python Most people think the importance of comments is...

2 minutes read.

Accuracy_score Function in Sklearn

A crucial stage in data science is measuring our model's performance using the appropriate metric. In this article, we will examine two methods for calculating the accuracy of your predictions:...

13 minutes read.

How to check if the dictionary is empty in Python?

What is a dictionary in Python? A directory is a collection of data but data is not ordered. Unlike other data types, it does not hold a single value as its...

3 minutes read.

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the...

5 minutes read.

Rank Based Percentile GUI Calculator using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With the capabilities...

3 minutes read.

How to Update Python?

How to Update Python In this article, we will discuss how we can update Python in our system. For a better understanding, this article will cover all the steps right from installation...

4 minutes read.

Time. Sleep() in Python

Python time sleep () function suspends execution for a certain seconds given by user. Time sleep () syntax: Sleep(seconds) Limitations: The number of seconds to be suspends the code as per its requirements. Returns: Void The execution...

3 minutes read.

ER diagram of the Bank Management System in python

What is an ER diagram? The full form of the ER diagram is the Entity Relationship diagram. This diagram is used in database management systems to have a rough idea of...

3 minutes read.

Working with files in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has an...

5 minutes read.

Sys Module in Python

What are Modules? The Modules are the kind of files that contain Python statements and definitions. The module is known by the name of the file followed by the suffix “.py”....

5 minutes read.

List Subtract in Python

The List is one of the most unique Data Structures in Python. It is generally used to store multiple values in just one single variable. It is one of the...

4 minutes read.

Python K-Means Clustering

K-Means Clustering is a basic yet incredible calculation in information scienceThere are a plenty of true utilizations of K-Means clustering (a couple of which we will cover here)This far reaching...

25 minutes read.

Python pow() Function

Python pow() Function The pow() function in Python return the parameter ‘x’ to the power ‘y’ and if the parameter ‘z’ is present, it returns x to the power y, modulo z (computed more efficiently than pow(x, y) % z). Syntax pow(x, y[, z]) Parameter x: This parameter represents the base...

1 minute read.

Gaussian elimination in python

Linear and polynomial equations are used in almost all fields of numerical simulation. However, its most common use in engineering is in the area of linear system analysis. The broader...

3 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

How To Install Python In Ubuntu

How To Install Python In Ubuntu Ubuntu is free and open-source software and it is an essential part of the Linux distribution. It is a popular operating system developed by Canonical. If we...

3 minutes read.