Skip to main content

IndentationError: expected an indented block How to resolve

While running any python program if the user receives an error like IndentationError: expected an indented block. This means indentations are not proper.

Let’s see the below example and how to solve the error IndentationError: expected an indented block.

Below code with Error

a = 4
b = 5
if a > b:
print ('A is maximum')
else:
print ('B is maximum')

Output

File "<string>", line 4
    print ('A is maximum')
    ^
IndentationError: expected an indented block

If we observe in code that there is indentation available for if and else condition, as a result, python throws an error message.

To resolve error we need to provide indentation to statements after If condition. So we try to provide uniform spaces for statements after if conditions like below

a = 4
b = 5
if a > b:
    print ('A is maximum')
else:
    print ('B is maximum')

After indentation output is

B is maximum

 In conclusion, the indentation needs to be consistent. It is recommended to use 4 spaces for indentation in Python.

Not equal to in python using != operator

To check if two operands are not equal python provides operator !=.

Let’s see an example of not equal to an operator on an integer variable.

#Use of operator not equal to
a= "3"
b= "4"
c = "4"
#If a is not equal to b then conditon will print true
print("a=",a,"b=",b,"\nResult of Not Equal to Operator is ",a!=b)
print("\n")
#if c equal to b then condition will print false as we are using not equal to operator
print(" b=",b,"c=",c,"\nResult of Not Equal to Operator is  ",b!=c)
print("\n")
a= 3 b= 4 
Result of Not Equal to Operator is  True


 b= 4 c= 4 
Result of Not Equal to Operator is   False

Similarly, we can apply not equal to an operator on a variable that contains string values.

!= Operator return value as True when the value of operands are different. If both operands are the same then Not Equal to the operator will return False.

#Let's See with String value
str1= "ethosspace.com"
str2= "google.com"
str3 = "google.com"
#If str1 is not equal to str2 then conditon will print true
print("str1=",str1,"str2=",str2,"\nResult of Not Equal to Operator is ",str1!=str2)
print("\n")
#if str3 equal to str2 then condition will print false as we are using not equal to operator
print(" str2=",str2,"str3=",str3,"\nResult of Not Equal to Operator is  ",str2!=str3)
str1= ethosspace.com str2= google.com 
Result of Not Equal to Operator is  True


 str2= google.com str3= google.com 
Result of Not Equal to Operator is   False

Simple code to Generate QR Code using Python

To generate QR Code like Below

It is important to install pyqrcode and pypng. To install this you can use the command prompt and use the below command.

pip install pyqrcode
pip install pypng

Below simple 5 line code will generate QR code for URL in python

#QR Code Generator
import pyqrcode
from pyqrcode import QRCode
urlDest = 'https://www.ethosspace.com/'
varQR = QRCode(urlDest, error='H', version=None, mode=None, encoding='iso-8859-1')
varQR.png('generatedQR.png', scale=8)
varQR.show()

Here in dest variable, we have used hyperlink ethosspace.com. Which can be replaced with url to generate QR Code.

How to remove duplicate keys from dictionary in python

This python code will remove all duplicate keys and associate items from the dictionary. To remove we are using one temp array and using it for loop iterating each value.

thisdict = {
  "1": "C language",
  "2": "Java Language",
  "4": "Python Language",
  "3": "C++",
  "4": "Python Language",
  "3": "C++",
  "5": "C++",
}
#declare temp array
tempA = []  
uniqueDict = dict()
for key, val in thisdict.items():
    if val not in tempA:
        tempA.append(val)
        uniqueDict[key] = val

print(uniqueDict)
{'1': 'C language', '2': 'Java Language', '4': 'Python Language', '3': 'C++'}

Print function with different examples in detail

Print statement in python is not reserved word nor a statement. Print is built in function call which run as expression statement.

The interactive session automatically prints the results of expressions you type, you don’t usually need to
say “print” explicitly at this prompt:

>>>ethosspace = 'Testing Services'
>>>ethosspace  
' Testing Services '

So print function used in files not on interactive prompt.

Syntax
print([object, …][, sep=’ ‘][, end=’\n’][, file=sys.stdout])

print(object(s), sep=separator, end=end, file=file, flush=flush)

Items in square brackets are optional and may be omitted in a given call, and values after = give argument defaults.
In English, this built-in function prints the textual representation of one or more objects separated by the string sep and followed by the string end to the stream file.

SEP is a string inserted between each object’s text, which defaults to a single space if not passed; passing an empty string suppresses separators altogether.

END is a string added at the end of the printed text, which defaults to a \n newline character if not passed. Passing an empty string avoids dropping down to the next output line.

FILE specifies the file, standard stream, or other file-like object to which the text will be sent; it defaults to the sys.stdout standard output stream if not passed.

Here are the real time example of print function.

print function with no parameter print the empty line

>>>print()

To print blank line no need to pass any parameter by default print without any parameter prints blank line.


>>> a=9
 >>> b='Testing'
 >>> c=['Prog']
 >>> print(a,b,c)
         9 Testing ['Prog']

So while printing 3 objects print function added empty space between those three objects. So in place of empty space if we want different separator then we can use below syntax.

 >>> print(a,b,c,sep=' => ')
          9 => Testing => ['Prog']

Output is now separated with separator => which we provided.


By default, print adds an end-of-line character to terminate the output line.

>>>print ('ethosspace'); print('leading software testing provider')
        ethosspace
        leading software testing provider

So if we don’t need new line then we will use end parameter here

