Python - Inshorts View

|
Divnesh BLOG


Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. ... Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse.
Arithmetic operators: Used for performing arithmetic operations
Operators
Description
+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulus
Relational operators: Also known as comparison operators, are used to compare values. Result of a relational expression is always either true or false.
Operators
Description
==
Equal to
< 
Less than
> 
Greater than
<=
Less than or equal to
>=
Greater than or equal to
!=
Not equal to

Logical operators are used to combine one or more relational expressions.

Operators
Description
AND
Result will be true, if both the expressions are true. If any one or both the expressions are false, the result will be false
OR
Result will be true, even if one of the expression is true. If both the expressions are false, the result will be false
NOT
If the expression is true, result will be false and vice versa

Syntax
IF:                                                                                                                                                                                    
ticket_status="Confirmed"
luggage_weight=32
weight_limit=30  #Weight limit for the airline
extra_luggage_charge=0
if(ticket_status=="Confirmed"):
    if(luggage_weight>0 and luggage_weight<=weight_limit):
        print("Check-in cleared")
    elif(luggage_weight<=(weight_limit+10)):
        extra_luggage_charge=300*(luggage_weight-weight_limit)
    else:
        extra_luggage_charge=500*(luggage_weight-weight_limit)
    if(extra_luggage_charge>0):
        print("Extra luggage charge is Rs.", extra_luggage_charge)
        print("Please make the payment to clear check-in")
else:                   
    print("Sorry, ticket is not confirmed")

                                                                                                                                                                                              
       


for:
No_Of_Passengers=5
for(Passenger_Count=1,Passenger_Count<=No_Of_Passengers,Passenger_Count=Passenger_Count+1)
     display "Immigration check done for passenger,", Passenger_Count
end-for
while:                
while(no_of_passengers>0):
    print("T -",ticket_number)
    ticket_number=ticket_number+1
    no_of_passengers=no_of_passengers-1
Datatype:
Category
Python

Numeric
int

long

complex
Numeric with decimal point
float

Alphanumeric
String

Boolean
boolean

Print statement:
Print ("Did you see \t I \n start \"here", end=" ")
print ("and I end in the same line although from a different print?")

Declaring variable:
Python
num=100
msg="Hello"
Languages like Python and JavaScript are dynamically typed whereas Go is statically typed.
Dynamic Typing is a technique in some languages where depending on how a value is used, the data type of the variable is dynamically and automatically assigned. Consider the below code in Python,
num=65 #Line 1
num="A" #Line 2
Reserved words:
Python
if, else, for, while, def, print, raise, try, except
Common Operation:
Common Operators
Python
 Arithmetic Operators
+,-,*,/, %,//
Relational Operators
==,!=,>,<,>=,<=
Assignment Operators
=,+=,-=,*=,/=,%=
Logical Operators
and,or,not

In Python, // indicates integer division.
Example: 11//2=5
BODMAS:
Precedence of an operator can be identified based on the rule - BODMAS. Brackets followed by Orders (Powers, Roots), followed by modulo, Division and Multiplication, followed by Addition and Subtraction
Python DO NOT support implicit conversions
Conversion
Python
Conversion to int
int()

num=int(“10”)
Value of num will be 10
Conversion to string
str()

num=str(10)
Value of num will be “10”








                                  
Functions:
A function is a block of code that performs a particular task. In python, functions are declared using the keyword def.                   
Default values:
Python
None
False
0
''/""
(Empty string - two single quotes/double quotes)

Get the input from user:

name=input("Enter your name:")
print(name)




List index:

Creating a list:
Creating an empty list
sample_list=[]
Creating a list with known size and known elements
sample_list1=["Mark",5,"Jack",9, "Chan",5] sample_list2=["Mark","Jack", "Chan"]
List can store both homogeneous and heterogeneous elements
Creating a list with known size and unknown elements
sample_list=[None]*5
None denotes an unknown value in Python
Length of the list
len(sample_list)
Displays the number of elements in the list

