The Ultimate Guide: Getting Started with Python( Python for beginners)

Python’s standard library is very extensive, offering a wide range of facilities . The library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming

In this tutorial we will learn everything which a beginner and a Devops engineer should know in Python. We will cover basic definition of python and some brilliant examples which will be enough to get you started with Python and for sure you will love it.

Table of content

  1. What is Python?
  2. Prerequisites
  3. Variables
  4. Strings
  5. Dictionary
  6. Lists
  7. Python Built-in functions
  8. Handling Exceptions
  9. Python Functions
  10. Python Searching
  11. Conclusion

What is Python?

Python is a high level , oops based , interactive and a general purpose scripting programing language. Python is a language which is used as a backend as well as frontend language. It focuses on object over functions.

Python is also a interpreted language because it converts codes in machine level code even before it runs. It works on variety of protocols such as https, ftp , smtp and many more. The latest version is 3.9.2 which was released in December 2020. Python works very well with most of the such as atom, notepad ++ , vim.

Python works on windows , Linux and macOS system and many more. For windows OS it can run a single command on windows terminal and for Linux & macOS it can easily run on shell without needing to save the program every time.

Prerequisites

  • Python doesn’t come installed on windows so make sure you have Python installed on windows machine. To see how to install python on windows click here.
  • For macOS and Linux Python comes installed by default but could be the older version such as python2. To check python version run the command.
python
This is older version Python2
  • Also use command python3 in lowercase to check if Python3 is installed.
python3
  • In case both the commands shows either Python2 or Python not found run the following command to install python.
sudo apt install python3

Variables

Variables are stored as a information it could be number , symbol , name etc. which are used to be referenced. Lets see some of the examples of Python variables.

  • There are few points one must remember when using variables such as
    • Variables cannot start with digits
    • Spaces are not allowed in variables.
    • Avoid using Python keywords

Example 1:

  • In below example var is a variable and value of var is this is a variable
var="this is a variable" # Defining the variable
print(var)    # Printing the value of variable

Example 2:

  • In below example we are declaring three variable.
    • first_word and second_word are storing the values
    • add_words is substituting the variables with values
first_word="hello"
second_word="devops"
add_words=f"{first_word}{second_word}"
print(add_words)
  • If you wish to print words in different line then use "\n" as below
first_word="hello"
second_word="devops"
add_words=f"{first_word}\n{second_word}"
print(add_words)

Strings

Python strings are collection of characters surrounded by quotes ” “. There are different ways in which strings are created.

  1. str() :
"This is method 1 to display string"

2. Directly calling it in quotes

"Hello, this is method2 to display string"

3. Using Format:

This was introduced in Python3 and uses curly brackets {} to replace the values.

Example 1

In below example you will notice that first curly bracket will be replaced by first value that is a and second will be replaced by b

'{} {}'.format('a','b')

Example 2

In below example if you provide any numerical value inside the curly braces it considers it as index and then retrieve from the given values accordingly

'{0} {0}'.format('a','b')

Example 3

In below example if you provide key value pair then values are substituted according to key

'{a} {b}'.format(a='apple', b='ball')

4. Using f string

f string are prepended with either f or F before the first quotation mark. Lets take a example.

a=1
f"a is {a}" 

5. Template strings are designed to offer a simple string substitution mechanism. These built-in methods work for tasks where simple word substitutions are necessary.

from string import Template
new_value = Template("$a b c d")       #  a will be substituted here
x = new_value.substitute(a = "Automation")
y = new_value.substitute(a = "Automate")
print(x,y)

Dictionary

In simple words these are key value pairs where keys can be number, string or custom object. Dictionary are represented in key value pairs separated by comma within curly braces.

map = {'key-1': 'value-1', 'key-2': 'value-2'}
  • You can access the particular key using following way
map['key-1']

Lets see an example to access values using get() method

my_dictionary = {'key-1': 'value-1', 'key-2': 'value-2'}
my_dictionary.get('key-1')    # It will print value of key-1 which is value-1
print(my_dictionary.values()) # It will print values of each key
print(my_dictionary.keys())   # It will print keys of each value
my_dictionary.get('key-3')    # It will not print anything as key-3 is missing

Lists

Lists are ordered collection of items. Lists are represented using square brackets containing ordered list of item.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Example of List
  • We can add or remove items from the list using built in function such as pop() or insert() or append() and many more. Lets us see an example.

The contents of one list can be added to another using the extend method:

list1 =['a', 'b', 'c', 'd']
print(list1)                        # Printing only List 1
list2 = ['e', 'f']
list2.extend(list1)
print(list2)                        # Printing List 2 and also 1
  • Use insert() to add one new guest to the beginning of your list.
  • Use insert() to add one new guest to the middle of your list.
  • Use append() to add one new guest to the end of your list.

Python Built-in functions

There are various single line command which are already embedded in python library and those are known as built in functions. You invoke a function by typing the function name, followed by parentheses.

  • To check the Python version on windows or Linux machine run the following command.
python3 --version
  • To print the output of a program , use the print command.
print("Hello Devops")
  • To generate a list of number through a range built-in function run the following command.
list(range(0,10))

Handling Exceptions

