The Wayback Machine - https://web.archive.org/web/20241002030323/https://www.geeksforgeeks.org/indentation-error-in-python/
Open In App

Indentation Error in Python

Last Updated : 13 Oct, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will explore the Indentation Error in Python. In programming, we often encounter errors. Indentation Error is one of the most common errors in Python. It can make our code difficult to understand, and difficult to debug. Python is often called a beautiful language in the programming world because we are restricted to code in a formatted manner otherwise it shows an Indentation error. Here we will discuss, the cause of Indentation error and the fixation of it.

What is an Indentation error?

An error is a mistake or issue that prevents the computer program from being run perfectly, Indentation error is one of those. Indentation error occurs in the compilation phase. An Indentation error is a compile-time error that occurs when tabs or spaces in a code do not follow expected patterns. This is typically a syntax error.

Indentation Error is a very common error in Python. Because Python is an interpreted language, its interpreter reads the code line by line. In Python coding, we have to write code that is appropriately formatted with perfect use of gaps to make the code Executable. This perfect use of gaps is termed as indentation. If the user does not write code with proper indentation, it generates an indentation error.

Cause of Indentation error in Python

Indentation error occurs when the number of spaces at the beginning of a block is not equal to the number of spaces assigned at the end. This is the root cause of the Indentation error in Python.

The following are the reasons of the Indentation error in Python code:

  • Misplacing gaps and spaces.
  • Using tabs and spaces during coding.
  • Failing to properly indent compound statements like those used in for loops, while loops, and if statements.
  • Placing some indent wrong.

How to fix Python Indentation Error

To fix indentation errors in Python you have to observe and analyze the code and accurately put the ident, by which it will be able to define the correct scope of various loops. 

  • Follow the correct sequence of code.
  • Use a perfect IDE(Pycharm)
  • Analyze the code and then put spaces as it should define the scopes of loops correctly.
  • Do not use spaces and tabs together stay in one.

Example: You can notice the gaps which is provided at the correct places. This gap makes code properly readable, beautiful and easy to understand. Indentation replaces the curly braces {} in writing code. this indentation describes the scope of a block. If you do not use proper indentation the compiler will return Indentation error. 

Python3




def check_number(a):
if a > 2:
if a < 7:
return "Number is between 2 and 7"
return "Number is greater than 2"
return "Number is out of the range of 2 and 7"
 
a = 5
result = check_number(a)
print(result)


Output

Indentation error.

Fix Python Indentation Error

Python3




def check_number(a):
    if a > 2:
        if a < 7:
            return "Number is between 2 and 7"
        return "Number is greater than 2"
    return "Number is out of the range of 2 and 7"
 
a = 5
result = check_number(a)
print(result)


Output:

Number is between 2 and 7


Similar Reads