Random access of elements:
Random read

print(sample_list[2])
Random write

sample_list[2]=“James”
List is mutable i.e., the above statement will rewrite the existing value at index position 2 with “James”.

Other operations:
Adding an element to the end of the list
sample_list.append("James")
List need not have a fixed size, it can grow dynamically
Concatenating two lists
new_list=["Henry","Tim"]
sample_list+=new_list
sample_list=sample_list+new_list
sample_list+=new_list, concatenates new_list to sample_list

sample_list=sample_list+new_list, creates a new list named sample_list containing the concatenated elements from the original sample_list and new_list

Observe this difference while visualizing


Sample code:

#This is a list of lists
#Stores airline and number of flights operated by them
airline_details=[["AI",8], ["EM",10],["BA",7]]

#To get the details of Emirates (EM) airline
#Prints a list
print(airline_details[1])

#To get the number of flights operated by British Airways (BA)
#[2][1] refers to 2nd list and 1st value, inside airline_details
#Remember counting is 0 based
print(airline_details[2][1])

#To display the details of all airlines
print("Airline details as a list:")
for airline in airline_details:
    print(airline)

#To display the number of flights operated by each airline
print("No. of flights operated by each airline:")
for airline in airline_details:
        print(airline[1])   

Tuple
Like list, tuple can also store a sequence of elements but the value of the elements cannot be changed. (i.e. tuples are IMMUTABLE). Elements can be homogeneous or heterogeneous but they are READ-ONLY.
Creating a tuple
lunch_menu=("Welcome Drink","Veg Starter","Non-Veg Starter","Veg Main Course","Non-Veg Main Course","Dessert")
() are optional, a set of values separated by comma is also considered to be a tuple.

sample_tuple="A","B","C"
Although () are optional, it is a good practice to have them for readability of code.

If we need to create a tuple with a single element, then we need to include a comma as shown below:
sample_tuple=("A",)
Random Write
lunch_menu[0]=""
This will result in an error as tuple is immutable. Hence random write is not possible in tuple.
Py test:
String:
String
"AABGT6715H"
Character
A
A
B
G
T
6
7
1
5
H

String is a data type and anything enclosed in a single quote or double quote is considered to be a string. All the remaining operations are similar to lists. But like tuple, strings are also IMMUTABLE.
Each value in a string is called a character. Just like list elements, we can access the characters in a string based on its index position
Set:
A set is an unordered group of values with no duplicate entries. Set can be created by using the keyword set or by using curly braces {}. set function is used to eliminate duplicate values in a list.
Creating a set
flight_set={500,520,600,345,520,634,600,500,200,200}
Removes the duplicates from the given group of values to create the set.
Eliminating duplicates from a list
passengers_list=["George", "Annie", "Jack", "Annie", "Henry", "Helen", "Maria", "George", "Jack", "Remo"]
unique_passengers=set(passengers_list)
set function - removes the duplicates from the list and returns a set
Common elements between setA and setB
setA & setB
Creates a new set which has common elements from setA and setB
Elements that are only in setA
setA - setB
Creates a new set which has only unique elements of setA
Merges elements of setA and setB
setA | setB
Creates a new set which has all the elements of setA and setB

Dictionary:
A dictionaries can be used to store an unordered collection of key-value pairs. The key should be unique and can be of any data type. Like lists, dictionaries are mutable.
It is similar to map
Creating a dictionary
crew_details=
{ "Pilot":"Kumar",
"Co-pilot":"Raghav",
"Head-Strewardess":"Malini",
"Stewardess":"Mala" }
First element in every pair is the key and the second element is the value.
Accessing the value using key
crew_details["Pilot"]
This will return the corresponding value for the specified key
Iterating through the dictionary
for key,value in crew_details.items():
     print(key,":",value)
items function gives both key and value, which can be used in a for loop.
Functions:

Eg:

def change_number(num):
    num+=10

def change_list(num_list):
    num_list.append(20)