>>>print (‘ethosspace’,end=”); print(‘ leading software testing provider’)

ethosspace leading software testing provider

Example of variable, %d and % in print statement. Use of variable in between sentence in print statement.

>>>x=5
>>>y=8
>>>z=2 * (x+y)
>>>print('A rectangle %d by %d has a perimeter of %d units.'%(x,y,z))
A rectangle 5 by 8 has a perimeter of 26 units.

Use online free python compiler to run program from anywhere.

Programs to print different Square, rectangle in Python Language

Below program will accept width and breadth from user. We can print SOLID rectangle, need to use two for loops along with print function with end parameter.

Step 1) Accept breadth and width from user
Step 2) First for loop is to print

#Python program to print hollow rectangle, solid rectangle.
#accept width and breadth from user
width=int(input("Enter Width\t"))
breadth=int(input("Enter breadth \t"))
for i in range(0,breadth):
    for j in range(0,width):
        print("*",end="")
    print()

OUTPUT

Enter Width	5
Enter breadth 	3

*****
*****
*****

Python Program to print hollow rectangle

This tricky program. It is important to use print function along with end parameter effectively. Here is the complete code

#Python program to print hollow rectangle
#accept width and breadth from user
width=int(input("Enter Width\t"))
breadth=int(input("Enter breadth \t"))
for i in range(0,breadth):
    for j in range(0,width):
        if (i==0 or j ==0 or i==breadth or j==width):
             print(" *",end="")
        else:
             print(" ",end="*")
    print()

Output

Enter Width	3
Enter breadth 	4
 * * *
 * * *
 * * *
 * * *

Use free online python compiler to write execute any python program.

Program to find number divisible by 3 or 5 in python

To find number divisible by 3 or 5 we have accepted user input. Used for loop and mod operator with If condition.

#Program to find numbers divisible by 3 or 5

rangeNo = int(input("\n\tEnter number upto which you need to find number divisible by 3 or 5\n\t"))

#Loop to print numbers divisible by 3
print('\n\nThese numbers are divisible by 3 upto %d'%rangeNo)
for i in range(1,rangeNo+1) :
    if (i%3 ==0):
        print("\t%d"%i)
        
#Loop to print numbers divisible by 5
print('\n\nThese numbers are divisible by 5 upto %d'%rangeNo)
for i in range(1,rangeNo+1) :
    if (i%5 ==0):
        print("\t%d"%i)

Output

Enter number upto which you need to find number divisible by 3 or 5
	10
	These numbers are divisible by 3 upto 10
	3
	6
	9


These numbers are divisible by 5 upto 10
	5
	10

calculate cube of numbers in python using while, for loop

Here is simple three line program to calculate cube and print it as per user input or range using while loop

#Program to find cube of numbers
#taking input from user till how many numbers user want to print cube
rangeNo=int(input("enter upto which number you want to print cube\t"))

i = 1;
while i <= rangeNo:
    cubeNo = 0
    cubeNo = i * i * i
    print("cube of %d is ===>   %f"  %(i,cubeNo))
    i=i+1

Output

enter upto which number you want to print cube	5
cube of 1 is ===>   1.000000
cube of 2 is ===>   8.000000
cube of 3 is ===>   27.000000
cube of 4 is ===>   64.000000
cube of 5 is ===>   125.000000

Below program is to calculate cube of numbers using for loop up to number (user input)

#Program to find cube of numbers
#taking input from user till how many numbers user want to print cube
rangeNo=int(input("enter upto which number you want to print cube\t"))

j = 1;
for i in range(j,rangeNo+1):
    cubeNo = 0
    cubeNo = i * i * i
    print("cube of %d is ===>   %f"  %(i,cubeNo))

Output

enter upto which number you want to print cube	5
cube of 1 is ===>   1.000000
cube of 2 is ===>   8.000000
cube of 3 is ===>   27.000000
cube of 4 is ===>   64.000000
cube of 5 is ===>   125.000000

How to Install python on Windows step by step guide

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Python language is popular for data science and analytics. Many data processing software use python. Many python libraries are used in machine learning projects.

Here is step by step guide to install python on windows machine.

It is important to download latest version from python official site only.

Step 1) Navigate to Python Site https://www.python.org/downloads/ for downloading latest version

Python Official Site

Step 2) Click on button “Download Python 3.10.0” ( In future this version may change to try to select latest version)

Step 3) After clicking on “Download Python 3.10.0” Site will download exe file to download folder section

downloaded folder view section

Step 4) Double click on exe file “python-3.10.0-amd64.exe” and Run the Setup

Python Installation Screen

Step 5) Select Check box “Add Python 3.10 to Path” and then click on Install Now Button

Add Python 3.10 selected

Step 6) Wait for installer to complete installation

Python installation is in progress

It will take couple of minutes for installation.

Step 7) System will give successful message along with path limitation (which can be ignored). Click on Close Button

Python Installed Successfully message

Step 8) Now go to command prompt to check if python is installed or not. Type cmd in Windows Search option and press enter. After displaying command prompt type python and you will get below message.

Python successful installation version message

To Start coding in python or to write first program in python we can use default editor “IDLE”. IDLE (Integrated Development and Learning Environment) is a default editor that comes with Python.

To open default editor type IDLE in Windows “Type here to Search” section and hit Enter

IDEL Default Editor for python

System will display below editor

Click on File -> New File

System will display editor to write new program for specific file.

Happy Learning and Coding

You can refer these program to explore python more and can run python code on online compiler as well.