Statement, Indentation and Comment in Python
Here, we will discuss Statements in Python, Indentation in Python, and Comments in Python. We will also discuss different rules and examples for Python Statement, Python Indentation, Python Comment, and the Difference Between 'Docstrings' and 'Multi-line Comments. What is Statement in Python A Python statement is an instruction that the Python inte
7 min read
Proper Indentation for Multiline Strings in Python
In Python, indentation plays a crucial role in code readability and structure, especially with multiline strings. Multiline strings, defined using triple quotes (""" or '''), allow for strings that span multiple lines, preserving the formatting within the quotes. Proper indentation of these strings is important for maintaining code readability and
3 min read
Indentation in Python
Indentation is a very important concept of Python because without properly indenting the Python code, you will end up seeing IndentationError and the code will not get compiled. Python IndentationPython indentation refers to adding white space before a statement to a particular block of code. In other words, all the statements with the same space t
3 min read
Python Value Error :Math Domain Error in Python
Errors are the problems in a program due to which the program will stop the execution. One of the errors is 'ValueError: math domain error' in Python. In this article, you will learn why this error occurs and how to fix it with examples. What is 'ValueError: math domain error' in Python?In mathematics, we have certain operations that we consider un
4 min read
How to Navigating the "Error: subprocess-exited-with-error" in Python
In Python, running subprocesses is a common task especially when interfacing with the system or executing external commands and scripts. However, one might encounter the dreaded subprocess-exited-with-error error. This article will help we understand what this error means why it occurs and how to resolve it with different approaches. We will also p
4 min read
Python | Prompt for Password at Runtime and Termination with Error Message
Say our Script requires a password, but since the script is meant for interactive use, it is likely to prompt the user for a password rather than hardcode it into the script. Python’s getpass module precisely does what it is needed. It will allow the user to very easily prompt for a password without having the keyed-in password displayed on the use
3 min read
Python | Assertion Error
Assertion Error Assertion is a programming concept used while writing a code where the user declares a condition to be true using assert statement prior to running the module. If the condition is True, the control simply moves to the next line of code. In case if it is False the program stops running and returns AssertionError Exception. The functi
3 min read
Python IMDbPY - Error Handling
In this article we will see how we can handle errors related to IMDb module of Python, error like invalid search or data base error network issues that are related to IMDbPY can be caught by checking for the imdb.IMDbErrorexceptionIn order to handle error we have to import the following from imdb import IMDbError Syntax : try : # code except IMDbEr
2 min read
How to print the Python Exception/Error Hierarchy?
Before Printing the Error Hierarchy let's understand what an Exception really is? Exceptions occur even if our code is syntactically correct, however, while executing they throw an error. They are not unconditionally fatal, errors which we get while executing are called Exceptions. There are many Built-in Exceptions in Python let's try to print the
3 min read
Create Error Bars in Plotly - Python
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Error Bars in Plotly For functions representing
3 min read
Error Handling in Python using Decorators
Decorators in Python is one of the most useful concepts supported by Python. It takes functions as arguments and also has a nested function. They extend the functionality of the nested function. Example: C/C++ Code # defining decorator function def decorator_example(func): print("Decorator called") # defining inner decorator function def
2 min read
Broken Pipe Error in Python
In this article, we will discuss Pipe Error in python starting from how an error is occurred in python along with the type of solution needed to be followed to rectify the error in python. So, let's go into this article to understand the concept well. With the advancement of emerging technologies in the IT sector, the use of programming language is
4 min read
How to Calculate Mean Absolute Error in Python?
Mean Absolute Error calculates the average difference between the calculated values and actual values. It is also known as scale-dependent accuracy as it calculates error in observations taken on the same scale. It is used as evaluation metrics for regression models in machine learning. It calculates errors between actual values and values predicte
2 min read
How to fix: "fatal error: Python.h: No such file or directory"
The "fatal error: Python.h: No such file or directory" error is a common issue encountered when compiling C/C++ code that interacts with Python. This error occurs when the C/C++ compiler is unable to locate the Python.h header file, which is part of the Python development package required for compiling code that interacts with Python.In this articl
5 min read
How to Fix - KeyError in Python – How to Fix Dictionary Error
Python is a versatile and powerful programming language known for its simplicity and readability. However, like any other language, it comes with its own set of errors and exceptions. One common error that Python developers often encounter is the "KeyError". In this article, we will explore what a KeyError is, why it occurs, and various methods to
5 min read
Python Django Handling Custom Error Page
To handle error reporting in Django, you can utilize Django's built-in form validation mechanisms and Django's error handling capabilities. In this article, I'll demonstrate how to implement error handling. If there are errors in the form submission, the user will be notified of the errors. Required Modules Install DjangoCreate Virtual Env Python D
4 min read
How to Fix Python Pandas Error Tokenizing Data
The Python library used to analyze data is known as Pandas. The most common way of reading data in Pandas is through the CSV file, but the limitation with the CSV file is it should be in a specific format, or else it will throw an error in tokenizing data. In this article, we will discuss the various ways to fix Python Pandas Error Tokenizing data.
4 min read
Correcting EOF error in python in Codechef
EOF stands for End Of File. Well, technically it is not an error, rather an exception. This exception is raised when one of the built-in functions, most commonly input() returns End-Of-File (EOF) without reading any data. EOF error is raised in Python in some specific scenarios: Sometimes all program tries to do is to fetch something and modify it.
3 min read
Floating point error in Python
Python, a widely used programming language, excels in numerical computing tasks, yet it is not immune to the challenges posed by floating-point arithmetic. Floating-point numbers in Python are approximations of real numbers, leading to rounding errors, loss of precision, and cancellations that can throw off calculations. We can spot these errors by
8 min read
NZEC error in Python
While coding in various competitive sites, many people must have encountered NZEC errors. NZEC (non zero exit code) as the name suggests occurs when your code is failed to return 0. When a code returns 0 it means it is successfully executed otherwise it will return some other number depending on the type of error. When the program ends and it is su
3 min read
How To Resolve The Unexpected Indent Error In Python
In Python, indentation is crucial for defining blocks of code, such as loops, conditionals, and functions. The Unexpected Indent Error occurs when there is an indentation-related issue in your code that Python cannot interpret correctly. This error typically happens when the indentation is inconsistent or there is a mix of tabs and spaces. What is
3 min read
Resolve Stopiteration Error in Python
Python is a versatile and powerful programming language, but like any other language, it has its share of errors. One common error that developers may encounter while working with iterators is the StopIteration error. This error occurs when there are no more items to be returned by an iterator. In this article, we will delve into the basics of iter
4 min read
Handle Memory Error in Python
One common issue that developers may encounter, especially when working with loops, is a memory error. In this article, we will explore what a memory error is, delve into three common reasons behind memory errors in Python for loops, and discuss approaches to solve them. What is a Memory Error?A memory error occurs when a program tries to access me
3 min read
Python Overflowerror: Math Range Error
Python is a powerful and versatile programming language, widely used for various applications. However, developers may encounter errors during the coding process. One such error is the 'OverflowError: Math Range Error.' This article will explore what this error is, discuss three common reasons for encountering it, and provide approaches to resolve
4 min read
“CAP_IMAGES: Can't Find Starting Number” Error in Python with Resolution
The error "CAP_IMAGES: Can't Find Starting Number" typically occurs in the context of the OpenCV when attempting to open a video file or capture device. This error message indicates that OpenCV encountered difficulties in reading or parsing the video stream due to the missing or incorrect starting frame number. Why “CAP_IMAGES: Can't Find Starting
5 min read
How to Fix "Error: Metadata Generation Failed" in Python
The "Error: Metadata Generation Failed" in Python usually occurs when there's an issue with generating or reading metadata related to the Python package. This error can happen for various reasons such as: Missing or corrupted metadata files: If the metadata files associated with the Python package are missing or corrupted it can lead to the metadat
4 min read
How to Fix 'Waiting in Queue' Error in Python
In Python, handling and managing queues efficiently is crucial especially when dealing with concurrent or parallel tasks. Sometimes, developers encounter a 'Waiting in Queue' error indicating that a process or thread is stuck waiting for the resource or a task to complete. This error can stem from several issues including deadlocks, insufficient re
3 min read
How to Fix MXNet Error “Module 'numpy' Has No Attribute 'bool' in Python
In Python, while working with NumPy, you may encounter the error “Module 'numpy' has no attribute 'bool'” when importing MXNet. This issue arises due to the deprecation of the numpy.bool alias in newer versions of NumPy. In this article, we will explore various solutions to fix this error and ensure compatibility between NumPy and MXNet. What is Im
3 min read
How to Fix the "No module named 'mpl_toolkits.basemap'" Error in Python
When working with the geographic data and plotting the maps in Python we might encounter the error: ModuleNotFoundError: No module named 'mpl_toolkits.basemap' This error occurs because of the mpl_toolkits.basemap module which is part of the base map toolkit is not installed in the Python environment. In this article, we will go through the steps t
3 min read
How to fix "error: Unable to find vcvarsall.bat" in Python
If you're encountering the error "error: Unable to find vcvarsall.bat" while trying to install Python packages that require compilation, such as those involving C extensions, you're not alone. This error typically occurs on Windows systems when the necessary Visual Studio Build Tools are not installed or not properly configured. Here’s a comprehens
3 min read
Article Tags :
Practice Tags :