num_val=10
print("*********effect of pass by value*********")
print("num_val before function call:", num_val)
change_number(num_val)
print("num_val after function call:", num_val)

print("-----------------------------------------------")

val_list=[5,10,15]
print("*********effect of pass by reference*********")
print("val_list before function call:", val_list)
change_list(val_list)
print("val_list after function call:", val_list)

Ordering and default values:


Python
JavaScript
Go
Positional arguments
Yes
Yes
Yes
Keyword arguments
Yes
No
No
Default arguments
Yes
Yes
No
Variable number of arguments
Yes
Yes
Yes

Variables and Scopes:



Exception handing:
Built-in Exception
When it will be raised
Example
ZeroDivisionError
When a value is divided by zero
num_list=[]
total=0
avg=total/len(num_list)
TypeError
When we try to do an operation with incompatible data types
total=10
total+="20"
NameError
When we try to access a variable which is not defined
avg=total/10 where total is not defined
IndexError
When we try to access an index value which is out of range
num_list=[1,2,3,4]
value=num_list[4]
ValueError
When we use a valid data type for an argument of a built-in function but passes an invalid value for it
#string is a valid data type for int() but the value “A” is invalid, as "A" can't be converted into int.
value="A"
num=int(value)
Better excetion handling:

Note:
  1. Default except block is the one without any type mentioned.
  2. If an error occurs and the matching except block is found, then that is executed.
  3. If an error occurs and the matching except block is not found, it executes the default except block.
  4. If an error occurs and the matching except block is not found and if the default except block is also not found, the code crashes.
  5. The default except block, if present should be the last except block, otherwise it will result in a runtime error.
Fallback exception handling:

def calculate_sum(list_of_expenditure):
    total=0
    try:
        for expenditure in list_of_expenditure:
            total+=expenditure
        print("Total:",total)
        avg=total/no_values
        print("Average:",avg)
    except ZeroDivisionError:
        print("Divide by Zero error")
    except TypeError:
        print("Wrong data type")

try:
    list_of_values=[100,200,300,400,500]
    num_values=len(list_of_values)
    calculate_sum(list_of_values)
except NameError:
    print("Name error occured")
except:
    print("Some error occured")


Finally:
A finally block of statement is an optional part of the try-except statements. A code written inside the finally block will ALWAYS be executed.

balance=1000
amount="300Rs"

def take_card():
    print("Take the card out of ATM")
try:
    if balance>=int(amount):
        print("Withdraw")
    else:
        print("Invalid amount")
except TypeError:
    print("Type Error Occurred")
except ValueError:
    print("Value Error Occurred")
except:
    print("Some error Occurred")
finally:
    take_card()


Recursive function:
Tower of hanoi

def tower_of_hanoi(n, source,destination,temp):
    if(n==1):
        disk=source.pop(0) #Removes the element in specified position
        destination.insert(0,disk) #Inserts the given element in specified position
        return
    tower_of_hanoi(n-1, source, temp, destination)
    disk=source.pop(0)
    destination.insert(0,disk)
    tower_of_hanoi(n-1, temp, destination, source)
    return

source=["blue","green","orange"]
destination=[]
temp=[]
tower_of_hanoi(3, source, destination, temp)
print("Source:",source)
print("Destination:",destination)


Python project structure:

Consider a scenario where 2 modules have the same name but in different package and both of them have the same function ‘add’.
Flights->Manage.py->add()
Employees->Manage.py->add()
To avoid naming conflicts during import we can use one of the below techniques:

                                  

Random module:
import random
x=10
y=50
print(random.randrange(x,y))

math module:
Function
Explanation
math.ceil(x)
Smallest integer greater than or equal to x
math.floor(x)
Largest integer smaller than or equal to x
math.factorial(x)
Factorial of x
math.fabs(x)
Gives absolute value of x
Eg:

import math
num1=234.01
num2=6
num3=-27.01

