Basic questions
- what is lambda function?
in line function
x= lambda a,b: a*b
- built in data types in python
- text
- number
- list
- dict
- set
- bool
- bytes
- DICTIONARY
note : no comma at last itemsdict = {"a":10, "b":20} for x in dict #here x is key only. for x in dict.keys() #key for x in dict.values() # values for x,y in dict.items() # key values
for copy
newdict = thisdict.copy
ornewdict = dict(thisdict)
- try except
try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong")
here else will be executed if except doesnt execute.
try except finally can be used too finally will execute no matter exception occurs or not
raise can be used for throwing exception.
Examples:python raise Exception("Sorry, no numbers below zero") raise TypeError("Only integers are allowed")
- Input
myinput = input()
pythong 2.7 uses raw_input. - String format examples [useful]
txt = "The price is {} dollars for {} itmes" print(txt.format(10,5)) myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars." # 0 1 2 for index and :.2f for 2 point pafter decimal. myorder = "I have a {carname}, it is a {model}." print(myorder.format(carname = "Ford", model = "Mustang"))
- decorator function
This is basically a function inside another function. and innerfunction is returned by outer function.
*args and **kwargs can be used to transparently pass the argument
example:def calculate_time(func): def inner1(*args,**kwargs): begin = time.time() func(*args,**kwargs) end = time.time() print("total time taken: ",func.__name__,end-begin) return inner1 #usage here @calculate_time def fact(num): print(math.factorial(num)) fact(100)
chaining of decorator is also possible.
-
common mistakes
x =a or b
if a false x will be equal to b whatever it is
x= a and b
if a true x will be equal to b whatever it is
code example
copy file from one to other
with open('data') as input_file, open('result', 'w') as output_file:
for line in input_file:
output_file.write(parse(line))
args kwargs
def myFun(*args,**kwargs):
print("args: ", args)
print("kwargs: ", kwargs)
myFun('geeks','for','geeks',first="Geeks",mid="for",last="Geeks")