Home > Article > Backend Development > python bits and pieces
1. Print statement:
print 'hello world!'
print "hello world!"
print 'hello %s!'%('world')
2. Process control:
if:
a = 1;b = 2
if (a == b):
print 'a = b'
elif (a > b):
print 'a > b'
elif (a < b):
print 'a < b '
else:
print '$%$#$%'
for each :
array = [1,2,3,4]
total = 0
for i in array:
total +=i
print total
while :
while 1 > 2
pass
3. Data type:
Linked list: array=[1,2,3,4] print array result:[1,2,3,4]
Hash:
print set ( [1,2,3,4,4]) result:set([1,2,3,4])
set1 = set([1,2,3,4,5]) set2 = set([1, 2,3,4,6])
print set1-set2 result:set([5])
print set1&set2 result:set([1,2,3,4])
print set1|set2 result:set([1 ,2,3,4,5,6])
Dictionary:
dict = {}
dict['zs'] = 12
dict['ls'] = 25
dict['ww'] = 36
for key in dict.keys():
print '%s%s'%(key,dict[key]) result:ww36 ls25 zs12
4. File reading and writing:
f = file("D:worka.txt"," r")
print f.read()
f.close() #The file stream needs to be closed
with open ("D:worka.txt","r") as f:
print f.read()
with open ("D:workb.txt","w") as f:
f.write("i am ok!")