Python Programming BootCamp Course - All important stuff
I am writing all the techniques,tricks and examples which I felt important while studying python from Python Programming Bootcamp (2019).
It's a nice course for beginners and its free too. Special thanks to the instructor Bordeianu Adrian
1 . Comments :
1.1 Single line comment starts with hash(#). Example :
# First Program
print("Hello World")
1.2 Multi line comments start with 3 double quotes ("""). Example:print("Hello World")
"""
First line
Second line
Third line
"""
print("Hello World")
First line
Second line
Third line
"""
print("Hello World")
2. Swapping number usual vs Python trick:
Usually we use temporary variable for swapping or we use addition and subtraction but in python its just a single line statement.
# Swap using temp
a=10
b=20
temp=a
a=b
b=temp
# Addition and subtraction method
a=10
b=20
a=a+b # a=30
b=a-b # b=30-20=10
a=a-b # a=30-10=20
# In python , it is
a=10
b=20
a,b=b,a # Single line
a=10
b=20
temp=a
a=b
b=temp
# Addition and subtraction method
a=10
b=20
a=a+b # a=30
b=a-b # b=30-20=10
a=a-b # a=30-10=20
# In python , it is
a=10
b=20
a,b=b,a # Single line
3. String Operations:
3.1 String slicing : It is one of the most commonly performed method.It's in the format of string_var[ start:end:interval]
statement="I love python , Its the best language"
print(statement[3:5]) # Output : ov , 5th index is not included
print(statement[3:10:2]) # Output : oept , interval is set to 2 , so every second character is included
#for next line use \ . Example
new_string_var=statement[3:4] + statement[1:6] + statement[2:4] \
+ statement[4:7] # next line
3.2 Other useful string operation :print(statement[3:5]) # Output : ov , 5th index is not included
print(statement[3:10:2]) # Output : oept , interval is set to 2 , so every second character is included
#for next line use \ . Example
new_string_var=statement[3:4] + statement[1:6] + statement[2:4] \
+ statement[4:7] # next line
find("sub-string") : Finding a character or sub-string in a given string. It returns the position if found else it returns -1.
count("sub-string") : Counts the number of times a sub-string is repeated.
split() : splits a string to make a list of sub-strings. The parameter specifies on what basis it will be split.
replace( replace_this , with_this) : replaces the first parameter with second.
#continuing the above example:
print(statement.find("python")) # 7
print(statement.find("ipython")) #-1
print(statement.count("I")) # 1
print(statement.count("i")) # 0 : Case sensitive
print(statement.split("I")) # ['','love python,','ts the best language]
print(statement.replace("I","i")) # replaces all "I" with "i"
print(statement.find("python")) # 7
print(statement.find("ipython")) #-1
print(statement.count("I")) # 1
print(statement.count("i")) # 0 : Case sensitive
print(statement.split("I")) # ['','love python,','ts the best language]
print(statement.replace("I","i")) # replaces all "I" with "i"
4. Type casting and type() :
Type casting means changing the datatype of any variable. Its much easier in Python compared to java and c++.
# finding the datatype
a=10
b="s"
print(type(b)) # < class : str >
# typecasting ,changing int to str
string_a=str(a)
# typecasting ,changing str to int
c="10"
int_c=int(c) # remember 10 is a number so typecasting worked. if c=" abc" ,then it will show error
a=10
b="s"
print(type(b)) # < class : str >
# typecasting ,changing int to str
string_a=str(a)
# typecasting ,changing str to int
c="10"
int_c=int(c) # remember 10 is a number so typecasting worked. if c=" abc" ,then it will show error
5. List and operations on list :
List is a mutable object and the size is flexible. See the example to understand some basic list operation. Note : Sorting can be performed on both integer list and string list but not on a list which is a combination of str and int.
a=[1,2,3,4,5,6,7]
# list slicing is same as string slicing
print(a[::-2]) # output : [7,5,3,1]
print(a[::0]) # ValueError: slice step cannot be zero
# add items to list
a.append(10)
a.append("String") #[1, 2, 3, 4, 5, 6, 7, 10,'String']
# add on a give position
a.insert(0,14)
# removing element by its value
a.remove(10)
# deleting element by position
del a[1]
# delete the last element and also see its value ,but list doesn't have any method called push.
print(a.pop()) #[14, 2, 3, 4, 5, 6, 7]
# min max
print(min(a),max(a))
# sorting list
a.sort() # inc order
a.sort(reverse=True) # dec order
a.reverse() # reverse the list, it is not sorting
b = ["a","b","c","abc","ab","ac","abcd"]
#sorting acc to length of string ---important---
result=list(sorted(b,key=len)) # output : ['a', 'b', 'c', 'ab', 'ac', 'abc', 'abcd']
# list slicing is same as string slicing
print(a[::-2]) # output : [7,5,3,1]
print(a[::0]) # ValueError: slice step cannot be zero
# add items to list
a.append(10)
a.append("String") #[1, 2, 3, 4, 5, 6, 7, 10,'String']
# add on a give position
a.insert(0,14)
# removing element by its value
a.remove(10)
# deleting element by position
del a[1]
# delete the last element and also see its value ,but list doesn't have any method called push.
print(a.pop()) #[14, 2, 3, 4, 5, 6, 7]
# min max
print(min(a),max(a))
# sorting list
a.sort() # inc order
a.sort(reverse=True) # dec order
a.reverse() # reverse the list, it is not sorting
b = ["a","b","c","abc","ab","ac","abcd"]
#sorting acc to length of string ---important---
result=list(sorted(b,key=len)) # output : ['a', 'b', 'c', 'ab', 'ac', 'abc', 'abcd']
6. Dictionary, tuples and sets :
Dictionary : is a key value pair. The key must be unique but values can be same for different keys.Dictionary are mutable and doesn't preserve the order.
dic={"key1":"apple","key2":"mango",1:2}
print(dic["key1"]) # Output : apple
print(dic.keys()) # Output : dict_keys([1, 'key1', 'key2'])
print(dic.values()) # Output : dict_values([2, 'apple', 'mango'])
dic["key3"]="banana"
print(dic) # Output : {1: 2, 'key3': 'banana', 'key1': 'apple', 'key2': 'mango'}
del dic["key1"]
print(dic) # Output : {1: 2, 'key3': 'banana', 'key2': 'mango'}
Trick : Setting default values while retrieving items from dictionary.
print(dic["key1"]) # Output : apple
print(dic.keys()) # Output : dict_keys([1, 'key1', 'key2'])
print(dic.values()) # Output : dict_values([2, 'apple', 'mango'])
dic["key3"]="banana"
print(dic) # Output : {1: 2, 'key3': 'banana', 'key1': 'apple', 'key2': 'mango'}
del dic["key1"]
print(dic) # Output : {1: 2, 'key3': 'banana', 'key2': 'mango'}
# aim : to read the number of times each character is repeated.
string = "Hello , I am writing this statement for a cool trick and blah blah blah"
character={}
for char in string:
character[char]=character.get(char,0)+1
# if there is no count for a particular character from the above string then a value =0 will be initialized. Otherwise it will return null which creates error.
print(character)
Tuple : is immutable which means you can't change its value. Its useful when you want to read something quickly and don't want to change the value. string = "Hello , I am writing this statement for a cool trick and blah blah blah"
character={}
for char in string:
character[char]=character.get(char,0)+1
# if there is no count for a particular character from the above string then a value =0 will be initialized. Otherwise it will return null which creates error.
print(character)
In the example given below, although we can't change the value inside the tuple but we can change the value of the list which is inside the tuple.Cool trick.
tup=(1,2,3,4,[1,2,3])
print(tup) # (1, 2, 3, 4, [1, 2, 3])
tup[4].append(5)
print(tup) # (1, 2, 3, 4, [1, 2, 3, 5])
Set : is mutable and doesn't allow duplicates. It also does not preserve the order.
print(tup) # (1, 2, 3, 4, [1, 2, 3])
tup[4].append(5)
print(tup) # (1, 2, 3, 4, [1, 2, 3, 5])
_set={1,23,35,35,46,55,55}
print(_set) # {23, 1, 35, 46, 55}
_set.add(100) # adding element
print(_set) # {1, 35, 100, 46, 23, 55}
_set.remove(1)
print(_set) # {35, 100, 46, 23, 55}
print(_set.pop()) # 35
print(_set) # {23, 1, 35, 46, 55}
_set.add(100) # adding element
print(_set) # {1, 35, 100, 46, 23, 55}
_set.remove(1)
print(_set) # {35, 100, 46, 23, 55}
print(_set.pop()) # 35
7. Find top 3 max numbers :
Simple and efficient code to find top 3 maximum values from the list with just one loop.
l=[1,5,6,67,98,68,56,423,343]
a=b=c=min(l)
for i in l:
if(i>a):
c=b
b=a
a=i
elif(i>b):
c=b
b=i
elif(i>c):
c=i
print(a,b,c)
a=b=c=min(l)
for i in l:
if(i>a):
c=b
b=a
a=i
elif(i>b):
c=b
b=i
elif(i>c):
c=i
print(a,b,c)
8. Finding common elements in 2 lists like a pro:
There are three methods to solve this question.
l1=[1,3,4,5,6,67,98,68,56,423,343]
l2=[3,4,56,35]
# method 1 result=[]
for i in l1:
if(i in l2):
result.append(i)
print(result)
# method 2 print([i for i in l1 if i in l2])
# method 3 ---important and something new---
res=set(l1) & set(l2)
print(res)
l2=[3,4,56,35]
# method 1 result=[]
for i in l1:
if(i in l2):
result.append(i)
print(result)
# method 2 print([i for i in l1 if i in l2])
# method 3 ---important and something new---
res=set(l1) & set(l2)
print(res)
9. Removing None value (Trick)
l=[1,2,3,None,4,5,6]
new_l=[ int(i or 0) for i in l ] # i or 0 initialize a default value 0 if i cannot be typecast to int
print(new_l)
new_l=[ int(i or 0) for i in l ] # i or 0 initialize a default value 0 if i cannot be typecast to int
print(new_l)
10. Yield vs Return (Trick)
Yield temporarily suspends the execution to send the value back to the caller statement but it stores enough data to start execution again from the point where it stopped. The yield statement is mainly used when defining a generator function.Whereas return gets executed only once and anything written after return inside a function will not be executed.
def fun_1():
yield "a"
yield "b"
yield "c"
def fun_2():
return "a"
return "b"
return "c"
print(list(fun_1())) # Output ["a","b","c"]
print(list(fun_2()) # Output ["a"]
yield "a"
yield "b"
yield "c"
def fun_2():
return "a"
return "b"
return "c"
print(list(fun_1())) # Output ["a","b","c"]
print(list(fun_2()) # Output ["a"]
11. Default value in function
For default values, assign the values inside the parameter of function definition.
def fun_1(a=1,b=2):
return a+b,a-b
print(fun_1())
return a+b,a-b
print(fun_1())
12. Global values
Values which can be accessed anywhere inside the program are global variables.
a=10
def fun():
a=3
print(a)
print(globals()["a"])
fun()
def fun():
a=3
print(a)
print(globals()["a"])
fun()
13. Accessing local function inside a function using global keyword (Trick)
A function inside a function is local to the first function and cannot be accessed directly from outside. See the given example to understand it.
def fun():
def fun2():
return " my world"
return "welcome to" + fun2()
print(fun()) # welcome to my world
print(fun2()) # Nameerror :name 'fun2' is not defined
# adding global keyword , don't use () after function name and use it just above the function definition
def fun():
global fun2
def fun2():
return " my world"
return "welcome to" + fun2()
def fun2():
return " my world"
return "welcome to" + fun2()
print(fun()) # welcome to my world
print(fun2()) # Nameerror :name 'fun2' is not defined
# adding global keyword , don't use () after function name and use it just above the function definition
def fun():
global fun2
def fun2():
return " my world"
return "welcome to" + fun2()
14. Lambda instead of functions
For small functions , use lambda instead of function. See example to understand how it works.
def fun_1(a,b):
return a+b
print(fun_1(2,3)) # Output : 5
lam_1=lambda a,b: a+b
# name of lambda variable is lam_1, its parameters are a,b and definition is written after :
print(lam_1(2,3))
return a+b
print(fun_1(2,3)) # Output : 5
lam_1=lambda a,b: a+b
# name of lambda variable is lam_1, its parameters are a,b and definition is written after :
print(lam_1(2,3))
15. Map function
Map function executes a specified function for each item in iterable. Syntax : map(function,iterable)
l=[1,2,3,4,5,6]
res=list(map(lambda a: a*a,l))
print(res)
res=list(map(lambda a: a*a,l))
print(res)
16. Reduce function
Unlike map , reduce needs a two parameters function which will be working on the iterable. The syntax is reduce(function, iterable[, initial]) , initial is not compulsory to be included in the definition. Reduce function returns a single value. Also, don't forget to import it from functools.
from functools import reduce
l=[1,2,3,4,5,6]
res=reduce(lambda a,b: a+b,l) # a,b two parameters
print(res) # 21
l=[1,2,3,4,5,6]
res=reduce(lambda a,b: a+b,l) # a,b two parameters
print(res) # 21
17. Filter function
Filter function works on boolean data and remove evrything which is false
l=[1,2,3,4,5,6]
res=list(filter(lambda a: a>=5,l)) # whatever is less than equal to 5 is false, thus filtered
print(res) # [5,6]
res=list(filter(lambda a: a>=5,l)) # whatever is less than equal to 5 is false, thus filtered
print(res) # [5,6]
18. Assert statement
Assert is mainly used for debugging. An assert statement will do nothing if the condition is true but throws an AssertionError exception as soon as it becomes false.
num=4
assert num>5 , "Number has to be greater than 5"
# AssertionError: Number has to be greater than 5
assert num>5 , "Number has to be greater than 5"
# AssertionError: Number has to be greater than 5
Comments
Post a Comment