The following table is the code comparison for same functionalities (mostly) in both
programs. At the end of the table, opinionative conclusion is presented.
Commenting # #
Tuples and List x =(1,2,3,4,"R") -> tuple are very Only arrays exist
efficient in terms of memory but
they cannot be appended or
edited like the array.
Tuple operations:
tuplename =(,,,,)
len(tuplename)
max(tuplename)
min(tuplename)
len(listname)
max(listname)
min(llistname)
listname.count()
To count occupied cells in the
list
listname.append(anything)
listname.remove(cellnumber)
listname.sort()
Array Operations X.append(4) -> Add to the array push(@X,word) -> similar
at the last location to append
unshift(@X,word) -> add
word in the beginning
X.insert(1, Hi) -> add to
defined location pop(@X) -> delete last cell
unshift(@X) -> delete first
X.pop(2) -> pop keyword cell
deletes from an array from
specified location $size_of_array=@array_n
ame
len(arrayname)
Splice(@X,1,2,@new_wor
d,new_word) -> splice
X.split() means replace
$glued=
join("",@array_name); ->
changing array to string
@array_from_string =
split('Arrayfromstringis',$
var_a);
@alphabetically_sorted_
array= sort(array_name);
@merged_array=(@array
1,@array2)
Dictionary Function capitals={'one':'washington DC', %capital =
'two':'Ottawa'} %capitals=("one"=>"was
hington DC", "two"=>
new={'three':'London'} "Ottawa");
print ("$capitals{'one'}");
capitals.update(new) @ranks=keys(%capitals);
print("Keys @ranks")
print (capitals)
@ranks=values(%capital
->{'one': 'washington DC', 'two': s);
'Ottawa', 'three': 'London'} print("values @ranks")
$size =values
(%capitals); -> size of
values
$capitals{three}=("New
Delhi");
delete$capitals{three};
if x%2==0: If (x%2==0)
print ("text", my_name) {
Print (even
number);
No braces are required, only
}
indent is sufficient Curved braces are required
Elseif if condition: if
{
elif condition: }
Eseif
else: {
}
Elseif
{
}
if flag==1:
print(var1, " is a prime
number")
String comparison if (A ge B)
operators: {
print ("Yes");
}
else
{
print ("No");
}
Binary operators bin(any number & any number) %b$x <- converts x
Using format specifier %b. value into binary
Binary Operations &|^ &,|,^,~ and, or, exclusive
or(xor) and 32 bit
complement
Math.e
-> 2.718281828459045
math.exp(any number)
-> for exponential
math.floor(16.94)
->16
math.sqrt(16)
-> 4
math.log(math.e)
-> 1
math.log10(2)
-> log10 to the base 2
max(,,,,,)
min(,,,,,)
round(19.923432,2)
->19.92
math.modf(12.123)
->(0.12299999999999933,
12.0)
Separates the decimal from
the whole number.
math.pow(4,2)
->16
4^2
math.hypot(5,12)
->13
math.pi
->3.141592653589793
math.degrees(1)
->57.29577951308232
Converts to radians
In array format
->'Tue Aug 15 01:08:43 2017'
@datetime=localtime();
print ("@datetime[0]");
import calendar
print(calendar.month(1965,3)) Seconds, minutes, hours,
day, month, year, week
->prints the full month calendar
in the shell
rectangle(10,20);
elsif(ord($c)>=48
User input can be taken and ord($c)<=57)
through {
push(@digits, $c)
}
else
{
push(@special,
$c)
}
}
print("Upper Case
@upper\n");
print("Lower Case
@lower\n");
print("Special
Case @special\n");
print("Digit Case
@digits\n");
}
charworks('a','b','B','D','#'
,'1','(','7');
print("Number of vowels:",
count," ")
Local variable vs Global All defined variable in the block All defined variables
variable are local by default, global are global by default,
keyword is required to define so they require
global variable keyword my to be
defined as local
Note: To know the number of arguments passed to the subroutine, the array can be
saved as $.
Arrays can also be passed to the subroutines using @ symbole.
my keyword makes the variable private to the subroutine.
sub circle
{
return
3.14*@_[0]*@_[0];
}
$area=circle(11);
print ("$area");
Remove os.remove(C:\\Users\\Rishabh\\
Documents\\new.txt)
myfile.close()
myfile.close()
myfile.close()
array_variable=myfile.readlines(
)
array_variable[2]=this 2 refers
to third line as array starts at 0th
place\n
myfile=open("C:\\Users\\Rishab
h\\Documents\\new.txt","w")
myfile.writelines(array_variable)
myfile.close
len(sys.argv) $#ARGV+1
->False/True
->True/False
Other Text Functions len(stringname)
stringname.lower()
stringname.upper()
stringname.title()
stringname.swapcase()
stringname.lstrip(anyletter)
stringname.rstrip(anyletter)
To strip(remove) any
letter(s) from the end
stringname.strip(anyletter)
To strip(remove) any
letter(s) from the beginning
and end
string.replace(anyword,with
anyword)
os.mkdir("C:\\Dr.Consolazio\\
Learnings\\Python\\newdirect
ory1")
os.chdir("C:\\Dr.Consolazio\\L
earnings\\Python\\newdirecto
ry1")
os.mkdir("NewFolderInside")
os.rmdir(NewFolderInside)
% Easy concatenations
% comma to separate characters contained in array
>>> name
{'abc': 'DEF', 'DEF': 'IJK10'}
b = "I am ham"
b.split()
['I', 'am', 'ham'] -> forming an array using the words in the sentence
L = [1,2,3,4,5]
Commands associated:
L[:] -> list all in the array
L[::2] -> alternate number array
L[1:] -> skip first cell and rest remains in array
L[1::2] -> skip first cell and write every second cell in new array
% and is a keyword
5 is not equal to 10
% not is a keyword
Continue -> when used in for loop -> spits all other values when the for loop is invalid.
Factorial
factorial =0
>>> for i in range (30):
factorial +=i
print (factorial)
% += increments and adds the same number
EASY DEBUGGING
Try and Except Keyword
try:
x = 5+ ham
except:
5+10
15
% try this syntax, if that doesnt work, execute the except code
Pass
>>> try:
5+ 5
except:
pass
%just add try before the doubtful code and pass to just outrageously move on
Raise
raise TypeError("just spitout this error")
% raise an error of your choice
Function
def fun():
print('function ran')
>>> x = fun()
function ran
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'a', 'b', 'factoria', 'factorial', 'fiboSeq', 'fun', 'i', 'j', 'primes', 'x']
Calling by reference
def addition(x,y):
z=x+y
return z
>>> addition(10,20)
30
def addition(x,y):
'"document"'
z=x+y
return z
%documenting the purpose of function while defining the function
Writing a text file
import time as t
from os import path
def createFile(dest):
'" The script creates a text file at the passed location and names file to date"'
## File name = month_Day_year
date = t.localtime(t.time())
name = "%d_%d_%d.txt" %(date[1],date[2],(date[0]%100))
if not (path.isfile(dest+name)):
f = open(dest+name,"w")
f.write("\n"*30)
f.close()
if __name__=='__main__':
destination='C:\\Dr.Consolazio\\Learnings\\Python\\'
createFile(destination)
input("Done!!")
#easy import and import aliasing. Time and date are contained in the time file.
open(filename, w or r or a) -> write or read or append the text file. By default it is set to read
the file.