You are on page 1of 5

name = raw_input("what is your name?

")
works as scanfs

print string.upper() //all capslock

~ x=18;
print "I'm" + x
error
we need to convert 18 into string first
print "I'm" + `x`
OR
x=str(18)

4**5 means 4 power 5


print("I(backslash)'m",18) //for printing two different datatypes
//backslash indicates there is no special charater
present, just print whatvever is written

~ family=['mom','dad','bro','sis','dog','cat']
family[3] //ans: 'sis'
family[1:4:2] //ans: 'dad','sis'
'Batman'[3] //ans: m

~ x= 'rasesh'
'z' in x //ans: false

~ list('rasesh') //ans: ['r','a','s','e','s','h']


x[0]='p' //ans: pasesh

list.append('x','y','z')
//append items at the end of the list
list[0:2] = []
//delete first two items
~ object.method(argument)
yourface.punch(arg)
(i.e. x.sort() /ans: ['a','e','h','r','s','s']
note: capital will be at first then lower

~ tuples is exact same thing as list with round parenthesis* ( And only difference
it can't get changed)

~ dictionary:
bio = {'dad':'james','mom':'martha','son':'robin'}
bio['dad'] //ans: 'james'
bio['son'] //ans: 'robin'
bio.has_key('sis') //ans: false

#print every key value pair


for k,v in bio.item():
print(k+v)

~ colon at the end of if condition and after else (i.e. else:)

~ gl = ['bread','milk','banana','chips']
for food in gl: (colon)
print "I want " + food
I want bread
I want milk and so on
~ in dictionary for printing key values
for names in bio:
print names, bio[names]

~ infinite loop
while 1:
x=raw_input ('Enter your name:')
x=='quit': break

~ creating function
def demo(x):
return '...

i.e.
def name(first='rasesh',last='patel'):
print "%s %s" % (first,last)
name() //ans: rasesh patel
name('bruce','wayne') //ans: bruce wayne
def demo(*name) (asterisk if length of argument is not fixed = ) //take
loop for arguments later
(two asterisk for DICTIONARY i.e. **name)

if we need to pass list as an argument


function(*list)
sets (we write sets in curly brackets)
i.e.
if 'milk' in groceries:
print("you have it")

~ object oriented programming

sometimes we need to fetch some data from different class for that we need to
define object
object.atributes(argument)
atribiutes can be methods also
i.e.
class classname:
/all data/
eyes ='blue'
def functionname(self,arg)
print arg *when we create funtion or method in class
first parameter must be 'self' after that
we can add other parameters**
object=classname()
object.eyes //ans: blue

~ to inherit from superclasses to subclasses


class childclass (parentclass1,parentclass2):
pass

~ constructor : special method that gives us output as soon as we create object!


why why need it?
i.e.
class demo:
def name(self):
print "something"
obj=demo()
obj.name() //ans: "something"

or instead of this we can build construtor

class new:
def __init__(self):
print "something"
obj.new() //ans: "something"

~ import and reload modules : import another file and its method in it
import filename
filename.method(arg)

reload(filename) *it updates the changes done in file*

~ read, write and modify lines written in file

___________________________________________________________________________________
_____________________________________

if we return value from function, we have save that in some variable

import math
use: math.sqrt()
from math import sqrt (from module import function)
use: sqrt()

best of both:
from module import *
no need to write module.function() just write function()

list - index
find index for some particular item
index_num= list.index("item")
additional
list.insert(index_num,"item")

for loop:
list = [1,3,4,2,0]
for i in list:
print list[i]
output: 3,2,0,4,1
takes i as value of list
OR
print i
output: 1,3,4,2,0

for i in range[5]
output: 1,3,4,2,0

dictionary
one key can have LIST(array) as a value

basic:
dict_name.remove('key_name')
advanced:
if key is list
dict_name['key_name'].remove('value')
dict_name['key_name'].sort()

advnaced: print all key and value pair without loop

dict_name.item() //print both key-value pair tuple


dict_name.keys()
dict_name.values()

some other:
c = ['C' for x in range(5) if x < 3]
print c

list = range(101) //list = [0,1,2,...,100]


reverse_list = list[::-10] //reverse_list = [100,90,80,...,10,0]

Lambda function(anonymous):
list = range(1:101) or list = [x for x%3==0]
print filter(lambda x: x%3==0,list) //FILTER used in
this, filters out condition we put in

~ Class

we can make different classes and fetch data by calling them.


in order to make this possible we need to make object
so it is called object oriented programming.
i.e.

class classname(object): //first letter of classname will be capital


def __init__(self): // __init__ is root file, atleast self
parameter must be present
OR
def __init__(self, name):
self.name = name //python takes self.name as its own name whatever we
pass in as parameter

extra def description():


print self.name
i.e. dog = classname("name")
dog.description()

here dog is called instance of classname and this is how we call description method
for dog

~inheritane in class

class C1(object):
def __init__(self):
pass
def function1(self):
pass
class C2(C1):
def funtion2(self):
pass
instance = C2(parameter)
it can access C2.funtion1() as well as C2.funtion2()

*here is the twist


(1) see if we calculate something in parent class
and
(2) and we calculate same thing for child class
but if there is a condition, in child's class and we need to perform if that
condition is satisfied whatever calculation is there in parent class
super(parentclass, self).method(args)

i.e.
class CEO(object):
def cal(self, hours):
self.hours = hours
return x = 20 * hours
clas Employee(CEO):
def cal(self, hours):
self.hours = hours
return x = 10 * hours
//if some condtion
def cal2(self):
return super(CEO, self).cal(hours) //multiplied by 20 only

~for input and output of file

f = open("output.txt", "w") // w for write, r for read and r+ for


read and write and a for append

for item in my_list:


f.write(str(item) + "\n")

f.close() // closing is necessary as not to let the data


stucked in temporary memory

~ for python to close the program

with open("text.txt", "mode") as my_file:


my_file.write("yep") or print my_file.read()

You might also like