Python Tutorial 1 – All you need to know !!

Table of Content

  1. Understanding the difference between high level and low level language.
  2. Interpreted v/s Compiled Language
  3. How Python Works ?
  4. Python Interpreter
  5. Introduction to Python
  6. Python Standard Library
  7. Python Implementations
  8. Python Installation
    • Python Installation on Linux Machine
    • Python Installation on Windows Machine
    • Python Installation on MacOS
  9. Python Keywords
  10. Python Data types
  11. Conclusion

Understanding the difference between High & Low level Languages

High Level Language : High level language is easier to understand that is it is human readable. It is either compiled or interpreted. It consume way more memory and are slow in execution. It is portable. It requires compiler or interpreter for translation.

The fastest translator that converts high level language is .

Low Level Language : Low level Language are machine friendly that is machines can read the code but not humans. It consume less memory and are fast to execute. It cannot be ported. It requires assembler for translation.

Introduction to Python

Python is a high level language, which is used in designing, deploying and testing at lots of places. It is consistently ranked among todays most popular programming languages. It is also dynamic and object oriented language but also works on procedural styles as well, and runs on all major hardware platforms. Python is an interpreted language.

Interpreted v/s Compiled Language

Compiled Language: Compiled language is first compiled and then expressed in instruction of target machine that is machine code. For example – C, C++, C# , COBOL

Interpreted Language: Interpreter is a computer program that directly executes instructions written in a programming or scripting language, without requiring them previously to have been compiled into a machine language program and these kind of languages are known as interpreter languages. For example JavaScript, Perl, Python, BASIC

How Python Works ?

  • First step is to write a Python program such as test.py
  • Then using Python interpreter program is in built compiled and gets converted into byte code that is test.pyc
  • Now byte code that is test.pyc is further converted into machine code using virtual machine such as (10101010100010101010)
  • Finally Program is executed and output is displayed.
How Python runs? – Indian Pythonista

Python Interpreter

Python includes both interpreter and compiler which is implicitly invoked.

  • In case of Python version 2, the Python interpreter compiles the source file such as file.py and keep it in same directory with an extension file.pyc
  • In case of Python version 3 : the Python interpreter compiles the source file such as file.py and keep it in subdirectory __pycache__
  • Python does not save the compiled bytecode when you run the script directly; rather, Python recompiles the script each time you run it.
  • Python saves bytecode files only for modules you import however running Python command with -B flag avoids saving compiled bytecode to disk.
  • You can also directly execute Python script in the Unix operating system if you add shebang inside your script.
#! /usr/bin/env python

Python Standard Library

Python standard library contains several well designed Python modules for convenient reuse like representing data , processing text , processing data , interacting with operating system and filesystems and web programming. Python modules are basically Python Programs like a file (abc.py) which are imported.

There are some extension modules that allow Python code to access functionalities supplied by underlying OS or other software’s components such as GUI , database and network, XML parsing .You can also wrap existing C/C++ libraries into python extension modules.

Python Implementations

Python is more than a language , you can utilize the implementation of Python in many ways such as :

  • CPython: CPython is an interpreter, compiler, set of built in and optional extension modules all coded in C language. Python code is converted into bytecode before interpreting it.
  • IronPython: Python implementation for the Microsoft-designed Common Language Runtime (CLR), most commonly known as .NET, which is now open source and ported to Linux and macOS
  • PyPy: PyPy is a fast and flexible implementation of Python, coded in a subset of Python itself, able to target several lower-level languages and virtual machines using advanced techniques such as type inferencing
  • Jython: Python implementation for any Java Virtual Machine (JVM) compliant with Java 7 or better. With Jython, you can use all Java libraries and framework and it supports only v2 as of now.
  • IPython: Enhances standard CPython to make it more powerful and convenient for interactive use. IPython extends the interpreter’s capabilities by allowing abbreviated function call syntax, using question mark to query an objects documentation etc.

Python Installation

Python Installation on Linux Machine

If you are working on Latest platforms you will find Python already installed in the systems. You can either type Python command.

At time Python is not installed but binaries are available in the system which you can install using RPM tool or using APT in Linux machines and for Windows use MSI( Microsoft Installer ) .

Ubuntu 16 server
Ubuntu 18 server

Python Installation on Windows Machine

