Basic Structure Of Python Program
The following are the common elements that can be found in a python program.
1. statements
2. Blocks or suits
3. comments
4. functions
Statement
Any executable program line is called as statement. statement can be terminated with ; but it is optional. It is used to separate statements written in a line.
Blocks or Compound Statement
Group of statements maintaining same amount of indentation from left hand side of the Editor. Block can be started with colon(:) and ends with Backspace
Comment
These are used to provide description for various different parts of the program. Comments are completely ignored by compiler since these are non-executable part.
2 styles of comments in python code:
1. Single line : starts with # symbol and ends with current line
2. multi line: start with triple single/double quotes and ends with same.
Function
Piece of code defined separately for re-usability.
Two forms of any function:
1. definition
2. invocation
Invocation of function can be seen in the following ways in python code:
fun()
fun(…)
var.fun()
Output Statement
Output is an activity that is used to display some information or response from the python program to user.
In python, we use print() function to perform output operation.
Syntax1:
print(“Message that we want to display”)
We can use print() function to print message, value, variable, result of an expression or combination of them.
#Example code
print("some message to be printed")
print(5)
output of each print() function displays in individual line.
#Example code
print("first line")
print("second line")
print("third line")
We can split the print() function in the code using ‘\’
#Example code
print("this is message\
that displays in\
multiple lines")
\n – new line character is used to split output of print() function
\t – horizontal tab
#Example code
print("this is message\nthat displays in\nmultiple lines")
more than one parameter of print() function can be separated with comma(,)
#Example code
print("Best","Computer","Institute")
print() display its parameters with a ‘space’ separator by default.
We can change that using ‘sep’ parameter
#Example code
print("best","computer","institute",sep="-")
The default termination character of print() is NewLine. We can also change the termination character of print() using ‘end’ parameter.
#Example code
print("first line",end=" ")
print("second line")