Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
143 views

Python and Automation by Nitikesh

The document discusses automation and provides examples of automation in industrial and IT contexts. It recommends Python as a programming language for automation due to its simplicity, flexibility in running on different platforms, extensive libraries, and ability to work on both Windows and Linux systems. The document then provides details on installing and using Python for automation, including setting environment variables, Python syntax for input/output, conditional statements, loops, lists, dictionaries and string manipulation.

Uploaded by

vinay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
143 views

Python and Automation by Nitikesh

The document discusses automation and provides examples of automation in industrial and IT contexts. It recommends Python as a programming language for automation due to its simplicity, flexibility in running on different platforms, extensive libraries, and ability to work on both Windows and Linux systems. The document then provides details on installing and using Python for automation, including setting environment variables, Python syntax for input/output, conditional statements, loops, lists, dictionaries and string manipulation.

Uploaded by

vinay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Automation By, Nitikesh (CTO @ idslogic)

Introduction
A process which runs automatically without any user guide to full fill the user needs is called
Automation.
Automation can be derived into two types:
1. Industrial Automation
2. IT Automation
Industrial Automation:
Use of electronics tools to minimize the work load for the user to gain more accuracy and
reduce the time scale.

E.g.: Robot Automation, Auto Drive Car automation etc.


IT Automation:
Development of new Application/workflow/tools which replaces the manual works for the
users which needs to be done repeatedly.

E.g.: Chat Bots, Automation scripts/tools etc.


Why Automation?
1. Reducing Time
2. Increasing Efficiency
3. Reducing man Power
4. No Dependencies
5. Profitable
Technology Stack
Automation can be done using any programming Languages. But choosing one programming
language for your required automation, is more important.
Because every language has its own significance and we need to choose the best practiced
Language for the automation.

For Industrial Automation, we normally use C/C++ and Python Raspberry pi for Electronic
tools.
For IT Automation, we need to choose the correct Automation Language for the required
Platform.
E.g: Let’s assume you have one Linux OS and you want to use C# for the Automation, then
it will be much more complicated for you to use DOT NET C# in Linux. (You can achieve that
by installing WinBox/Wine in Linux but it is not recommended). So, we have to use Linux
based Languages like Python, Shell scripting, perl, ruby etc.

Recommended Language for Windows/Linux Both is Python. And For Windows it should be
Batch script/C# but for Linux it should be Shell script/Python/any Linux oriented Languages.
Introduction to Python:

Python is a dynamic, interpreted and light weight language. It does not use any variable data types as
this is a scripting language. Extension for python is .py

Note: Scripting languages has no data types. E.g.: php, python etc.
Why Python?
1. Interactive (This makes code short and flexible)
2. Runs in independent platform (in Any OS like Windows/Linux/Mac)
3. Modular (Python uses modules to modularize codes)
4. Open Source (Free of Cost in the market)
5. Extensive libraries

How to install Python in Windows?

1. First go to https://www.python.org/downloads/and download your required python


version.
2. After download has been completed, Double click on the setup file to start the installation.
Follow the GUI instructions to install Python into your System.
3. After the installation has been completed mark the line where it’s mentioned that “set
Environment variable automatically”.

An environment variable is a dynamic-named value that can affect the way running processes will
behave on a computer. They are part of the environment in which a process runs.

If you will set the environment variable for python, then you can use python.exe anywhere from cmd
(Command Prompt) by typing “python <options>”

How to set Environment Variable in Windows?

1. Go to My Computer’s Properties → Advanced System Settings →Advanced → “Environment


Variables”

2. Scroll Down and find Variable name as “Path” and Edit it. Then Add your Python installation
directory there, so that you can access it directly from Command Prompt. In my case I will
add “C:\\python\\” in the Text Box and click on “OK”.
3. Now You can access Python Directly from Cmd. To run a python file command is “Python
<file directory with file name>”. E.g.: python C:\\test\\sum.py
How to install Python 3.x.x in Ubuntu?

Command for installing python in ubuntu are:

$ sudo apt-get install software-properties-common

$ sudo add-apt-repository ppa:deadsnakes/ppa

$ sudo apt-get update

$ sudo apt-get install python3.6

Comparison of C & Python & C# removing default pre-processor or Namespace or Directives


(E.g.: #include, Using, Namespace etc.)

Program Name C Program Python Program C# Program


“Hello World” Program

Execution Time Taken


0.00002s 0.00007s 0.0001s
Rating Based On Code 3 1 4
Complication (out of 5)
Libraries & Platform Very few More More
independent No, works only in GCC Yes No works in MS Framework only

As you can compare with the above table, C Language is the faster than the Python and C# code. But
python has the simplest coding format with best Performance. Python checks the variables and its
datatype which takes some time to execute, but you can avoid it and improve performance by using
Cython, numpy, pandas, numba and different Data structure implementations.

What we got?

1. C Program – High Speed – Medium Code Complications – Classic and have very few libraries
2. Python – Medium Speed – Very simple code structure – Advanced and Rich libraries
3. C# - Medium Low Speed – Medium Code Complications – Advanced and Rich libraries

Now even you can choose the best programming Language for any kind of applications using their
compatibility, speed and Complicacy.

For best performance and good Coding structure I am choosing python for describing.

In the next chapter, I will be describing about Python3 basics and will try to complete it in short & wise.
Python3 Input/output:

Keyword syntax Keyword Work


print(string) Show output as string
Input(string) Take input from the user

String is the mixture of characters. It is equivalent to sentence with all special characters.

E.g.: “Hello Dear, how are you.”

Here “Hello Dear, how are you.” Is String. And ‘H’,’e’,’l’,’l’,’o’,’,’,’h’,’o’,’w’,’ ‘,’a’,’r’,’e’,’
‘,’y’,’o’,’u’,’.’ are the characters.

# is used for Commenting single line and ‘’’ is used to comment multiline in python.

Python uses Colon (:) to modularize the code statements. After putting Colon (:), you need to give
spaces in the next line to continue with the particular module. (It is called Indentation in python.)
The best practice to use 4 spaces / one tab to modularize the code.

Python3 Conditional Structure:

If Statement:

Syntax:

if (Condition): #Used Colon to use more codes inside if statement


Statement1 #Used 4 space to be inside If statement
Statement2 #Again used 4 spaces to be inside If statement
Statement3 #Statement3 will not be inside If statement

E.g.:

If the password is wrong then it will only print “Execute Successfully!!”.


If…else Statement:

Syntax:

if (Condition): #Used Colon to use more codes inside if statement


Statement1 #Used 4 space to be inside If statement
Statement2 #Again used 4 spaces to be inside If statement
else: #Used Colon to use more codes inside else statement
Statement3 # Used 4 space to be inside else statements

Statement4 #Statement4 will not be inside If /else statement


E.g.:

If...elif...else Statement:

Syntax:

if (Condition): #Used Colon to use more codes inside if statement


Statement1 #Used 4 space to be inside If statement
elif (Condition): # Used Colon to use more codes inside elif statement
Statement2 # Used 4 space to be inside elif statements
else: #Used Colon to use more codes inside else statement
Statement3 # Used 4 space to be inside else statements
Statement4 #Statement4 will not be inside If /else statement

E.g.:

Nested If Statement:

Syntax:

if (Condition1): #Used Colon to use more codes inside if statement


Statement1 #Used 4 space to be inside If – 1 statement
If(Condition2):
Statement2 # used 4 spaces + another 4 spaces to be inside If - 2
Statement3
E,g:

Addition Program in Python:

str() used for convert from


Interger type to String.

Python Looping:
1. While Loop
2. For Loop
While Loop:
Syntax:

While(Condition):

Execution

Statement

E.g.:

For Loop:
Syntax:

For iterations in sequence:

Executions/Statements
E.g:

Lists in Python:

A List is a datatype in python. List supports any kind of datatype/objects in it.

E.g:

List1 = [1,2,3,4,5] → Integer Datatype

List2 = [‘a’,’b’,’c’,’d’] → Character Datatype

List3 = [“Hello World”] → String datatype

List4 = [Unknown Datatype] → Object

We can store mixed data type in a list.

List5 = [1,2,’a’,’b’,”Hello World”,None] #None represents nothing

To access List members, we use index technique.

List5[0] will give us “1” as output.

Best way to access one list is to use For Loop.

E.g.:

Dictionaries in Python:

Syntax:

Dict = {key: value}

Access Value by Dict[key].


E.g.:

In the above code, using For Loop and Dictionary we have got one better and scalable Python code by
putting username as key and password as value.

String Modifications in Python:

String manipulation is a very important factor in Python. Python represents the strings using Single
quote (‘) as well as double quote (“).

E.g.: string1 = ”Nitikesh” and string1 = ’Nitikesh’

Utilization or Usage of String:

String can be access using indexing method. Every string starts with an index of 0.

E.g.: string1=”Nitikesh” → Here Index 0 is N, Index 1 is I, Index 2 is t and so on.

For Accessing those index we use the below format:

string1[0] will give us an output as ‘N’.

String Slice in Python:

For accessing a sub string inside a full string is called slicing.

If we will go from left to right then the indexing starts with 0 and if we will go from right to left
then the indexing starts from -1.
Syntax: stringname[start_index:end_index:steps], default step is 1.
Step represents the difference between the index numbers.

E.g.:str1=”Hello World” , str1[0,4] will give us the output “Hell” , str1[-5:-1] then the o/p is “Worl”

str1[0:6:2] then the o/p is “hlo” because it will take index 0 then index 2 then index 4 then index 6
Using the String slice, we can remove many lines of codes. We can take the example of reverse of a string.

In other languages, we have to write a bunch of codes to get the reverse of a string. But here we can get it
by single line.

E.g.: Str1=”Hello” and the reverse will be Str1[::-1]

It will start from start to end in the steps of -1 which is in reverse order.

Explanation: If we will use Str1[-1:0:-1] then it will give us the out put in reverse order but it will
remove the first character as we have set a limiter as 0. But if we will remove that limiter then we can use
another way to get the reverse of a string as well by using Str1[-1::-1].

You can access the characters from a string using Looping as well.

Let’s take an example of finding the count of numbers in a string.

Tuples in Python:

Tuple is similar to list. But in List, the values are mutable and in Tuple, the values are Immutable.

Mutable means values can be modified in list but in tuple, we can’t change the values
inside it.

Type() is a function is used to get the datatype of the variable in python.


Must watch the below example to understand tuple more.
E.g:

Python functions:

Python functions are very important thing for modularize the code and to write a very efficient code base.

Python functions must need to be defined before it will get called.

We define python functions as “def”.

Refer to the below example for better understanding on functions.


As per the coding standards, you should always use camelCase. The first letter is
small and then with each word joined it will be capital. E.g.: firstFunction

E.g.:

Accessing/Modifying and Deleting Files in Python:

In our daily life, we use to work on files and stores them in our systems. For accessing the file, we
normally use MS Word, Notepad and other software’s as they provide more features to accessing and
modifying the data.

Here also we will do the same thing with any other software’s but using python code.

Why to use python to modify the data?

If there is any kind of changes you are doing daily in the file then you can create the python script to make
the work simple and automated. It will save your time and effort seamlessly.

How to open a file in python?

We use “open” function to open the file. Open function takes two arguments. Compulsory one is File’s
Location and optional one is the permission for the file. The default permission is read only. For write, we
use “w”.

E.g.: fileOpen = open(“C:\\test.txt”,’w’)

If we are opening a file then we need to close the file or it will run in the background process which will
take more memory space each time you will run it.

We use Close() function to close the file. E.g.: fileOpen.Close()

For more information regarding the Files and its usage, please find the below example.
Python Cheat Sheet:

1. We can use “import” to import other prebuilt or manual modules into our scripts.
E.g.:

2. We can use dir() function to get the sub functions for the given module/class.

3. For reading and writing excel, you must use “xlrd” module.
4. For getting current date and time use datetime module.

5. For delay or sleep, use time module

Shows a perfect 10 second sleep.


6. As we have not discussed any OOPs concept in this Basic learning of python, I would be
suggesting you to go through the OOPs concept or contact us for more accurate instructions.
7. Creating a simple virus of auto folder creation on desktop in python.

8. How normal memory system works?


In a normal Hard drive, data stored in the arrangements of 4kb blocks. If the data is of 11 KB,
then it will take 4KB+4KB+3KB from the HDD and rest 1KB will be lost and will not be used
further.
4KB 4KB 4KB 4KB
4KB 4KB 4KB 4KB
4KB 4KB 4KB 4KB
4KB 4KB 4KB 4KB
After the Python tutorial, I will demonstrate some automations for daily life. Please find the
below demonstrations.
Automation Script for creating/modifying a file with the date & time when ever System is
opened.

After the script has been written, put the .py file it into Folder:
“C:\Users\[Username]\AppData\Roaming\Microsoft\Windows\Start
Menu\Programs\Startup\”
It will trigger the program to run in every system start up.
Automation Script for Alerting Bitcoin Price in every Hour.
To get bitcoin price, we will use https://api.coindesk.com/v1/bpi/currentprice/inr.json

For setting it for running in every 1 hour, we will use “Task Scheduler” or a manual python
script as below.

Request module used for handling the GET/POST/.. methods. It sends request to the websites and
will get response from the websites.

Response code 200 means the web site responded to its request.

GET requests a representation of the specified resource. But POST submits data to be processed
to the identified resource. POST is secured than GET.
How to use task scheduler?

Search for task scheduler in search box and open it. Then right click on the Task Scheduler
(Local) and create a new Task

Then Name the Task. In our case I am giving a name “BTC PRICE NOTIFIER”.

Then go to triggers and click on New. Then select daily and repeat in 1 hour for a duration of
indefinitely.

After that click on ok.

Then go to Actions and Click on new. Then browse the script you want to run. (If want to run
direct python file (.py) then make sure that environment variable is properly set.)

Then click on ok and again click on ok. Now you are done with your scheduler which will run in
every hour to notify you for Bitcoin’s Price.

Some codes in Batch script for knowledge:

Extension: .bat

How to show a matrix view?

You might also like