In this blog, we will learn about proper Python programming structure. Normally when you write Python Statements the interpreter reads and executes the statements line by line which means sequentially. But there are some statements out there that can easily alter this behavior like conditional statements.

Python programming structure

Most of the time’s python programs are written in such a way that only one statement is only written in a single line. The interpreter considers the “newline character” as the terminator of one instruction. But that doesn’t mean writing multiple lines is not possible it is possible. And you can find that below in the example. So, let’s jump into action and learn about Python programming structure.

Also Read: Twitter API with Python: Everything you need to know

Example 1:

print('Welcome to this blog') 

Output:

Welcome to this blog

Example 2:

 [1, 2, 3, 4]
  
# x[1:3] means that start from the index 
# 1 and go upto the index 2
print(x[1:3])

In the above mentioned format, the first index is included, but the last index is not included

Output:

[2, 3]

Multiple Statements Per Line

You can easily write multiple statements per line but generally, it is not advisable as it is not a good practice as it reduces the readability of the code. We would suggest trying to avoid writing multiple statements in a single line. There are ways you can easily write multiple lines by terminating one statement with the help of ‘,’. ‘.’ is used as the terminator of one statement in this case.

We have also provided you with an example to help with the code given below.

Example:

 a = 20; b = 20; c = b + a
  
print(a); print(b); print(c)

Output:

20
20
40

Line Continuation to avoid left and right scrolling

Some programs can become very and may push you to scroll down and left and right frequently. Also, you can try to fit your code in such a way that you do not have to scroll here and there every time. Python provides you with the option to write a single statement in multiple lines which is also known as a line continuation. Line continuation helps with the readability of the program as well.

# Bad Practice as width of this code is too much.
 
#code
x = 10
y = 20
z = 30
no_of_teachers = x
no_of_male_students = y
no_of_female_students = z
 
if (no_of_teachers == 10 and no_of_female_students == 30 and no_of_male_students == 20 and (x + y) == 30):
    print('The course is valid')
 
# This could be done instead:
 
if (no_of_teachers == 10 and no_of_female_students == 30
    and no_of_male_students == 20 and x + y == 30):
    print('The course is valid')

Different Types of Line Continuation in Python programming structure

Basically, there are two types of line continuation in Python programming structure:

1: Implicit Line Continuation

One of the most straightforward techniques in a writing statement that spans multiple lines. Any statement that contains opening parentheses (‘(‘), brackets (‘[‘), or curly braces (‘{‘) are considered incomplete. Until and unless all the matching parentheses, square brackets, and curly braces have been closed properly. Until they are closed the program statement can be continued across lines without any error.

Example 1:

# The following code is valid
a = [
    [1, 2, 3],
    [3, 4, 5],
    [5, 6, 7]
    ]
  
print(a)

Output:

[[1, 2, 3], [3, 4, 5], [5, 6, 7]]

Example 2:

# The following code is also valid
  
person_1 = 18
person_2 = 20
person_3 = 12
  
if (
   person_1 >= 18 and
   person_2 >= 18 and
   person_3 < 18
   ):
    print('2 Persons should have ID Cards')

Output:

2 Persons should have ID Cards

2: Explicit Line Continuation

Explicit Line Continuation is mostly used when the above method is not applicable. In the Explicit Line Continuation method, you have to use a character that helps the interpreter to understand that the particular statement is spanning more than one line.

Backslash (/) is used to show that a statement spans if you use more than one line.

Note: The thing you have to note is that Backslash (/) must be the last character in that line even white space is not allowed.

Example:

x = \
    1 + 2 \
    + 5 + 6 \
    + 10
  
print(x)

Output:

24

Comments in Python

Well, writing comments in the code is also very important as they help you in code readability and also get more information about the code. Comments In python will help you write details against a statement. Your interpreter doesn’t count them in commands and counts them as comments. In this part of the blog, we will learn how to write comments in Python.

Here are some different symbols used for writing commends are Triple Double Quotation marks (“””) and Hash (#). Triple Double Quotation marks are used to write multiple line comments. Hash is used in writing single-line comments that do not go to multiple lines. Also, Triple Double Quotation marks to start the comment and then again Triple Double Quotation marks to need the comment.

So, now let us provide you with an example.

Example 1:

####### This example will print Hello World ####### print('Hello World')  # This is a comment

Example 2:

""" This example will demonstrate 
    multiple comments """
  
""" The following
    a variable contains the 
    string 'How old are you?'
"""
a = 'How old are you?'
  
""" The following statement prints
    what's inside the variable a 
"""
print(a)

Note: You cannot use Hash (#) inside a string it doesn’t create a comment. So, to help you with that, we will provide you with an example.

Example:

""" The following statement prints the string stored
    in the variable """
  
a = 'This is # not a comment #'
print(a) # Prints the string stored in a

White Spaces

We have provided the whitespace character given below:

Python programming structure

Also, you can take a look at the ASCII table by clicking here.

Also, whitespace is mostly ignored and not required by the Python interpreter. When it is clear where one token ends and the next one starts whitespace can be simply ignored. Generally, these things happen when special non-alphanumeric characters are involved.

Example 1:

# This is correct but whitespace can improve readability
  
a = 1-2  # Better way is a = 1 - 2
  
print(a)

Example 2:

# This is correct
# Whitespace here can improve readability.
x = 10
flag =(x == 10)and(x<12)
print(flag)
  
""" Readable form could be as follows
x = 10
flag = (x == 10) and (x < 12)
print(flag)
"""
  
# Try the more readable code yourself

Let us tell you whitespace are important in separating the main keywords from one variable to another variable. So, again let us provide you with another example.

Example:

x = [1, 2, 3]
y = 2
  
""" Following is incorrect, and will generate syntax error
a = yin x
"""
  
# Corrected version is written as
a = y in x
print(a)

Whitespaces as Identation

The syntax of Python is quite easy but still, it is a code and you have to take some care while writing the code. Indentation is used in writing python codes. Also, white spaces before the statement have a significant role and are important for indentation. Whitespace before a statement can have a different meaning. Let’s try an example.

Example

print('foo') # Correct
  
   print('foo') # This will generate an error
  
# The error would be somewhat 'unexpected indent'

Leading whitespace is used to determine the grouping of the statements like control structures or loops etc.

Example

x = 10
  
while(x != 0):  
 if(x > 5):   # Line 1
  print('x > 5')  # Line 2
 else:        # Line 3
  print('x < 5') # Line 4
 x -= 2       # Line 5
  
"""
Lines 1, 3, 5 are on same level
Line 2 will only be executed if if condition becomes true.
Line 4 will only be executed if if condition becomes false.
"""

Output

x > 5
x > 5
x > 5
x < 5
x < 5

Conclusion

In this blog, we have explained in detail the Python programming structure. Hope you find this information useful. Thank you for the read.

Categorized in: