Computer >> Computer tutorials >  >> Programming >> Python

How to provide multiple statements on a single line in Python?


More than one statements in a block of uniform indent form a compound statement. Normally each statement is written on separate physical line in editor. However, statements in a block can be written in one line if they are separated by semicolon. Following is code of three statements written in separate lines

a=10
b=20
c=a*b
print (c)

These statements can very well be written in one line by putting semicolon in between.

a=10; b=20; c=1*b; print (c)

A new block of increased indent generally starts after : symbol as in case of if, else, while, for, try statements. However, using above syntax, statements in block can be written in one line by putting semicolon. Following is a straight forward example of a block of statements in a for loop

for i in range(5):
   print ("Hello")
   print ("i=",i)

This block can also be written in single line as follows −

for i in range(5): print ("Hello"); print ("i=",i)

However, this practice is not allowed if there is a nested block of statements.