Python syntax

Python Syntax Simplified: Learn How to Write Efficient Code with Examples

Python syntax is easy and straightforward. If you wrote the program using Python syntax best practices and structured it in the right way, other developers will be able to read and understand it with ease. In this chapter, we’ll cover the most important things you need to know about Python syntax.

Statements

In Python, every statement ends with the NEWLINE character (carriage return).

That means each line in a Python script is a statement.

The following Python script contains two statements in two separate lines.

#!/usr/bin/env python3
print('EC2 Instance ID: ', 'i-0e9a442e6332682dc')
print('EC2 Instance AMI ID: ', 'ami-0d3349b5c3c7b98b9')

Interpreter output at Cloud9 IDE:

1. Python syntax - Statements - Example 1

You can use the backslash character ( \ ) to split a single statement into multiple lines:

>> result = 1 + 2 + 3 + 4 + 5 \
    + 6 + 7 + 8 + 9
>> print(result)
45         

Interpreter output at Cloud9 IDE:

2. Python syntax - Statements - Example 2

The backslash ( \ ) character allows you to split a single statement into two logical lines.

This means that the following example is valid because it is still a single print() statement:

>> print('EC2 Instance ID:  \
i-0e9a442e6332682dc')
EC2 Instance ID:  i-0e9a442e6332682dc

But the following one is not:

>> print('EC2 Instance AMI ID: ') \
>> print('ami-0d3349b5c3c7b98b9')
SyntaxError: invalid syntax

Interpreter output at Cloud9 IDE:

3. Python syntax - Statements - Example 3

You can use the semicolon ( ; ) to specify multiple statements in a single line:

>> print('EC2 Instance ID: ', 'i-0e9a442e6332682dc'); print('EC2 Instance AMI ID: ', 'ami-0d3349b5c3c7b98b9')
EC2 Instance ID:  i-0e9a442e6332682dc
EC2 Instance AMI ID:  ami-0d3349b5c3c7b98b9

Meanwhile, it is possible, it is not recommended to use such syntax, as it impairs the readability of your code.

4. Python syntax - Statements - Example 4

Expressions in parentheses ( ), square brackets [ ], or curly braces { } can be spread over multiple lines without using backslashes:

ec2_instance_amis = [
     'ami-077e31c4939f6a2f3',
     'ami-00399ec92321828f5',
     'ami-086850e3dda52e84a'
]

Indentation

Amount of spaces or a tabs at the beginning of the statement is called an indentation level.

Indentation levels are used to determine the group of statements.

And finally, all statements with the same level of indentation are forming a group or a block.

For example, functions, classes, or loops in Python usually consist of one or more blocks of statements.

Unlike with other programming languages like C++ or Java where curly braces { } defines a block of code, in Python we’re defining a blocks of code using indentation.

Indentation Rules

  • All the statements within a block must use the same indentation (the same amount of spaces or tabs).
  • It is recommended to use four spaces as indentation to make your code more readable.
  • You must not mix spaces and tabs to indent statements in your Python program.
  • Any block of statements can have an inner blocks with the next indentation level.

Let’s take a look at one of the previous Python program examples:

#!/usr/bin/env python3
"""
This program copies objects from source to destination S3 bucket
"""
import boto3
REGION = 'us-east-2'
SRC_BUCKET = 'hands-on-cloud-python-course-src-bucket'
DST_BUCKET = 'hands-on-cloud-python-course-dst-bucket'
S3_RESOURCE = boto3.resource('s3', region_name=REGION)

def copy_objects():
    src_bucket = S3_RESOURCE.Bucket(SRC_BUCKET)
    dst_bucket = S3_RESOURCE.Bucket(DST_BUCKET)
    print(f'Source S3 bucket: {SRC_BUCKET}')
    print(f'Destination S3 bucket: {DST_BUCKET}')
    
    for s3_object in src_bucket.objects.all():
        print(f'Copying object: {s3_object.key}')
        source_file_data = {
            'Bucket': SRC_BUCKET,
            'Key': s3_object.key
        }
        dst_bucket.copy(source_file_data, s3_object.key)

if __name__ == '__main__':
    copy_objects()

In this program, the function copy_objects() contains two blocks:

  • Main function block at lines 17-31
  • Nested function block describing for loop at lines 23-31
5. Python syntax - Indentation Rules - Example

Parentheses

Parentheses in Python are used for the following operations:

  • Grouping
  • Calling

Grouping

Grouping is usually used in mathematical expressions when you need to specify an order of the operations.

For example:

>> result = (2 + (3 * 4 + 1)) / 2
>> print(result)
7.5

Without parentheses, the result variable value would be:

>> result = 2 + 3 * 4 + 1 / 2
>> print(result)
14.5

Interpreter output at Cloud9 IDE:

6. Python syntax - Parentheses - Grouping example

Naming conventions

An identifier is a name given to Python program elements like variables, functions, classes, modules, packages, etc.

You should start identifier name with either lower or upper case alphabet letter or an underscore ( _ ) symbol, and it can contain more than one alphabet letter (a-z or A-Z), digits (0-9), or underscores (no other characters are allowed).

  • Identifiers in Python are case sensitive, what means variables named S3_bucket and s3_bucket are different.
  • Class names should use the CamelCase naming convention, for example:
    • DynamoDbManager
    • S3FileManager
    • MyDynamoDbProductItem
  • Function should be named in lowercase, where multiple words should be separated by underscores, for example:
    • dynamodb_add_item(product)s3_object_upload(object_name).
  • Variable names in the function should be specified in lowercase, for example:
    • src_bucket
    • dst_bucket
  • Module and package names should be in lowercase, for example:
    • my_module
  • Constant variables should be named in uppercase, for example:
    • REGION
    • S3_RESOURCE

More information is available at PEP 8 – Prescriptive Naming Conventions documentation.

Comments

In Python, there are two types of comments:

  • Single line comment – starts from the symbol ( # )
  • Multi line comment – surrounded with triple ( ''' ) or ( """ ) quotes

Single line

Example of single-line comments (lines 1, 3, 10-11):

# This function copies files from one S3 bucket to another
def copy_objects():
    # Initializing S3 buckets resources
    src_bucket = S3_RESOURCE.Bucket(SRC_BUCKET)
    dst_bucket = S3_RESOURCE.Bucket(DST_BUCKET)
    print(f'Source S3 bucket: {SRC_BUCKET}')
    print(f'Destination S3 bucket: {DST_BUCKET}')
    # Copying S3 objects
    # from one bucket to another
    for s3_object in src_bucket.objects.all():
        print(f'Copying object: {s3_object.key}')
        source_file_data = {
            'Bucket': SRC_BUCKET,
            'Key': s3_object.key
        }
        dst_bucket.copy(source_file_data, s3_object.key)

Multi-line

Example of multi line comments (lines 3-5):

def copy_objects():
    """
    This function copies files
    from one S3 bucket to another
    """
    src_bucket = S3_RESOURCE.Bucket(SRC_BUCKET)
    dst_bucket = S3_RESOURCE.Bucket(DST_BUCKET)
    print(f'Source S3 bucket: {SRC_BUCKET}')
    print(f'Destination S3 bucket: {DST_BUCKET}')
    
    for s3_object in src_bucket.objects.all():
        print(f'Copying object: {s3_object.key}')
        source_file_data = {
            'Bucket': SRC_BUCKET,
            'Key': s3_object.key
        }
        dst_bucket.copy(source_file_data, s3_object.key)

Similar Posts