Exceptions are error which causes a program to stop if not handled properly. There are many built-in exceptions, such as IOErrorKeyError, and ImportError. Lets see a simple example below.

  • Here we defined a list of characters and stored it in a variable devops
  • Now, while true indicated that till the ,condition is true it will execute the try block.
  • .pop() is built in method to remove each item one by one.
  • Now in our case as soon as all the characters are removed then except block catches the IndexError and prints the message.
devops = ['d','e','v','o','p','s']
 
while True:
    try:
        devop = devops.pop()
        print(devop)
    except IndexError as e:
        print("I think I did lot of pop ")
        print(e)
        break
 
Output:
 
s
p
o
v
e
d
I think I did lot of pop
pop from empty list

Python Functions

Earlier in this tutorial we have already seen that there are numerous built in function and some of them you used above. But you can define and create your own functions. Lets see the syntax of function.

def <FUNCTION NAME>(<PARAMETERS>):
    <CODE BLOCK>
<FUNCTION NAME>(<ARGUMENTS>)

Lets look at some of the Python functions examples

EXAMPLE 1

  • Here each argument use order of arguments to assign value which is also known as positional argument.
  • a and b variables are parameters which are required to run the function
  • 1 and 2 are arguments which are used to pass the value to the function ( arguments are piece of information that’s passed from a function call to a function)
def my_function(a,b):
  print(f" value of a is {a}")
  print(f" value of b is {b}")
my_function(1, 2)

EXAMPLE 2:

  • With keyword arguments, assign each argument a default value:
def my_function(a=3,b=4):
  print(f" value of a is {a}")
  print(f" value of b is {b}")
my_function()

EXAMPLE 3

Passing arbitrary number of arguments. When you are not sure about the number of parameters to be passed then we call it as arbitrary. Lets look at an example

  • Find the Even in the string

mylist = []
def myfunc(*args):      #  args is to take any number of arguments together in myfunc
    for item in args:
        if int(item)%2 == 0:
            mylist.append(item)
    print(mylist)
myfunc(5,6,7,8,9)

EXAMPLE 4

  • IF LOOP: Find the least among two numbers if both numbers are even else return greater among both the numbers

def two_of_less(a,b):    # Defining the Function where a and b variables are parameters
    if a%2==0 and b%2==0:
      print(min(a,b))       # using built in function min()
    if a%2==1 or b%2==1:
      print(max(a,b))       # using built in function max()
two_of_less(2,4)

EXAMPLE 5

  • Write a function takes a two-word string and returns True if both words begin with same letter

def check(a):
    m = a.split()
    if m[0][0] == m[1][0] :
     print("Both the Words in the string starts with same letter")
    else:
     print("Both the Words in the string don't start with same letter")    
check('devops Engineer')

Python Searching

The need to match patterns in strings comes up again and again. You could be looking for an identifier in a log file or checking user input for keywords or a myriad of other cases.

Regular expressions use a string of characters to define search patterns. The Python re package offers regular expression operations similar to those found in Perl.

Lets look at example which will give you overall picture of in built functions which we can use with re module.

  • You can use the re.search function, which returns a re.Match object only if there is a match.
import re
import datetime
 
name_list = '''Ezra Sharma <esharma@automateinfra.com>,
   ...: Rostam Bat   <rostam@automateinfra.com>,
   ...: Chris Taylor <ctaylor@automateinfra.com,
   ...: Bobbi Baio <bbaio@automateinfra.com'''
 
# Some commonly used ones are \w, which is equivalent to [a-zA-Z0-9_] and \d, which is equivalent to [0-9]. 
# You can use the + modifier to match for multiple characters:
 
print(re.search(r'Rostam', name_list))
print(re.search('[RB]obb[yi]',  name_list))
print(re.search(r'Chr[a-z][a-z]', name_list))
print(re.search(r'[A-Za-z]+', name_list))
print(re.search(r'[A-Za-z]{5}', name_list))
print(re.search(r'[A-Za-z]{7}', name_list))
print(re.search(r'[A-Za-z]+@[a-z]+\.[a-z]+', name_list))
print(re.search(r'\w+', name_list))
print(re.search(r'\w+\@\w+\.\w+', name_list))
print(re.search(r'(\w+)\@(\w+)\.(\w+)', name_list))
 

OUTPUT

<re.Match object; span=(49, 55), match='Rostam'>
<re.Match object; span=(147, 152), match='Bobbi'>
<re.Match object; span=(98, 103), match='Chris'>
<re.Match object; span=(0, 4), match='Ezra'>
<re.Match object; span=(5, 10), match='Sharm'>
<re.Match object; span=(13, 20), match='esharma'>
<re.Match object; span=(13, 38), match='esharma@automateinfra.com'>
<re.Match object; span=(0, 4), match='Ezra'>
<re.Match object; span=(13, 38), match='esharma@automateinfra.com'>
<re.Match object; span=(13, 38), match='esharma@automateinfra.com'>

Conclusion

In this tutorial you learnt everything which a beginner and a Devops engineer should know. This tutorial covered definition of python and some brilliant examples which will be enough to get you started with Python and for sure you will love it.

By Now, you are ready to build some exciting python programs. Hope you liked this tutorial and please share it with your friends.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s