python cheatsheet


Python is an open source general purpose language which started in 1991. Nowadays python is very popular because of the wide range of open source library available in python.

Python is cross-platform language, you can run it on Windows, Linux and Mac machine.

There is not complicated syntax in python. That’s why anyone can easily learn it.


Install Python

1. If you are a Linux user then you can use the following command to install python on the machine
1. sudo apt-get update
sudo apt-get install python3.6
b. If you are a window user then you can follow the below steps
1. Goto the link https://www.python.org/downloads/
2. Download the stable version.
3. Click on the executable and install.
Python can be installed into the window machine without any admin rights for a local user only.

In this article, I will give a basic understanding of python. Let’s do some example


Hello World Example:

To print anything on to your console python provide the print function
E.g. print(“Hello World”)

Like as any programming language python provide all possible elements
1. Variables and Types
2. List
3. Operators
4. Loops
5. Conditional statement
6. Class and objects
7. Module and packages

Let’s understand one by one

Please be careful about indent if there is a mismatch in indent python code will through an error, I will suggest you please VS code as your editor which help to maintain proper indent.

Python is case sensitive language, please take care of that also.

 


Variables and Types

In python, we did not need to define the type of variable python automatically detect the type of variable.

objects (like str, int, float) are immutable.

>>> x="xyz"
>>> type (x)
<type 'str'>
>>> x=1
>>> type (x)
<type 'int'>
>>> x=1.3
>>> type (x)
<type 'float'>

Numbers python support 2 types of numbers:
1. Integer
2. Float
Sample code:

#!/usr/bin/python

intnumber =7
floatnumber = 8.9
print(intnumber)
print(floatnumber)

### output
7
8.9

 


List

The list is kind of array in which we can store any kind of object and they are very easy to manage.

List is Mutable.

A simple example of a list is below:

#Declare a list

llist = []

You CANNOT assign values to index (if the index doesn’t exist… like for an empty list llist[0]=”a” will not work)

# Append data one by one to list

#!/usr/bin/python
llist=[]
llist.append(30)
llist.append(40)
llist.append(60)
print(llist)# we can also append data like below as a whole object:
llist.append([6,7,8])
print(llist)

############output ##########
[30, 40, 60]
[30, 40, 60, [6, 7, 8]]

 


Operators

Like as any programming language python provide basic arithmetical functions like
Addition, subtraction, multiplication which can be easily used over the different type of data.

Sample code:

!/usr/local/bin/python3.7
# Declare 2 variables
x=10
y=3

print("multiplication is : {0} ".format(x*y))
print("SUM is : {0} ".format(x+y))
print("Division is : {0}  ".format(x/y))
print("Subtraction is : {0}  ".format(x-y))


###### output ##########
multiplication is : 30 
SUM is : 13 
Division is : 3.3333333333333335  
Subtraction is : 7  

These operators can be used with String and list as well.

 


Loops

Python is mainly used 2 types of loops
1. For loop
2. While loop

Example of for loop

# run loop from 0 to 6 loop will run 7 times

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

# we can define loop range as is in below example
print(“Print loop in a range from 2 to 8”)
# Prints out 2,3,4,5,6,7

for i in range(2, 8):
 print(i)

# print loop in range by switching as in below example

for i in range(2, 9, 2):
 print(i)

Will print 2,4,6,8 (in steps of 2)

 

Example of  while loop:

#Simple counter using while loop

#!/usr/bin/python
counter = 0
while counter <=8:
 print(counter)
 counter += 2

=======result=======
0
2
4
6
8

 


What are the functions

Functions are the way to divide the code into small sections and made the code the
Reusable.

Functions are defined by def keyword in Python

def function_name(arguments):
 // code block


def printname(name):
  print(name)

###Function can return values also
def sum(x,y):
 return x+y;

 


Class and object

As we now python is an object-oriented language and classes and object are a very important part of that.

Classes:
We can say that they are the blueprint of user-defined methods, variables. From which we create objects or we can also say that classes are the wrapper of user-defined function and variables.

Objects:
An instance of a class is known as an object. Every object has its own properties.

I am showing an example of class and object.

class MyfirstClass:
 testvariable = "Test data"

 def myclassfunction(self):
  print("i am function inside class")

# Creating object of a class

_obj=MyfirstClass()

# Access a variable with object
print(_obj.testvariable)

# Access class function with object
_obj.myclassfunction()

################Result ##############
Test data
i am function inside class

 

When you execute the above code then the following result will come

Result:

 


Dictionaries

Dictionaries are the datatype which is used to store data in key-value pair.
E.g.

Declare  a dictionary

mydict={}

Add value to the dictionary

mydict[“key”] = “myvalue”

Key can be of any type like string, number, object, and value also can be of any type.

We can also declare a dictionary as below example.

mydict={
“Key1” : ”value1”
“Key2” : “value2”
}

 

Example:

#!/usr/bin/python
mydict={}

for i in range(5):
 mydict[i]="value" + str(i)

print(mydict)

# We can easily remove elements from dict like as
# Remove by indes

print("Element at index 2 is removed")

del mydict[2]
print(mydict)

# We can delete element by key name like below:
print("Remove element by key name")
mydict.pop(3)
print(mydict)


######result############
{0: 'value0', 1: 'value1', 2: 'value2', 3: 'value3', 4: 'value4'}
Element at index 2 is removed
{0: 'value0', 1: 'value1', 3: 'value3', 4: 'value4'}
Remove element by key name
{0: 'value0', 1: 'value1', 4: 'value4'}

 

 


Module and packages

Modules:
Modules are nothing but a piece of code of an application. In general software development practices. Software developers and engineers create many modules so that it is always easy to maintain code, and the module can be used with other software systems also.

In python, a module is a simply .py extension file which can be included in other files.

Packages:
Packages we can say is a namespace which contained multiple modules. Packages generally provide a set of functionality.

Some example of packages
re  is a package file which is used for regular expression

Some other packages like

  • Matplotlib
  • Numpy
  • Pandas
  • Mysql-connect
    Many more.

We can import a file very easily in our python code
Like

#!/usr/bin/python

import re
import os
import sys

There are lots of packages available in python. We can use them as per our need.