Python has one of the simplest and easiest sysntax to read and uderstand among the major programming languages. Let us take the example below:
# A program to calculate the average of a list of numbers
grades = [90, 80, 98, 100] # List of grades
sum = 0 # Initial sum of the grades
for mark in grades:
sum += mark
average_grade = sum/len(grades)
print("Average grade is: ", average_grade)
Output:
Average grade is: 92
Comments
Comments are used in any programming language to document and communicate with users or readers of your code. Comments in Python start with the hash symbol (#). A line may begin with a comment and, comments may be placed after other statements. The Python interpreter identifies and ignores comments during compilation and execution.
Indentations
The example program consists of assignment and loop or iterative statements among others. Functions , loops and conditionals are blocks of code which are denoted by a colon at the end of the block start and, indentations within the block of code. An indentation is a set of white spaces at the begining of a line to denote the block within which a statement belongs. In the example code,
for mark in grades:
sum += mark
is a for-loop block and 'sum += mark
' starting with three white spaces indicates that the statement belongs to the for loop block.
End of line and semicolon
Contrary to programming languages like C and C++, a semicolon (;) is not required to indicate the end of a line. The end of a statement in Python is indicated simply by the end of a line. In situations where one may want to put multiple statements on a single line, statements must be separated by a semicolon.
x = 60; y = 20
Brackets or paranthesis
Parenthesis may be used for grouping to enforce precedence or may be used when calling a function. Examples:
2 + 3 * 4
By default operator precendence, the expression above will evaluate to 24. A paranethesis can be used to alter how the expression is evaluated.
(2+3) * 4
will evaluate to 20 since (2+3) is grouped by the parenthesis and therefore will be evaluated to a single value before being multiplied by 4.
To call a function (see functions), a paranthesis is used to denoted a function call and to also pass values to the function. Example:
print("Average grade is: ", average_grade)
The paranthesis indicates that print is a function call and the values within the bracket are passed to the function.