This document provides an introduction to the basic components and syntax of Python programs. It covers keywords, identifier names, statements, indentation, comments, code blocks, and docstrings. It also includes examples and explanations to help beginners understand the fundamental concepts of Python programming.
1. Keywords in Python
Keywords are reserved words in Python. We cannot use keywords as variable names, function names, or any other identifier. They are used to define the syntax and structure of the Python language. In Python, keywords are case-sensitive.
With Python 3.10.2, there are a total of 35 keywords. All keywords except True, False, and None are in lowercase. We can use the command help("keywords")
in the Python interpreter to see a list of all keywords in Python.
Below is a table of keywords in Python 3.10.2
.
False | await | else | import | pass |
None | break | except | in | raise |
True | class | finally | is | return |
and | continue | for | lambda | try |
as | def | from | nonlocal | while |
assert | del | global | not | with |
async | elif | if | or | yield |
2. Identifiers in Python
Identifiers are names given to entities such as classes, functions, variables, etc. They help distinguish this entity from others.
2.1. Rules for naming identifiers
- Identifiers can include lowercase letters (a to z), uppercase letters (A to Z), digits (0 to 9), and underscores (_). For example, myClass, var_1, and print_this_to_screen are valid identifiers.
- Identifiers cannot start with a digit. For example, the identifier
1variable
is invalid butvariable1
is valid. - Identifiers cannot be named the same as keywords.
- Special characters such as !, @, #, $,%, etc. should not be used in identifiers.
- Identifiers can have any length.
2.2. Some notes to remember
– Python is case-sensitive. Therefore, the identifiers VaRiable and variable are different.
– Identifiers should be meaningful and easy to remember. Instead of naming a variable c = 10
, it can be named count = 10
. At this point, the name of the variable will be more meaningful and indicate that the count
variable is a variable used to store a counting value.
– Words in an identifier can be joined together by underscores. For example, this_is_a_long_variable.
– Identifiers do not include whitespace characters. For example, the identifier count a
is invalid but counta
is valid.
3. Statements in Python
Python will interpret each statement to execute. A statement in Python is usually written in one line. We do not need to add a semicolon (;) at the end of each statement. For example:
a = 5
b = 10
print("Sum = ", a + b)
We can write a statement on multiple lines by using appropriate characters such as a line continuation character (\), parentheses (), square brackets [], and curly braces {}.
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
a = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
colors = ['red',
'blue',
'green']
We can also put multiple statements on one line by using a semicolon (;) as follows:
a = 1; b = 2; c = 3
4. Indentation in Python
Python uses indentation to define a code block such as the body of a function, loop, etc.
Note: Python does not use curly braces {} for code block like C/C++, Java,…
For example:
for i in range(1,11):
print(i)
if i == 5:
break
In Python, 4 spaces are used for indentation and are preferred over tabs. If you use incorrect indentation, the program will report an IndentationError
.
5. Comments in Python
Comments
are used to explain what the code is doing. This is especially important when reviewing source code or maintaining the program later. Use the hash symbol (#) to start writing comments in Python. The Python interpreter will ignore comments starting from the hash symbol (#) until it encounters a new line character.
#This is a comment
#print out Hello
print('Hello')
Comment on multiple lines
We can write comments on multiple lines, each line starting with the hash symbol (#). Or another way to comment on multiple lines is to use quotes ”’ or “””. For example:
#This is a comment
#print out Hello
print('Hello')
"""This is also a
perfect example of
multi-line comments"""
print('Hello World!')
'''This is also a
perfect example of
multi-line comments'''
print('Hello World!')
6. Code Block in Python
One or more statements can form a code block. Code blocks are often encountered in Python such as statements in a class, function, or loop, etc. Python uses indentation to start defining and separating a code block from other code blocks. For example:
7. Docstring in Python
Docstring is short for the documentation string in Python. It is a string of characters that appears immediately after the definition of a method, class, or module. Use triple quotes “”” to write docstring. For example:
def double(num):
"""Function to double the value"""
return 2*num
We can access docstring with the __doc__
attribute. For example:
def double(num):
"""Function to double the value"""
return 2*num
print(double.__doc__)
Result
Function to double the value
Docstring is essentially a comment. You should write docstrings, especially when writing APIs or libraries. They will make it easier for programmers to use your API or library.
Good job!