Python for DevOps: Chapter1 - Introduction

Python for DevOps: Chapter1 - Introduction

The credit for creating Python goes to Guido van Rossum, at National Research Institute for Mathematics and Computer Science, Netherlands. Many people think that the Python language is named after the Python snake, but it is not so, it is named after a very popular BBC TV show Monty Python's Flying Circus.

Python became an Open Source project right from the beginning of its inception. Van Rossum is the principal author and Benevolent Dictator for Life (BDFL) for Python, and hence he has the final say about any changes to the Python codebase. Although the development of Python was started in the late 1980s, the first official version of it was released in 1994, and the second version on October 16, 2000, with many new major features such as garbage collection, support for Unicode. And version 3, was released on December 3, 2008. At the moment both versions 2 and 3 are maintained simultaneously by the Python community because of compatibility issues in these versions.

Installing Python

Python installer can be downloaded from the Python.org website. Some of the Linux flavors have Python installed in them, however, if it is not there, use the below command to install using the shell.

sudo apt install python3.7

On Windows, chocolatey can be used to install python quickly and easily.

choco install python

Use python --version to check the version of Python installed.

Python Shell

When you install Python, it also installs Python shell. It is an interactive interpreter, and it is very basic and easy to start using Python. To use the Python shell, just type Python in command prompt, and to exit from the shell use exit() function.

Python-Shell.PNG

Python Files

Python files have .py as an extension. Python codes can be saved in a file and then that file can be called and run in command prompt or any other shell in the below format. python filename.py

Let's write our first Python program and run it. (VSCode is my go-to IDE for almost everything).

Create a file as hello.py and add the below code to it.

# This is my first Python script
print("Hello world!")

Now to invoke the script, type python .\hello.py . Please make sure that the current working directory should be where the hello.py file is kept.

hello.PNG

Variables

A variable is a name that points to the computer memory location where you store value. Python variables are dynamically typed, which means the same variable can be reassigned to values of different types.

In the below example, variable big is first assigned an integer value and then a string value.

variables.PNG

Comments

Documentation is a love letter that you write to your future self. - Damian Conway.

And comments are considered documentation, some document generating tools heavily depend on comments. So let us see how comments work in Python. (Comments are texts ignored by the interpreter/compiler)

# is used to do a single-line comment.

# This is single-line comment

print("Hello World!") # This comment is after a statement

For multiline comments, enclose your comments in either """ or '''

"""
This
is
an
example
of
multiline
comments
"""

Comments.PNG

Basic Mathematical Operations

Basic mathematical operations in Python can be easily performed by using the built-in available math operator.

maths.PNG

Loops and Control Statements

Loops are useful when you want a block of code to execute many times as per some conditions. Block of code can be run multiple times using for or while loops or using some tricks with if statements or try-except block.

if/elif/else

This statement is used to decide which code of block to execute. The syntax of if/elif/else is as below.

if <condition> :
  …
elif <condition> :
  …
else:
  …

elif is sort of else if, and it can be 0 or more. else part is optional. When the condition is true, the underneath statements get executed.

Below is an example of if/elif/else.

if_elif_else.PNG

if statements can be nested and if the outer if statement is True then only the inner if statement gets checked.

for loops

for loops are used to iterate through the sequence. The syntax of for loop is as below.

for i in <sequence> :
  …
  …

An example of iterating through the bird's list is below.

for.PNG

range() function

To iterate through a number, use range() function. The sample code of range() function is as below. Here the output will print numbers from 0 to 5.

for i in range(6):
    print(i)

continue and break

continue statement skips a step in the loop, whereas break statement exits from the loop.

birds = ["Crow", "Peacock", "Dove", "Pigeon", "Sparrow"]
for bird in birds :
    if bird == "Dove" :
        continue
    elif bird == "Sparrow" :
        break
    print(bird)

In the above code, when the if condition is true, it will skip the sequence, and when the elif condition is true, it will exit out of the loop. And because of that, the output will be Crow, Peacock, and Pigeon.

Exception Handling

Exceptions are events that cause your program to crash if not handled. Using try-except block allows handling the exceptions. There has to be at least one except statement if there is try statement, there can be more than one except statement. The except block only executes when there is an exception in try block. There is finally block also, it executes irrespective of whether exceptions occurred or not. finally is used to clear out variables, to close open connections which are not needed.

In the below code, it throws ZeroDivisionError as the exception and the program crashed, and it did not run the print statement.

zerodivisionerror.PNG

Let us put the code inside the try-except block, and now even though the exception is raised the print statement is executed.

except.PNG

It is always recommended to use specific exception type in except statement, however, you can use the generic one Exception also.

Lists

Lists are one of the most popular ways to store data in an ordered fashion. The use of square brackets [ ] is the syntax of the list. A list can be of any data type, can be a combination of different data types.

fruits = ["apple", “banana”, “orange”, “melon"]
numbers = [1, 2, 3, 4, 5, 6]
combo = ["apple", 2, "unto", true]

Dictionary

Dictionary is pair of key values. The use of curly brackets { } is the syntax of the dictionary.

capitals = {
    "India": "New Delhi",
    "Australia": "Canberra",
    "Denmark": "Copenhagen",
    "Japan": "Tokyo",
    "United Kingdom": "London",
}

print(capitals["India"])

To find a value from the dictionary using a key is very efficient and fast in nature. The key and value of the dictionary can be of any data type. If the same key is again repeated in the dictionary, the latest value overrides the previous ones.

Functions

When you want to repeat the same line of code at multiple places, it's logical to create a function and encapsulate all the lines of code in it. By creating functions, the code will be better organized, maintainable, and easier to understand.

def <function_name> (<param1>, <param2>, …):
  …
  …

The first word is def and then the name of the function. Parameters can be inside the brackets if there are many parameters, separate them by commas.

To call a function, use the function name.

def positioned(first, second):
    print(f"first: {first}")
    print(f"second: {second}")

positioned(1, 2)

The default value for the parameters in the function can also be set, as given below.

def get_city(city="Mumbai"):
    print(f"City: {city}")

get_city()
get_city("Bangalore")

In the above example, when the first time the method is called without passing the parameter, it would print City: Mumbai but when the function called using Bangalore as the parameter, it would print City: Bangalore.

Python will not complain if you use tabs or spaces to indent as long as you are consistent.

This is it in this chapter, in the next chapter we will go through how to automate files and file systems.

Did you find this article valuable?

Support Pawan Dubey by becoming a sponsor. Any amount is appreciated!