TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to PYTHON

Python IndentationError (unexpected indent)

Understand the cause of IndentationError. Determine how to fix this error.
IndentationError. A Python program uses indentation to nest blocks. Each statement in a block must have the same indentation level. An IndentationError occurs if this rule is broken. But separate blocks may use different indents.Error
Example. This program causes an IndentationError (unexpected indent). In the for-loop, 2 print method calls appear. But the second print() call is indented further to the right than the first. Python raises an error on the first print() call.

Tip: To fix this program, we can change the two print() statements to be indented the same number of characters.

Python program that causes IndentationError # An incorrectly-formatted for-loop. for n in range(0, 1): print(n) print(n) Output print(n) ^ IndentationError: unexpected indent
Example 2. Next, we find that indent levels have no requirement to be even throughout a program. In this example, the print-statements are unevenly-indented. But they are in separate blocks. For this reason the program executes. It raises no errors.
Python program that causes no error # Correct. for n in range(0, 1): print(n) # Correct but different. for n in range(0, 1): print(n) Output 0 0
We see that the important part of indentation is consistency within blocks. It can vary between different blocks, one after another. But within the same block, indents must be correct.
Summary. Indentation is key in the Python language. It tells us how blocks are organized. Scope, a related concept, is also determined by indentation. The Python language requires strict indentation. This leads to programs more easily understood.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf