Python Syntax
Python language program is read by a parser. Python was developed to be the most understandable programming language. The Python syntax is the set of rules which defines how a Python language program will be written.
Line Structure in Python
A Python program is divided into several logical lines, and the token NEWLINE terminates each logical line. It means each line in a Python script is a statement. A logical line is drawn from one or more physical lines. See the following Python syntax examples.
print('id: ', 1)
print('First Name: ', 'Rohit')
print('Last Name: ', 'Kumar')
Joining two lines in Python
Use backslash character '\' to join a statement span over multiple lines, as shown in the example.
if 200 > 135 and \
150 <= 333 and \
True != False:
print('Python Syntax Example')
Comments in Python
Python programs use a hash character '#' to write a comment. By the end of the line, all words after # are part of the comment, and Python compilers ignore them, meaning they don't execute them.
print('Hello World!') # This is a comment
Multiple Statements in a Single Line
In Python, a semicolon ';' is used to separate several statements in a row.
print('Google');print('Facebook');print('Twitter')
Expressions in brackets ( ), square brackets [ ], or curly brace { } do not use backslashes.
list = [11, 12, 13, 1415, 16, 17, 18,19, 20, 21, 22]
Python Indentation
The leading space or tab at the beginning of the line is considered as the indentation level of the line, which is used to determine the group of statements. Statements with the same level of indentation considered as a group or block. Other languages like C, C++ use braces ({}) to indicate blocks of codes for class, functions, or flow control.
For example, functions, classes, or loops in Python contains a block of statements to be executed. Other programming languages such as C# or Java use curly braces { } to denote a block of code. Python uses indentation (space or a tab) to denote a block of statements.
Python Indentation Rules
- Use the colon ':' to start a block and press Enter.
- All the lines in a block must use the same indentation, either space or a tab.
- Python recommends four spaces as indentation to make the code more readable. Do not mix space and tab in the same block.
- A block can have inner blocks with next level indentation.
if 10 > 5: # 1st block startsprint("10 is greater than 5") # 1st blockprint("Now checking 20 > 10") # 1st blockif 20 > 10: # 1st blockprint("20 is greater than 10") # inner blockelif: # 2nd block startsprint("10 is less than 5") # 2nd blockprint("This will never print") # 2nd block
def funHello(name):print("Hello ", name)print("Welcome to eVidyalam")
dfdf