'What is the reason for an IndentationError in my code?
i have python code like this, basically i just want to solve this product percentage so the result in product percentage will appear, here's the code:
product_a_sales = 5
product_b_sales = 5
total_sales = product_b_sales - product_a_sales
try:
product_a_percentage_sales=(product_a_sales/total_sales) * 100
except ZeroDivisionError:
product_a_percentage_sales=0
and it returns an error like this
File "<ipython-input-30-aa369d387f3d>", line 5
product_a_percentage_sales=(product_a_sales/total_sales) * 100
^
IndentationError: expected an indented block
Solution 1:[1]
This is a basic syntax error.
The statements between try and except must be indented.
The error message actually explains it perfectly: the line with product_a_percentage_sales = is not an "indented block", but an indented block was expected.
Refer to the Python tutorial for more information: 8. Handling Errors.
Solution 2:[2]
You have to just watch your whitespace and indentations on the code after try:
product_a_sales = 5
product_b_sales = 5
total_sales = product_b_sales - product_a_sales
try:
product_a_percentage_sales=(product_a_sales/total_sales) * 100
except ZeroDivisionError:
product_a_percentage_sales=0
Solution 3:[3]
As the Error message explains, in line 5, you have syntax error related to incorrect indentation. Frome more info on indentation in Python, please refer to these links: 1, 2, 3 and 4.
The correct syntax would be as follows:
product_a_sales = 5
product_b_sales = 5
total_sales = product_b_sales - product_a_sales
try:
product_a_percentage_sales=(product_a_sales/total_sales) * 100
except ZeroDivisionError:
product_a_percentage_sales=0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | shadowtalker |
| Solution 2 | tylerjames |
| Solution 3 | Rouhollah Joveini |