Python can be installed in Windows with few steps , and to install Python steps can be found here.

Python Installation on MacOS

Python V2 comes installed on MacOS but you should install latest Python version always. The popular third-party macOS open source package manager Homebrew offers, among many other packages, excellent versions of Python, both v2 and v3

  • To install Homebrew, open Terminal or your favorite OS X terminal emulator and run
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
  • Add homebrew directory at the top of your PATH environment variable.
export PATH="/usr/local/opt/python/libexec/bin:$PATH"
  • Now install Python3 using the following commands.
brew install python3
  • Verify the installation of Python using below command

Python Keywords

Python reserves certain words for special purpose known as keywords such as

  • continue
  • def
  • del
  • break
  • class
  • if
  • return

Python Data types

Whatever program you write in Python is a data and this data contains some values which is also known as objects. Each object has a type known as data types. These data types are either mutable in nature that is modifiable or immutable in nature that is unmodifiable.

Python contains numerous built in types such as:

  1. Numbers : These are of two types that is integer and floating point.
    • Decimal integer: 1 , 2
    • Binary integer: 0b010101
    • Octal integer: 0o1
    • Hexadecimal integer: 0x1
    • Floating point: 0.0 , 2.e0
  2. Strings

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

  • str() :
"This is method 1 to display string"
  • Directly calling it in quotes
"Hello, this is method2 to display string"
  • 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')
  • 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}" 
  • 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)
  1. Tuples : They are immutable ordered sequence of items that is they cannot be modified. The items of a tuple are arbitrary objects and may be of different types. For Example (10,20,30) or (3.14,5.14,6.14)

4. Lists: The list is a mutable ordered sequence of items. The items of a list are arbitrary objects
and may be of different types. For Example [2,3,”automate”]

5. Dictionaries: Dictionary is written as key:value pair , where key is an expression giving the item’s key and value is an expression giving the item’s value. For Example {‘x’:42, ‘y’:3.14, ‘z’:7} # Dictionary with three items, str keys.

6. Sets: Set stores multiple items in a single variable. It contains unordered and unindexed data. Sets cannot have two items with the same value. Example of sets are fruits = {“apple”, “banana”, “cherry”}

Data typesMutable or Immutable
StringImmutable (Cannot be modified)
TuplesImmutable (Cannot be modified)
IntegersImmutable (Cannot be modified)
ListMutable (Can be modified)
SetsMutable (Can be modified)
Floating pointImmutable (Cannot be modified)
DictionariesMutable (Can be modified)

Conclusion

In this tutorial you learned basic introduction to python , why it is interpreted and high level language. Also you learned lots of details of python datatypes , keywords and how python works. There were handful examples which you learned. Hope this tutorial will help you and if you like please share it.

Jump to another tutorial-2 for some more interesting facts about Python.

How to Setup Python on Windows machine

You might be already aware of difference between low level and high level language. Buts lets quickly see what are main difference between the both. High level language such as c , c ++ and python are portable , human friendly, that is they are easier to debug and understand while writing the programs. They need either compiler or interpreter to run the programs.

On the other hand, Low level language such as machine language or assembly level language they are difficult to understand and are written in assembly language which are converted using assembler.

In case of Linux distributions Python programming language by default , but in windows it does not come with it. In this tutorial, we will learn what is python which is widely used in artificial intelligence, by astronauts, by developers for creating the apps. Learning and setting python on windows is a need of the hour. So lets get started with it.

Table of content

  1. What is Python?
  2. Prerequisites
  3. How to install Python on windows machine?
  4. A simple python code to start your day
  5. Conclusion

What is Python?

Python is a high level , oops based , interactive and a general purpose scripting programing language. Python is very easier to understand and readable. 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 on December 2020. Python works very well with most of the such as atom, notepad ++ , vim.

Prerequisites

  • Windows 7 + operating system with admin rights
  • Command Prompt which is already present in windows operating system

How to Install Python on windows machine?

  • Now run the executable installer which got downloaded.
  • Next step will prompt you to select whether to Disable path length limit , you ignore it or disable it.
  • Now python should be installed on your windows machine.

 Verify Python Was Installed On Windows

  • Now Navigate to command prompt and type python
  • Pip is basically python package manager which is used to fetch lots of other additional modules. Pip comes with most of pythons executable. To check if it is installed use
