Python Code Syntax

Python File Extension

'py' is the Python file extension.

Simple 'Hello World' Program

print("Hello World!")

In the above example, print statement is used to display the value on the screen. All the text within print should be in double quotes or single quotes. Statement separator is a semicolon, but is only needed when there is more than one statement on a line.

Python Expression

We can easily calculate mathematical expression starting with ">>>" prompt.

>>> 234 + 623
>>> 2 * 3452
>>> 343 * 23 + 42 - 5

For any expression containing more than one operation, Python follows the usual order of operations.

Python also provides functions to perform mathematical operations, like round() -

>>> round(23.34)
>>> round(-32.9)

Some mathematical functions are not built-in to Python, they need to use the math package.

>>> from math import*
>>> sqrt(49)
>>> sqrt(5)

Python Argument Separator

The 'sep' keyword is used to separate the arguments passed in a print function.

>>> from __future__ import print_function
>>> print("a", "b", "c", "d", sep=":")
>>> print("e", "f", "g", "h", "i", "j", sep="---")

__future__ is the real module and used only in Python 2.x. In Python, the indention of a statement is significant, like if we put a single space before print in the shell, we will get -

SyntaxError: unexpected indent

Python Code Block

Every statements in the Python is a command that python interpreter execute. There may be a single statement or a group of statements called block.

Example - Program with multiple statements
print("   *  ")
print("  ***  ")
print(" ***** ")

The output of the above command looks like -

python code block

Python Comments

The # symbol is used to comment the code. Everything written after '#' on a line is ignored. There is no block comments available in Python. For multilines comment, each line begins with the hash mark and a single space. If we need to comment more than one paragraph, they should be separated by a line that contains a single hash mark.

# Code to print * pyramid
print("   *  ")
print("  ***  ")
print(" ***** ")

We can also use inline comments in Python. Inline comment is written on the same line of a statement, followed by the code itself.

print("   *  ")  # Code to print * pyramid
print("  ***  ")
print(" ***** ")

Python Whitespace

Whitespace is meaningful in indentation and placement of newlines. To prematurely go to next line, use \ to the end of line. There is no need to use braces {} to mark blocks of code.

Read more articles

General Knowledge

Learn Popular Language