Operators
|
Description
|
+
|
Addition
|
-
|
Subtraction
|
*
|
Multiplication
|
/
|
Division
|
%
|
Modulus
|
Operators
|
Description
|
==
|
Equal to
|
<
|
Less than
|
>
|
Greater than
|
<=
|
Less than or equal to
|
>=
|
Greater than or
equal to
|
!=
|
Not equal to
|
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
|
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")
|
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(no_of_passengers>0):
print("T -",ticket_number)
ticket_number=ticket_number+1
no_of_passengers=no_of_passengers-1
|
Category
|
Python
|
|
Numeric
|
int
|
|
long
|
||
complex
|
||
Numeric with
decimal point
|
float
|
|
Alphanumeric
|
String
|
|
Boolean
|
boolean
|
Print ("Did you see \t I \n
start \"here", end=" ")
print ("and I end in the
same line although from a different print?")
|
Python
|
num=100
msg="Hello" |
Python
|
if, else, for, while, def, print,
raise, try, except
|
Common
Operators
|
Python
|
Arithmetic Operators
|
+,-,*,/, %,//
|
Relational
Operators
|
==,!=,>,<,>=,<=
|
Assignment
Operators
|
=,+=,-=,*=,/=,%=
|
Logical Operators
|
and,or,not
|
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” |
Python
|
None
|
False
|
0
|
''/""
(Empty string - two single quotes/double quotes) |
name=input("Enter
your name:")
print(name)
|
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 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”.
|
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 |
#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])
|
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.
|
String
|
"AABGT6715H"
|
|||||||||
Character
|
A
|
A
|
B
|
G
|
T
|
6
|
7
|
1
|
5
|
H
|
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
|
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.
|
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)
|
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
|
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) |
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")
|
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()
|
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)
|
import random
x=10
y=50
print(random.randrange(x,y))
|
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
|
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
|
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.
|
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
|
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
|
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
|
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.
|
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")
|
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)
|
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"))
|
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()
|
g = lambda x,y:x*(x+y)
print(g(8,2))
|
List: Link tgs Dropdown