pip -V
  • To verify if python environmental variables was successfully added. Search for sysdm.cpl and click on edit environmental variables.

A simple python code to start your day

  • Create a simple file main.py on your desktop
mystring = " This is Author of Automateinfra and its time to start learning python"
mylist   = [letter for letter in mystring] # This is function which iterates over each alphabet in mystring
print(mylist)       # This will print the result of mylist
  • Navigate to your desktop location on command prompt and use below command to run your first program in python
python main.py
  • Great work ! python was installed successfully and we could run our first program of python quickly.

Conclusion

In this tutorial we covered basic difference between high level language and low level language. We also discussed what is python and how to install python on windows machine to get you started in organization scripting and automation work.

Hope this tutorial will helps you in understanding and setting up Python on Windows machine.

Please share with your friends.

How to Automate JSON files and text files using Python

In the DevOps world, you are continually parsing, searching, and changing the text in files, why not automate them using Python. Lets learn how to automate files using Python with few lines of code.

Reading and Writing a text file using python

Using Pathlib module

Pathlib module: This module offers classes representing filesystem paths with semantics appropriate for different operating systems.

In below code snippet you will use pathlib module to open a test.txt file from defined path and then read the content using path.read_text() function and then stores it in the variable cont. Next, using path.write_text() it appends the data in the same file. The Path.write_text() function opens the file in text mode, write data to it, and close the file. Lastly using print() function it prints the value of both cont and cont1.

Lets learn to read and write into file using pathlib module with following example:

import pathlib
from pprint import pprint

path = pathlib.Path("test.txt")
cont = path.read_text()
cont1 = path.write_text("LOG:information technology")
print(cont)
# cont1 provides the number of indexes used in the text "LOG:information technology"
print(cont1)  
O/P:

Hi
26

Using open() function

With open() function you open the file to perform the operations such as read, append data or close the file etc. Here as soon as file is opened , it reads the file using read() function and stores the values in the content variable. Next, it prints the content and the length of content inside the file using print() and finally closes the file.

myfile = open('test.txt')
content = myfile.read()
print(content)
print(len(content))
myfile.close()   # Always close your file so that it doesnt consume memory
O/P:

LOG:information technology
26

Lets look at another example where mode is defined as r and w which denotes read and write . We can also use a to append the data in file. The Difference between w and a mode is w overwrites the data in file and a appends the data in file.

Also, If you intend to open any binary file such as pdf use the mode as rb or wb which denotes read or write binary.

In below example first file is opened and then read using read() function and prints the content. Next, you write the data in the file “Adding new line” in the file using write() function

with open("test.txt",mode="r") as mynewfile:   
    contents2 = mynewfile.read()
    print(contents2)

with open("test.txt",mode="w") as mynewfile:  
    contents1 = mynewfile.write("Adding new Line")
O/P

LOG:information technology

Reading and Writing a Json file using python

Using json.load() and json.dump()

  • Create a file and name it as file.json and paste the below content
{
 "a": 1,
 "b": 2
}

The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. Json module helps to work with JSON files such as reading a JSON file, writing data in JSON file or appending the file etc. json.load() function is used to open a JSON file. json.dump() function will add data into the JSON file.

Next , create another file and name it as program.py. Copy and Paste the below code. Here you will use json and pprint module along with open() function. Firstly you will open and read a JSON file using json.load() then Updating the file but only in outputs not in actual memory and finally Updating the file in outputs as well in actual memory using json.dump()

import pathlib
import json
from pprint import pprint

# Section 1: Opening and Reading a JSON file using json.load() 

with open('service-policy.json', 'r') as opened_file: # Opens a Json File
    policy = json.load(opened_file) 
    print(policy)
    pprint(policy)

# Section 2: Updating the file but only in outputs not in actual memory

policy['c'] = '3'  
pprint(policy)

# Section 3: Updating the file in outputs as well in actual memory using json.dump()

This way you will update the policy actually in memory

with open('service-policy.json', 'w') as opened_file1:
    policy2 = json.dump(policy, opened_file1)
print(policy2)

The output of the above program is as follows:

Conclusion

In this tutorial you learnt how to read and write text in text files and JSON files. Automating with Python is a fun and takes few lines of code and also keeps you away from silly manual errors. With that now, you have idea to automate files in python , what are you going to automate with Python?