Python Syntax

Syntax is the set of rules on how code in a particular programming language should be written in, in order to be correctly structured. In this section we will look at Python indentation, python variables, and python comments.

Python indentation

Indentation in python is used to indicate a block of code that should be grouped together. This is contrary to other programming languages like Java whereby indentation is used to enhance code readability.

The developer/programmer chooses the space they wish to use i.e,2 spaces,3 spaces,4 spaces etc. but the chosen space should be used consistently in the python module.

Example 1

In the below program, we have chosen an indentation of 0 spaces to group related code blocks. Note that in this module, the variable score, the if,elif and else statements are all at the same block level as it’s an if..elif..else construct.

python syntax

The code is saved in file named indentation_example_one.py .On running it, the result is as follows

Example 2

Let’s mess the indentation on line 8 and make it use 1 space as below

When we run the module,we get the error below

The score,if,elif,else statements are part of  the if—elif-else construct and should be at the same level.When the elif on line 8 is taken out of order,Python flags an error in the source code file as shown above  when the code is run.

Python variables

In Python variables are created at the point values are assigned to them e.g. declaring String f_name=”John”,score=74 etc.Unlike other programming languages like Java whereby variable type are declared jointly when declaring the variable ,Python does not require this. Also variable type changes depending on the value assigned to the variable.

Examples

f_name="John"     # valid

score=74              #  valid

score="74"   #score can hold a string as well

score     #illegal, must have a value provided in order for variable to be created.

 

Python Comments

Comments are used to add readability to code for other developers .They help elaborate the thought process why the logic was written as is and helps future developers who will be maintaining the code on how to proceed with caution J in most instances. In Python, comments begin with #.We can have multi line comments as well but that will be discussed in detail in the Python Comments tutorial.

Example

#we hold the score values in score variable

score=50

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.