print("The smallest integer greater than or equal to num1,",num1,":",math.ceil(num1))
print("The largest integer smaller than or equal to num1,",num1,":",math.floor(num1))
print("The factorial of num2,",num2,":", math.factorial(num2))
print("The absolute value of num3",num3,":",math.fabs(num3))
                                                   
output:
The smallest integer greater than or equal to num1, 234.01 : 235
The largest integer smaller than or equal to num1, 234.01 : 234
The factorial of num2, 6 : 720
The absolute value of num3 -27.01 : 27.01


String functions:
Case sensitive operations
Function
Output
Explanation
name.count("a")
2
Returns the count of a given set of characters. Returns 0 if not found
name.replace("a","A")
RAghAv
Returns a new string by replacing a set of characters with another set of characters. It does not modify the original string
name.find("a")
1
Returns the first index position of a given set of characters
name.startswith("Ra")
True
Checks if a string starts with a specific set of characters, returns true or false accordingly.
name.endswith("ha")
False
Checks if a string ends with a specific set of characters, returns true or false accordingly.
name.isdigit()
False
Checks if all the characters in the string are numbers, returns true or false accordingly.
name.upper()
RAGHAV
Converts the lowercase letters in string to uppercase
name.lower()
raghav
Converts the uppercase letters in string to lowercase
name.split("a")
['R', 'gh', 'v']
Splits string according to delimiter and returns the list of substring. Space is considered as the default delimiter.

List functions:
Function
Output
Explanation
num_list.append(60)
[10,20,30,40,50,60]
Adds an element to end of list
num_list.index(10)
0
Returns the index position of the element.
In case of multiple occurrence of the element, returns the index of the first occurrence.
Throws ValueError, if the element is not found
num_list.insert(3,60)
[10,20,30,60,40,50]
Inserts an element at a given position
num_list.pop(3)
40
Removes and returns the element at given index position from the list
num_list.remove(30)
[10,20,40,50]
Removes the first occurring element whose value is 30
num_list.sort()
[10,20,30,40,50]
Sorts the list in ascending order
num_list.reverse()
[50,40,30,20,10]
Reverses the list
Dictionary functions:
crew_details={
              "Pilot":"Kumar",
              "Co-pilot":"Raghav",
              "Head-Strewardess":"Malini",
              "Stewardess":"Mala"
              }
Function
Output
Explanation
crew_details.get("Pilot")
Kumar
Returns the value for given key. If the given key is not found, returns None
crew_details.update({"Flight Attendant":"Jane", "Co-pilot":"Henry"})
No output, dictionary will be updated
Updates the dictionary with the given key-value pairs. If a key-value pair is already existing, it will be overwritten, otherwise it will be added to the dictionary
Date Time:
We need to imports
import time
import datetime
Python has inbuilt modules called time and datetime. They are very helpful in finding details of time.
Function
Explanation
time.gmtime()
Returns the current GM time
time.localtime()
Returns the current time based on the current locality
time.strftime(t,format)
Converts t to a string as specified by the format argument and returns it.
Where t is the time returned by time.gmtime() or time.localtime(). It is optional, default value is current time as returned by time.localtime()
datetime.datetime.strptime (date_string, format)
Converts a date string in the specified format to a datetime value and returns it
datetime.date.today()
Returns the current local date
File handling:
Method
Description
open(file_path,operation)
This method is used to open the file for the specified operation. The operation can either be r,w,a for read, write and append.
close()
This method is used to close a file which is already open.
write()
This method is used to write a string to a file, if file is present. If not, it creates the file and writes the string into it.
read()
This method is used to read all the contents of a file into a string.

Eg:

try:
    flight_file=open("flight.txt","r")
    text=flight_file.read()
    print(text)
    flight_file.write(",Good Morning")
except:
    print("Error occurred")
finally:
    print("File is being closed")
    flight_file.close()
    if flight_file.closed:
        print("File is closed")
    else:
        print("File is open")


Turtle:
from turtle import *

wn = Screen()
wn.setup(500,500)
turtle = Turtle()
turtle.speed("fastest")

step = 100
def draw_square(length,angle):
    for i in range (0,step):
        for b in range (0,4):
            turtle.forward(length+i)
            turtle.right(angle+b)

  draw_square(100,90)                                          

Regular expression:
Two commonly used methods in the re module are search and sub. Search is used to find a pattern and sub is used to perform a substitution.
Here, r in front of the search pattern indicates 'raw string' where the special characters are treated as normal characters.
The output will be 'None' if the pattern is not found.
To search the pattern "Air" in the given string"Airline"

re.search(r"Air","Airline")!=None
To search the pattern having two characters in between A and l in the given string "Aopline"
re.search(r"A..l","Aopline")
To search for a digit between A and l in the given string "A2line"

re.search(r"A\dl","A2line")
To search for a number between 4 and 8 in between A and l in the given string
re.search(r"A[4-8]l","A2line")
To search for the pattern "Hell" or "Fell" in the given string "Fellow".

re.search(r"Hell|Fell","Fellow")
To check for the space after "Air" in the given string "Airline".

re.search(r"Air\s","Airline")
To check if a number is found 0 or n times after A in the given string.

re.search(r"A\d*","A2234line")

To check if a number is found 1 or n times after A in the given string.

re.search(r"A\d+","Airline")
To check if a number is found 0 or 1 times after A in the given string.

re.search(r"A\d?i","Airline")
To check if 3 digits are present after A in the given string.

re.search(r"A\d{3}i","A223irline")
To check if the given string is starting with A.

re.search(r"^A","Airline")
To check if the given string is ending with e.

re.search(r"e$","Airline")
To check whether last character is alphanumeric or not. w checks for a-z,A-Z,0-9,_ 
re.search(r"\w$","Airline%")
To replace the word "Flight" with the word "Plane".
re.sub(r"Flight",r"Plane","Flight Savana Airlines a2134")
To replace the ‘a’ to ‘A’ if it is followed by 4 numbers. () is used to group characters. Here we are grouping 4 numbers together and referring it as \1. 1 indicates the first group
re.sub(r"a(\d{4})",r"A\1","Flight Savana Airlines a2134"))
Concurrency:
  • Multitasking - unit of concurrency is the process which is like a task or job. Concurrency is achieved by interleaving execution of different tasks.
  • Multithreading - unit of concurrency is a thread which is smaller or light weight compared to a process. One process can have multiple threads. This allows for a finer level of concurrency during interleaved execution.
  • Multiprocessing - here we would have multiple CPUs executing concurrently. So processes or threads can be assigned to different available CPUs and be concurrently executed achieving concurrency
from threading import Thread #threading module should be imported
def tryit1():
    name=input("Enter your name")
    print("Hi your name is ",name)
def tryit2():
    for i in range(1,1000000):
        x=i*2.0
    print("Done")
thread1=Thread(target=tryit1)   #we are creating one thread for tryit1
thread1.start()     #we are starting that thread
thread2=Thread(target=tryit2)   #we are creating one thread for tryit2
thread2.start()     #we are starting that thread
#we are waiting for the threads to complete using join.
thread1.join()
thread2.join()
Lambda function:
Lambdas are functions without names, in other words they are anonymous functions. They take inputs and return outputs but do not have a name. They are shortcuts to create simple temporary functions.
This is equivalent to the function:
def add(x,y):
    return x+y
Input to lambda function:
g = lambda x,y:x*(x+y)
print(g(8,2))
Lambdas are different from functions in the following respects:
  1. Functions have a name, Lambdas don’t.
  2. Functions have a return keyword, Lambdas don’t.
  3. Functions are used for reusability while lambdas are used inline whenever needed.
  4. Functions can have multiple statements, Lambdas can have only an expression.
Lambdas are similar to functions in the following respects:
  1. Both can take parameters and return a value.

























Python practice online : https://repl.it/languages/python3

Featured Post

HTML cheetsheet

List: Link tgs Dropdown

Popular Post

(C) Copyright 2018, All rights resrved InShortView. Template by colorlib