Skip to content

Instantly share code, notes, and snippets.

@vsathyak
Last active October 6, 2021 02:03
Show Gist options
  • Save vsathyak/d5cfbe5119ca2ec5af29bcd7d6a8f896 to your computer and use it in GitHub Desktop.
Save vsathyak/d5cfbe5119ca2ec5af29bcd7d6a8f896 to your computer and use it in GitHub Desktop.
Python Bootcamp From Zero to Hero in Python
Course Materials
----------------
Github Link for Materials : https://github.com/Pierian-Data/Complete-Python-3-Bootcamp
Free Python Interpreter
-----------------------
>> jupyter.org/try
>> Google collab online notebooks
>> repl.it
>> Google search "Python Onine Interpreter"
############################################################################################################################
Python Object and Data Structure Basics : Introduction to Python Data Types
***************************************************************************
NAME TYPE
---- ----
Integers int Eg. 1, 200
Floating point float Eg. 2.3, 100.0
Strings str Eg. "hello", 'Sammy', "2000"
List list Eg. [10,"hello", 200.3]
Dictionaries dict Eg. {"name":"vsk","age":"33"}
Tuples tup Eg. (10,"hello",200.3)
Sets set Eg. {"a","b"}
Booleans bool Eg. True or False
Python Numbers : Arithmetic Operators
-------------------------------------
Addition : +
Subtraction : -
Division : /
Multiplication : *
Floor Division : //
Modulo : %
Power : **
Variable Assignments
---------------------
The names you use when creating these labels need to follow a few rules:
>> Names can not start with a number.
>> There can be no spaces in the name, use _ instead.
>> Can't use any of these symbols :'",<>/?|\()!@#$%^&*~-+
>> It's considered best practice (PEP8) that names are lowercase.
>> Avoid using the characters 'l' (lowercase letter el), 'O' (uppercase letter oh),
or 'I' (uppercase letter eye) as single character variable names.
>> Avoid using words that have special meaning in Python like "list" and "str"
Note. Dynamic Typing is allowed in Python
Eg. my_dog = 3
my_dog = ["Sammy", "Frankie"]
Here initially my_dog is of type integer and later become a list.
Checking datatype
-----------------
>> a = 10
>> type(a)
int
############################################################################################################################
Introduction to Strings : Ordered sequence of characters.
-----------------------
>> len() to check the length of a string!
eg. len('Hello World')
11
Note. Python's built-in len() function counts all of the characters in the string, including spaces and punctuation.
Print
-----
>> s = "Hello World"
>> print(s) --> Hello World
>> s = "Hello \tWorld"
>> print(s) --> Hello World
>> s = "Hello \nWorld"
>> print(s) --> Hello
World
String Indexing
---------------
>> var[start:stop:step]
>> s = 'Hello World'
>> print(s) ---> Hello World
>> s[0] ---> 'H'
>> s[-1] ---> 'd'
>> s[0] ---> 'H'
>> s[1:] ---> 'ello World'
>> s[:3] ---> 'Hel'
>> s[:] ---> 'Hello World'
>> s[-1] ---> 'd' # Last letter (one index behind 0 so it loops back around)
>> s[:-1] ---> 'Hello Worl' # Grab everything but the last letter
>> s[::2] ---> 'HloWrd' # Grab everything, but go in step sizes of 2
>> s[::-1] ---> 'dlroW olleH' # Reverse a string
String Concatination
--------------------
>> s = 'Hello World'
>> s + 'concatenate me'
>> print(s)
Hello World concatenate me
>> letter = 'z'
>> letter*10
zzzzzzzzzz
Inbuilt string methods
----------------------
>> s.upper() --> HELLO WORLD CONCATENATE ME
>> s.lower() --> hello world concatenate me
>> s.split() --> ['Hello', 'World', 'concatenate', 'me']
>> s.split('W') --> ['Hello ', 'orld concatenate me'] , will do the split on 'W'
Print Formatting using format()
--------------------------------
format() to add formatted objects to printed string statements
>> print('This is a string {}'.format('INSERTED'))
This is a string INSERTED
>> print('The {} {} {}'.format('fox','brown','quick')
The fox brown quick
>> print('The {2} {1} {0}'.format('fox','brown','quick')
The quick brown fox
>> print('The {q} {b} {f}'.format(f='fox', b='brown', q='quick')
The quick brown fox
>> result = 100/777
print(result) ---> 0.12870
>> print("The result was {r}".format(r=result))
Print Formatting using f-strings()
----------------------------------
>> name = "Jose"
>> age = 3
>> print(f'{name} is {age} years old.')
Sam is 3 years old.
Join
----
The join() method takes all items in an iterable and joins them into one string.
>> string.join(iterable)
Eg.
>> myDict = {"name": "John", "country": "Norway"}
mySeparator = "TEST"
x = mySeparator.join(myDict)
print(x) ---> nameTESTcountry
############################################################################################################################
Lists in Python : Ordered sequence of objects(mutable).
***************
Eg.
>> my_list = [1,2,3]
>> my_list = ['A string',23,100.232,'o']
>> len(my_list) --> 4
Indexing and Slicing
--------------------
>> my_list = ['one','two','three',4,5]
>> my_list[0] --> one
>> my_list[1:] --> ['two', 'three', 4, 5]
>> my_list[:3] --> ['one','two','three']
Concatination
-------------
>> my_list + ['new item']
>> ['one', 'two', 'three', 4, 5, 'new item']
Note: This doesn't actually change the original list!
You would have to reassign the list to make the change permanent.
-----------------------------------------------------------------
>> my_list = my_list + ['add new item permanently']
>> print(my_list)
['one', 'two', 'three', 4, 5, 'add new item permanently']
We can also use the * for a duplication method similar to strings:
Basic List Methods
------------------
append()
--------
Used to permanently add an item to the end of a list
>> list1 = [1,2,3]
>> list1.append(4)
>> print(list1)
[1, 2, 3, 4]
pop()
-----
Used to delete an item from the list. By default pop takes off last index, but you can also specify which index to pop off.
>> popped_item = list1.pop()
>> print(popped_item) --> 4
>> print(list1) --> [1, 2, 3]
Remove from specific location in list
-------------------------------------
>> new_list = ['one', 'two', 'three', 'four']
>> new_list.pop(1)
>> print(new_list) --> ['one', 'three', 'four']
Remove last element from list
-----------------------------
>> new_list = ['one', 'two', 'three', 'four', 'five', 'six']
>> new_list.pop(-1)
>> print(new_list) --> ['one', 'two', 'three', 'four', 'five']
>> new_list.pop(-3)
>> print(new_list) --> ['one', 'two', 'four', 'five']
Sort a list
-----------
>> new_list = [10, 1, 8, 5, 2, 6, 4, 3, 9, 7]
>> new_list.sort() --> It doesnt return anything. But when the new list get printed, you will get sorted o/p
>> print(new_list) --> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Reverse a list
--------------
>> new_list.reverse() --> Sort in reverse order.
>> print(new_list) --> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
############################################################################################################################
Dictionaries in Python : Key value pairing that is unordered.
**********************
Syntax
------
>> my_dict = {'key1':'value1','key2':'value2'}
>> my_dict['key2'] --> value2
Dictionaries hold different data type
-------------------------------------
>> my_dict = {'key1':123,'key2':{'name': 'vsk'},'key3':['item0','item1','item2']}
>> my_dict['key3'][0] ---> item0
>> my_dict['key2']['name'] ---> vsk
Create a new dictionary
-----------------------
>> d = {}
>> d['animal'] = 'Dog'
>> d['answer'] = 42
>> print(d)
{'animal': 'Dog', 'answer': 42}
>> d = {'name': 'Vysakh', 'age': 33, 'place': 'USA'}
>> print(d.keys()) ---> dict_keys(['name', 'age', 'place'])
>> print(d.values()) ---> dict_values(['Vysakh', 33, 'USA'])
>> print(d.items()) ---> dict_items([('name', 'Vysakh'), ('age', 33), ('place', 'USA')])
############################################################################################################################
Tuples
******
Tuples are ordered sequence of object and are are immutable. means once an element is inside a tuple, it cannot be reassigned.
Builtin methods of tuple
------------------------
1. count : To count the no: of occurance of an element in the tuple
>> t = (1, 1, 2, 4, 3, 2, 1)
>> t.count('1') ---> 3
2. index : Return the very first index position of that element in the tuple.
>> index(1) ---> 0
t = ('one', 3.5, 2, 3.5)
print('Tuple : {}'.format(t)) ---> Tuple : ('one', 3.5, 2, 3.5)
print('Length of tuple : {}'.format(len(t))) ---> Length of tuple : 4
print('Tuple t index 0 : {}'.format(t[0])) ---> Tuple t index 0 : one
print('Tuple t index -1 : {}'.format(t[-1])) ---> Tuple t index -1 : 3.5
print('Count of 3.5 in Tuple t : {}'.format(t.count(3.5) )) ---> Count of 3.5 in Tuple t : 2
Why bother using tuples when they have fewer available methods?" To be honest, tuples are not used as often as lists in
programming, but are used when immutability is necessary. If in your program you are passing around an object and need to
make sure it does not get changed, then a tuple becomes your solution. It provides a convenient source of data integrity.
############################################################################################################################
Sets in Python : Unordered collection of unique elements. So duplicate elements are not allowed
**************
Create a set myset
------------------
>> myset = set()
Add value to myset
------------------
>> myset.add(1)
>> myset.add(2)
>> print(myset) ---> {1, 2}
# Create a list with repeats
>> list1 = [1,1,2,2,3,4,5,6,1,1]
# Cast as set to get unique values
>> set(list1) ----> {1, 2, 3, 4, 5, 6}
############################################################################################################################
Booleans in Python
******************
>> Conveys only True or False
>> type(True) or type(False) ---> bool
>> 1 == 1 ---> True
############################################################################################################################
None in Python
***************
>> Used as a placeholder
############################################################################################################################
I/O with Basec Files in Python
******************************
Open a file
-----------
>> myfile = open('filename.txt')
open('C:\\Users\\Username\\Folders\\test.txt') ==> Windows
open('/Users/YourUserName/Folder/myfile.txt') ==> Mac/Linux
Read file content
-----------------
>> myfile.read() --> read the content of the file
>> Note : Return the content as a string.
Read again
----------
>> my_file.read() --> returns '' This happens because you can imagine the reading "cursor" is at the end
of the file after having read it. So there is nothing left to read.
Set the read index to start of file
-----------------------------------
>> my_file.seek(0)
Return list of lines
--------------------
>> my_file.readlines()
>> Note : Return the content as a list of lines.
Close file
----------
my_file.close()
Eg.
my_file = open('vsk_file.txt') ==> open the file.
print(my_file.read()) ==> Howdy, This is VSK. Hope you doing good.
my_file.seek(0)
print(my_file.readlines()) ==> ['Howdy, This is VSK. Hope you doing good.'] --> Return content as a list of lines
my_file.close()
Writing to a File
*****************
By default, the open() function will only allow us to read the file. We need to pass the argument 'w' to write over the file.
>> my_file = open('test.txt','w+')
>> my_file.write('This is a new line')
>> my_file.seek(0)
>> my_file.read()
>> myfile.close()
Eg.
>> my_file = open('vsk_file.txt', 'w+') ---> open in w or w+ delete the content of original file
>> my_file.write('Adding content to the file.') ---> Adding content
>> my_file.seek(0) ---> Set curson to beginning of file
>> print(my_file.read()) ---> Eead content.
Appending to a File
*******************
Passing the argument 'a' opens the file and puts the pointer at the end, so anything written is appended. Like 'w+', 'a+'
lets us read and write to a file. If the file does not exist, one will be created.
>> my_file = open('test.txt','a+')
>> my_file.write('\nThis is text being appended to test.txt')
>> my_file.write('\nAnd another line here.')
>> my_file.seek(0)
>> print(my_file.read())
>> my_file.close()
Modes
-----
r : read only
w : write only (overwrite file or create new)
a : append only
r+ : allows read n write
w+ : allows writing and reading (overwrite existing file to create a new file)
Iterating through a File
************************
for readline in open('test.txt'):
print(readline)
############################################################################################################################
Python Comparison Operators
***************************
Comparison Operators in Python
------------------------------
1. ==
2. !=
3. >
4. <
5. >=
6. <=
Chained Comparison Operators
----------------------------
Chaining can be done using 'and', 'or' & 'not' operator.
>> 1<2 and 2<3 --> True
>> 1==2 or 2<3 --> True
>> not 1==1 --> False
############################################################################################################################
Python Statements
*****************
If Elif and Else statement in Python
------------------------------------
Syntax of if else statement:
----------------------------
>> if some_condition:
# execute some code
else:
# do something else
Eg.
>> x = False
if x:
print('x was True!')
else:
print('I will be printed in any case where x is not true')
Syntax of if elif else statement:
---------------------------------
>> if some_condition:
# execute some code
elif some_other_condition:
# do something different
else:
# do something else
Eg.
>> loc = 'Bank'
if loc == 'Auto Shop':
print('Welcome to the Auto Shop!')
elif loc == 'Bank':
print('Welcome to the bank!')
else:
print('Where are you?')
############################################################################################################################
For Loops
*********
Eg 1. List :
>> list1 = [1,2,3,4,5,6,7,8,9,10]
>> for item in list1:
print(item)
Eg 2. String
>> for letter in 'This is a string.':
>> print(letter)
Eg 3. Tuple
>> up = (1,2,3,4,5)
>> for t in tup:
print(t)
Eg. 4 Dictionary
>> d = {'k1':1,'k2':2,'k3':3}
>> for key,value in d.items(): ---> if you need to iterate through just keys, use d.keys() and for value, use d.values()
print(key)
print(value) ---> O/P : k1 1 k2 2 k3 3
Eg. 5 Dictionary
>> d = {'k1':1,'k2':2,'k3':3}
>> for item in d:
print(item) --> O/P : k1 k2 k3
############################################################################################################################
While Loops
***********
Syntax:
------
>> while test:
code statements
OR
>> while test:
code statements
else:
final code statements
Eg 1.
>> x = 0
>> while x < 10:
print('x is currently: ',x)
print(' x is still less than 10, adding 1 to x')
x+=1
Eg 2.
>> x = 0
>> while x < 10:
print('x is currently: ',x)
print(' x is still less than 10, adding 1 to x')
x+=1
else:
print('All Done')
break, continue, pass
---------------------
break : Breaks out of the current closest enclosing loop. --> Breaks the loop
continue : Goes to the top of the closest enclosing loop. --> Go to the top of the loop without executing the rest
pass : Does nothing at all.
eg for continue.
>> mystring = 'Sammy'
for letter in mystring:
if letter == 'a':
continue
print(letter)
O/P : Smmy
eg for break.
>> mystring = 'Sammy'
for letter in mystring:
if letter == 'a':
break
print(letter)
O/P : S
############################################################################################################################
Useful Operators
****************
range : The range function allows you to quickly generate a list of integers
*****
Syntax : range(start, stop, step_size)
>> for item in range(10):
print(item) --> 0 1 2 3 4 5 6 7 8 9
>> for item in range(3,10):
print(item) --> 3 4 5 6 7 8 9
>> for item in range(3,10,3):
print(item) --> 3 6 9
Casting to list
***************
>> list(range(0,11,2)) --> [0, 2, 4, 6, 8, 10]
enumerate :
*********
>> index_count = 0
for letter in 'abcde':
print("At index {} the letter is {}".format(index_count,letter))
index_count += 1
OR
write this using enumerate as follows: 0 a
>> word = 'abcde' 1 b
for index,letter in enumerate(word): ---> O/P : 2 c
print('{}\t{}'.format(index,letter)) 3 d
4 e
zip : zip is used to merge to list and return tuple
***
>> names = ['Jenny', 'Alexus', 'Sam', 'Grace']
>> dogs_names = ['Elphonse', 'Dr. Doggy DDS', 'Carter', 'Ralph']
>> names_and_dogs_names = zip(names, dogs_names)
>> list_of_names_and_dogs_names = list(names_and_dogs_names)
>> print(list_of_names_and_dogs_names)
O/P : [('Jenny', 'Elphonse'), ('Alexus', 'Dr. Doggy DDS'), ('Sam', 'Carter'), ('Grace', 'Ralph')]
in : check if an object is in a list
**
>> 'x' in ['x','y','z'] --> True
>> d = {'mykey' : 345}
345 in d.keys() --> False
not in :
******
>> 'x' not in ['x','y','z'] --> False
min and max :
***********
>> mylist = [10,20,30,40,100]
>> min(mylist) --> 10
>> max(mylist) --> 100
input : to read input and always accept the input as a string
*****
>> result = input('Enter something : '
Enter something : hello
print(result) --> hello
############################################################################################################################
List Comprehension
******************
List Comprehensions
--------------------
Eg. 1
>> words = ["@coolguy35", "#nofilter", "@kewldawg54", "reply", "timestamp", "@matchamom", "follow", "#updog"]
>> usernames = [word for word in words if word[0] == '@'] ==> Eg: for list comprehension
>> print(usernames)
["@coolguy35", "@kewldawg54", "@matchamom"]
Eg: 2
We want to add 100 to each value. We can accomplish this goal in one line:
>> my_upvotes = [192, 34, 22, 175, 75, 101, 97]
>> updated_upvotes = [item + 100 for item in my_upvotes]
Eg. 3
Square numbers in range and turn into list
>> lst = [x**2 for x in range(0,11)]
>> print(lst)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Eg. 4
Check for even numbers in a range
>> lst = [x for x in range(11) if x % 2 == 0]
>> print(lst)
[0, 2, 4, 6, 8, 10]
Note if you are using if ... else condition instead of just if, then there is a slight difference in the syntax
Eg 5.
If even number, print it else print ODD
>> result = [x if x%2 == 0 else "ODD" for x in range(0,11)]
print(result)
[0, 'ODD', 2, 'ODD', 4, 'ODD', 6, 'ODD', 8, 'ODD', 10]
Here if else condition written before for loop. But if you are using just if condition only, then it comes after for loop.
############################################################################################################################
Methods and Functions
*********************
Methods used with list
----------------------
. append() Adds an element at the end of the list
>> fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits) --> ['apple', 'banana', 'cherry', 'orange']
. clear() Removes all the elements from the list
>> fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits) --> []
. copy() Returns a copy of the list
>> fruits = ["apple", "banana", "cherry"]
x = fruits.copy()
print(x) --> ["apple", "banana", "cherry"]
. count() Returns will count the number of occurrences of an element in a list
>> fruits = ["apple", "banana", "cherry"]
x = fruits.count('cherry')
print(x) --> 1
. extend() Add the elements of a list (or any iterable), to the end of the current list
>> fruits = ["apple", "banana", "cherry"]
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits) --> ['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']
. index() Returns the index of the first element with the specified value
>> fruits = ["apple", "banana", "cherry"]
x = fruits.index('cherry')
print(x) --> 2
. insert() Adds an element at the specified position
>> fruits = ["apple", "banana", "cherry"]
fruits.insert(1,'orange')
print(x) --> ['apple', 'orange', 'banana', 'cherry']
. pop() By default it removes the last element in the list or you could removes the element at the specified position
>> fruits = ["apple", "banana", "cherry"]
fruits.pop(1)
print(fruits) --> ['apple', 'cherry']
fruits.pop()
print(fruits) --> ['apple']
. remove() Removes the first item with the specified value
>> fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits) --> ['apple', 'cherry']
. reverse() Reverses the order of the list
>> fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits) --> ['cherry', 'banana', 'apple']
. sort() Sorts the list
>> cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars) --> ['BMW', 'Ford', 'Volvo']
############################################################################################################################
Introduction to Functions
*************************
def Keyword
-----------
Function definition syntax
--------------------------
>> def say_hello_to_world():
'''
Docstring explains the function
'''
print('Hello World')
Function call
-------------
>> say_hello_to_world()
Hello World
Function with parameter & return value syntax
---------------------------------------------
>> def sum_of_2_nos(no1, no2):
sum = no1+ no2
return sum
Function call
-------------
>> result = sum_of_2_nos(5, 10)
print(result)
15
Function with parameter having default value
---------------------------------------------
>> def say_hello(name='vsk'):
print('Hello '+name)
Function call
-------------
>> say_hello(tom)
Hello tom --> if i call function with out any value then it uses the default value for the param
############################################################################################################################
*args and **kwargs in Python
****************************
*args
-----
When a function parameter starts with an asterisk, it allows for an arbitrary number of arguments, and the function takes
them in as a tuple of values. Rewriting the above function:
>> def myfunc(*args):
return sum(args)*.05
>> myfunc(40,60,20) --> 6.0
**kwargs
--------
Similarly, Python offers a way to handle arbitrary numbers of keyworded arguments. Instead of creating a tuple of values,
**kwargs builds a dictionary of key/value pairs
>> def myfunc(**kwargs):
print(kwargs)
if 'fruit' in kwargs:
print("My favorite fruit is {}.format(kwargs['fruit'])")
else:
print("I don't like fruit")
>> myfunc(fruit='pineapple', veggie='lettuce')
O/P:
----
{'fruit':'apple', 'veggie': 'lettuce'}
My favourite fruit is pineapple
*args and **kwargs combined
---------------------------
You can pass *args and **kwargs into the same function, but *args have to appear before **kwargs
>> def myfunc(*args, **kwargs):
print(args)
print(kwargs)
print('I would like {} {}.'.format(args[0], kwargs['food']))
>> myfunc(10, 20, 30, fruit='orange', food='eggs', animal=dog')
O/P :
----
(10, 20, 30) --> args always tuple
{fruit='orange', food='eggs', animal=dog'} --> kwargs always dictionary
I would like 10 eggs.
############################################################################################################################
Lambda Expressions, Map, and Filter Functions
*********************************************
map()
----
map() function returns a map object
Syntax : map(function, iterable_object)
Function definition
-------------------
>> def square(num):
return num**2
List
----
>> >> my_num = [1, 2, 3, 4, 5]
Using map
---------
>> list(map(square,my_num)) --- O/P ---> [1, 4, 9, 16, 25]
OR
Using for loop
--------------
>> for item in map(square, my_num): --- O/P ---> 1 4 9 16 25
print(item)
filter()
--------
The filter() filters the given sequence with the help of a function that tests each element in the sequence to be true or not
Syntax : filter(function, iterable object)
>> nums = [1,2,3,4,5,6]
>> def check_even(num):
return num % 2 == 0
>> for item in filter(check_even, nums): --- O/P ---> 2 4 6
print(n)
lambda expression
-----------------
lambda expressions allow us to create "anonymous" functions. This basically means we can quickly make ad-hoc functions
without needing to properly define a function using def.
>> square = lambda num: num ** 2
>> square(2) ---O/P---> 4
You can use these lambdas with map n filters.
So you can write the above map as follows.
>> list(map(lammbda num:num**2, my_num)) --- O/P ---> [1, 4, 9, 16, 25, 36]
So you can write the above filter as follows.
>> list(filter(lambda num:num%2 == 0, my_num)) --- O/P ---> [2, 4, 6]
>> names = ['Andy', 'Eve', 'Sally']
>> list(map(lambda x:x[0], names)) ---> ['A', 'E', 'S']
############################################################################################################################
Object Oriented Programming
***************************
Class
-----
Syntax:
-------
>> Class NameOfClass():
# Class Object Attribute
attribute_name = 'value'
def __init__(self, param1, param2):
self.param1 = param1
self.param2 = param2
def some_method(self):
# perform some action
print(self.param1)
Eg:
---
>> class Dog():
# Class bject Attribute
# Same for any instance of a class
# Called using class name or instance name
species = mammal
def __init__(self, breed, name, spots):
# Attributes
# We take in arguments
# Assign it using self.attribute_name
self.breed = breed
self.name = name
# Expect Boolean : True/False
self.spots = spots
# OPERATIONS/Actions ---> Methods
def bark(self):
print('WOOF! My name is {}').format(self.name))
>> my_dog = Dog(breed='Lab', name='Frankie', spots=False)
>> my_dog.species --> mammal
>> my_dog.breed --> Lab
>> my_dog.name --> Frankie
>> my_dog.spots --> False
>> my_dog.bark() --> WOOF! My name is Frankie
Eg. 2
-----
>> class Circle:
pi = 3.14
# Circle gets instantiated with a radius (default is 1)
def __init__(self, radius=1):
self.radius = radius
self.area = radius * radius * Circle.pi
# Method for getting Circumference
def getCircumference(self):
return self.radius * self.pi * 2
>> c = Circle()
print('Radius is: ',c.radius)
print('Area is: ',c.area)
print('Circumference is: ',c.getCircumference())
Radius is: 1
Area is: 3.14
Circumference is: 6.28
############################################################################################################################
Inheritence and Polymorphism
----------------------------
Inheritance is a way to form new classes using classes that have already been defined. The newly formed classes are called
derived classes, the classes that we derive from are called base classes
>> class Animal:
def __init__(self):
print("Animal created")
def whoAmI(self):
print("Animal")
def eat(self):
print("Eating")
class Dog(Animal):
def __init__(self):
Animal.__init__(self)
print("Dog created")
def whoAmI(self):
print("Dog")
def bark(self):
print("Woof!")
>> d = Dog()
Animal created
Dog created
>> d.whoAmI() ---> Dog
>> d.eat() ---> Eating
>> d.bark() ---> Woof!
Polymorphism
------------
>> class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return self.name+' says Woof!'
class Cat:
def __init__(self, name):
self.name = name
def speak(self):
return self.name+' says Meow!'
niko = Dog('Niko')
felix = Cat('Felix')
print(niko.speak())
print(felix.speak())
O/P
---
>> Niko says Woof!
Felix says Meow!
>> Here we have a Dog class and a Cat class, and each has a .speak() method.
When called, each object's .speak() method returns a result unique to the object.
There a few different ways to demonstrate polymorphism. First, with a for loop:
>> for pet in [niko,felix]:
print(pet.speak())
O/P
---
>> Niko says Woof!
Felix says Meow!
Another is with functions:
-------------------------
>> def pet_speak(pet):
print(pet.speak())
>> pet_speak(niko)
pet_speak(felix)
O/P
---
Niko says Woof!
Felix says Meow!
In both cases we were able to pass in different object types, and we obtained object-specific results from the same
mechanism.
A more common practice is to use abstract classes and inheritance. An abstract class is one that never expects to be instantiated. For example, we will never have an Animal object, only Dog and Cat objects, although Dogs and Cats are derived from Animals:
>> class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def speak(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal):
def speak(self):
return self.name+' says Woof!'
class Cat(Animal):
def speak(self):
return self.name+' says Meow!'
fido = Dog('Fido')
isis = Cat('Isis')
print(fido.speak()) --> Fido says Woof!
print(isis.speak()) --> Isis says Meow!
############################################################################################################################
Special Methods
***************
Classes in Python can implement certain operations with special method names. These methods are not actually called directly
but by Python specific language syntax
>> class Book:
def __init__(self, title, author, pages):
print("A book is created")
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return "Title: %s, author: %s, pages: %s" %(self.title, self.author, self.pages)
def __len__(self):
return self.pages
def __del__(self):
print("A book is destroyed")
>> book = Book("Python Rocks!", "Jose Portilla", 159) --> o/p : A book is created
#Special Methods
>> print(book) --> o/p : Title: Python Rocks!, author: Jose Portilla, pages: 159
>> print(len(book)) --> o/p : 159
>> del book --> o/p : A book is destroyed
>> The __init__(), __str__(), __len__() and __del__() methods
>> These special methods are defined by their use of underscores.
>> They allow us to use Python specific functions on objects created through our class.
############################################################################################################################
Modules and Packages
********************
Packages are collection of modules and modules are nothing but .py scripts.
Install packages
----------------
>> pip install requests
>> pip insall colorama
Using modules
-------------
>> from coloroma import init
>> init()
>> from coloroma import Fore
>> print(Fore.RED + "some red text")
some red text ---> displayed in red
Watch __name__ and __main from Udemy.
Also refer : https://www.freecodecamp.org/news/if-name-main-python-example/
############################################################################################################################
Errors and Exception Handling
*****************************
Eg.
>> try:
result 10 + 10
except:
print("Hey it looks like you aren't adding correctly!")
else:
print("Add went well")
print(result)
>> try:
f = open('testfile', 'r')
f.write('Write a test line')
except TypeError:
print('There is a type error.') --- O/P ---> There is an OS error
except OSError: I always run
print('There is an OS error')
finally:
print('I always run')
>> def askint():
try:
val = int(input("Please enter an integer: "))
except:
print("Looks like you did not enter an integer!")
finally:
print("Finally, I executed!")
print(val)
>> askint() askint()
Please enter an integer: vsk Please enter an integer: 20
Looks like you did not enter an integer! Finally, I executed!
Finally, I executed!
>> def askint():
while True:
try:
val = int(input("Please enter an integer: "))
except:
print("Looks like you did not enter an integer!")
continue
else:
print("Yep that's an integer!")
print(val)
break
finally:
print("Finally, I executed!")
>> askint()
Please enter an integer: 20
Yep that's an integer!
20
Finally, I executed!
############################################################################################################################
Pylint
******
There are dozens of good testing libraries out there. Most are third-party packages that require an install, such as:
. pylint
. pyflakes
. pep8
Better way to test ur code is to write tests that send sample data to ur program & compare what's returned to a desired outcome.
Two such tools are available from the standard library:
. unittest
. doctest
>> pip install pylint
>> pylint filename.py -r y
Running tests with the Unittest Library
***************************************
Watch the video
############################################################################################################################
Python Decorators
*****************
Nothing but annotations.
Any doubts, watch the vide
############################################################################################################################
Python Generators
*****************
Generators allow us to generate as we go along, instead of holding everything in memory(eg. list)
# Generator function for the cube of numbers (power of 3)
>> def gencubes(n):
for num in range(n):
yield num**3
>> for x in gencubes(10):
print(x)
O/P : 0 1 8 27 64 125 216 343 512 729
Here the output is not stored in a list.Since we have a generator function we don't have to keep track of every single cube
we created. Generators are best for calculating large sets of results (particularly in calculations that involve loops
themselves) in cases where we don’t want to allocate the memory for all of the results at the same time.
Note : A key to fully understanding generators is the next() function and the iter() function
Note : Watch the video for more understanding
############################################################################################################################
Advanced Python Modules
***********************
Watch videos
############################################################################################################################
Advanced Python Objects and Data Structures
*******************************************
Watch videos
############################################################################################################################
############################################################################################################################
############################################################################################################################
Print
-------
name = "Vysakh"
print("My name is " + name )
Comments
--------
# This is an eg. for single line comment in python.
Math
----
Exponents ->> **
Convert to string
------------------
str(***)
Function
--------
def your_name(name):
print("My name is " + name)
Calling funtion
---------------
your_name("Dobrik")
Funtion with named parameter
----------------------------
def create_spreadsheet(title, row_count = 1000):
print("Creating a spreadsheet called " + title + " with " + str(row_count) + " rows")
# Call create_spreadsheet() below with the required arguments:
create_spreadsheet("Applications", 10)
Note : regular parameter should be passed in the defenition first.
Funtion with return value
-------------------------
def sum(x, y):
return x + y
result = sum(5, 10)
print("Sum is : " + str(result))
Funtion with multiple return value
-----------------------------------
def square_point(x_value, y_value):
x_2 = x_value * x_value
y_2 = y_value * y_value
return x_2, y_2
x_squared, y_squared = square_point(1, 3)
print(x_squared)
print(y_squared)
Boolean
--------
flag = True => no quotes
Check the datatype
------------------
a = "name"
type(a)
<type 'str'>
my_baby_bool_two = True
print(type(my_baby_bool_two))
<class 'bool'>
Conditional Statements
----------------------
if condition:
...
elif condition:
...
else:
...
Error Handling
--------------
try:
# some statement
except ErrorName:
# some statement
Eg:
---
def divides(a,b):
try:
result = a / b
print (result)
except ZeroDivisionError:
print ("Can't divide by zero!")
List
-----
heights = [61, 70, 67, 64]
names = ['Jenny', 'Alexus', 'Sam', 'Grace']
mixed_list = ['Jenny', 61]
heights = [['Jenny', 61], ['Alexus', 70], ['Sam', 67], ['Grace', 64], ['Vik', 68]]
. A list begins and ends with square brackets ([ and ]).
. Each item (i.e., 67 or 70) is separated by a comma (,)
. It’s good practice to insert a space () after each comma, but your code will run just fine if you forget the space.
Zip
---
zip is used to merge to list
names = ['Jenny', 'Alexus', 'Sam', 'Grace']
dogs_names = ['Elphonse', 'Dr. Doggy DDS', 'Carter', 'Ralph']
names_and_dogs_names = zip(names, dogs_names)
list_of_names_and_dogs_names = list(names_and_dogs_names)
print(list_of_names_and_dogs_names)
Empty list
----------
my_empty_list = []
my_empty_list.apppend[1]
print my_empty_list --> [1]
List cconcatenation
-------------------
broken_prices = [5, 3, 4, 5, 4] + [4]
broken_prices ==> [5, 3, 4, 5, 4, 4]
Range
-----
The function range takes a single input, and generates numbers starting at 0 and ending at the number before the input.
So, if we want the numbers from 0 through 9, we use range(10) because 10 is 1 greater than 9:
my_range = range(10) => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
my_range = range(2, 9) => 2, 3, 4, 5, 6, 7, 8
my_range = range(2, 9, 2) => 2, 4, 6, 8
Length of a list
-----------------
broken_prices = [5, 3, 4, 5, 4] + [4]
length = len(broken_prices) ==> len()
To get final element in a list
-------------------------------
list[-1]
age = [1, 2, ,3 ,4]
print(age[-1]) ==> 4
Slicing Lists
-------------
age[0:3] => [1, 2]
>>> fruits = ['apple', 'banana', 'cherry', 'date']
>>> print(fruits[0:3])
['apple', 'banana', 'cherry']
>>> print(fruits[:3])
['apple', 'banana', 'cherry']
>>> print(fruits[2:])
['cherry' , 'date']
Counting elements in a list
---------------------------
votes = ['Jake', 'Jake', 'Laurie', 'Laurie', 'Laurie', 'Jake', 'Jake', 'Jake', 'Laurie', 'Cassie', 'Cassie', 'Jake', 'Jake', 'Cassie', 'Laurie', 'Cassie', 'Jake', 'Jake', 'Cassie', 'Laurie']
jake_votes = votes.count('Jake') ==> 9 , count of Jake in the list
Sorting Lists
--------------
names = ['Xander', 'Buffy', 'Angel', 'Willow', 'Giles']
print(names) ===> ['Xander', 'Buffy', 'Angel', 'Willow', 'Giles']
names.sort() or sorted(names)
print(names) ===> ['Angel', 'Buffy', 'Giles', 'Willow', 'Xander']
Tuple
-----
Tuples are immutable.
my_info = ('Mike', 24, 'Programmer')
my_info ==> ('Mike', 24, 'Programmer')
my_info[0] ==> 'Mike'
my_info[1] ==> 24
my_info[-1] ==> Programmer
Unpacking a tuple
-----------------
name, age, job = my_info
name => Mike
age => 24
job => Programmer
Create a For Loop
-----------------
for <temporary variable> in <list variable>:
<action>
for i in dog_breeds:
print(i)
Eg using break:
---------------
dog_breeds_available_for_adoption = ['french_bulldog', 'dalmatian', 'shihtzu', 'poodle', 'collie']
dog_breed_I_want = 'dalmatian'
for dog in dog_breeds_available_for_adoption:
print(dog)
if dog == dog_breed_I_want:
print("They have the dog I want!")
break
Eg: using continue:
-------------------
ages = [12, 38, 34, 26, 21, 19, 67, 41, 17]
for age in ages:
if age < 21:
continue
else:
print(age)
To retrieve value from a list use .pop()
Eg:
all_students = ["Alex", "Briana", "Cheri", "Daniele", "Dora", "Minerva"]
students_in_poetry = []
while len(students_in_poetry) < 3:
student = all_students.pop()
students_in_poetry.append(student)
print(students_in_poetry)
pop() always fetch the last value in the list.
List Comprehensions
--------------------
words = ["@coolguy35", "#nofilter", "@kewldawg54", "reply", "timestamp", "@matchamom", "follow", "#updog"]
usernames = [word for word in words if word[0] == '@'] ==> Eg: for list comprehension
>>> print(usernames)
["@coolguy35", "@kewldawg54", "@matchamom"]
Eg: 2
------
my_upvotes = [192, 34, 22, 175, 75, 101, 97]
We want to add 100 to each value. We can accomplish this goal in one line:
updated_upvotes = [vote_value + 100 for vote_value in my_upvotes]
Strings
-------
my_name = "Vysakh"
first_initial = my_name[0]
print(first_initial) ==> V
Slice of String
---------------
string_name[first_index:last_index]
String Concatenation
---------------------
fruit_prefix = "blue"
fruit_suffix = "berries"
We can create a new string by concatenating them together as follows:
favorite_fruit = fruit_prefix + fruit_suffix
>>> favorite_fruit
'blueberries'
String Methods
--------------
>>> 'Hello world'.upper() => 'HELLO WORLD'
>>> 'Hello world'.lower() => 'hello world'
>>> 'Hello world'.title() => 'Hello World'
>>> 'Hello World'.split() => ['Hello', 'world']
>>> ''.join(['Hello','world']) => 'Hello world'
>>> 'Hello world'.replace('H', 'J') => 'Jello world'
>>> ' Hello world '.strip() => 'Hello world'
>>> "{} {}".format("Hello", "world" => 'Hello world'
>>> 'Hello'.find('e') => '1'
>>> \n => represent new line
>>> \t => represent new tab
Another example for join()
-------------------------
reapers_line_one_words = ["Black", "reapers", "with", "the", "sound", "of", "steel", "on", "stones"]
reapers_line_one = ' '.join(reapers_line_one_words)
Another example for format()
----------------------------
def favorite_song_statement(song, artist):
return "My favorite song is {} by {}.".format(song, artist)
>>> favorite_song_statement("Smooth", "Santana")
"My favorite song is Smooth by Santana"
Dictionary
----------
empty dictionary={}
add multiple keys using update()
-------------------------------
sensors = {"living room": 21, "kitchen": 23, "bedroom": 20}
sensors.update({"pantry": 22, "guest room": 25, "patio": 34})
print(sensors) ===> {"living room": 21, "kitchen": 23, "bedroom": 20, "pantry": 22, "guest room": 25, "patio": 34}
Convert 2 list to dictionary using list comprehension
-----------------------------------------------------
names = ['Jenny', 'Alexus', 'Sam', 'Grace']
heights = [61, 70, 67, 64]
Python allows you to create a dictionary using a list comprehension, with this syntax:
students = {key:value for key, value in zip(names, heights)}
#students is now {'Jenny': 61, 'Alexus': 70, 'Sam': 67, 'Grace': 64}
.get()
-------
Dictionaries have a .get() method to search for a value instead of the my_dict[key] notation we have
been using. If the key you are trying to .get() does not exist, it will return None by default:
user_ids = {"teraCoder": 100019, "pythonGuy": 182921, "samTheJavaMaam": 123112, "lyleLoop": 102931, "keysmithKeith": 129384}
tc_id = user_ids.get('teraCoder',100000) ==> 100000 is the default return value if no match found
print(tc_id)
stack_id = user_ids.get('superStackSmash',100000)
print(stack_id)
Delete a key
-------------
Use pop()
---------
raffle = {223842: "Teddy Bear", 872921: "Concert Tickets", 320291: "Gift Basket", 298787: "Pasta Maker"}
>>> raffle.pop(320291, "No Prize")
"Gift Basket"
Get All Keys
-------------
use .keys()
>>> user_ids = {"teraCoder": 100019, "pythonGuy": 182921, "lyleLoop": 102931, "keysmithKeith": 129384}
>>> users = user_ids.keys()
>>> print(users)
dict_keys(['teraCoder', 'pythonGuy', 'lyleLoop', 'keysmithKeith'])
Get All Values
---------------
use .values()
>>> num_exercises = {"functions": 10, "syntax": 13, "loops": 22, "lists": 19, "classes": 18, "dictionaries": 18}
>>> total_exercises = 0
>>> for exercises in num_exercises.values():
total_exercises += exercises
print(total_exercises) ==> 100
Get keys and values
--------------------
use .items()
Classes
-------
class Facade: => Class definition
pass
facade = Facade() => Instantiation
class Circle():
pi = 3.14
def area(self, radius):
area = self.pi * radius ** 2
return area
circle = Circle()
pizza_area = circle.area(6)
teaching_table_area = circle.area(18)
round_room_area = circle.area(5730)
Constructor
-----------
class Circle:
pi = 3.14
# Add constructor here:
def __init__(self, diameter):
print("New circle with diameter: {}".format(diameter))
teaching_table = Circle(36)
hasattr() and getattr()
----------------------------
Class eg with constructor
-------------------------
class Circle:
pi = 3.14
def __init__(self, diameter):
print("Creating circle with diameter {}".format(diameter))
# Add assignment for self.radius here:
self.radius = diameter/2
def circumference(self):
circumference = 2 * self.pi * self.radius
return circumference
medium_pizza = Circle(12)
teaching_table = Circle(36)
round_room = Circle(11460)
medium_pizza.circumference()
teaching_table.circumference()
round_room.circumference()
Inheritence
-----------
class User:
is_admin = False
def __init__(self, username)
self.username = username
class Admin(User):
is_admin = True
Overriding
----------
class User:
def __init__(self, username, permissions):
self.username = username
self.permissions = permissions
def has_permission_for(self, key):
if self.permissions.get(key):
return True
else:
return False
class Admin(User):
def has_permission_for(self, key):
return True
Super()
-------
super() gives us a proxy object. With this proxy object, we can invoke the method of an object’s parent class
(also called its superclass).
class PotatoSalad:
def __init__(self, potatoes, celery, onions):
self.potatoes = potatoes
self.celery = celery
self.onions = onions
class SpecialPotatoSalad(PotatoSalad):
def __init__(self, potatoes, celery, onions):
super().__init__(potatoes, celery, onions)
self.raisins = 40
Interfaces
----------
class InsurancePolicy:
def __init__(self, price_of_item):
self.price_of_insured_item = price_of_item
class VehicleInsurance(InsurancePolicy):
def get_rate(self):
return self.price_of_insured_item * .001
class HomeInsurance(InsurancePolicy):
def get_rate(self):
return self.price_of_insured_item * .00005
Polymorphism
------------
a_list = [1, 18, 32, 12]
a_dict = {'value': True}
a_string = "Polymorphism is cool!"
len(a_list)
len(a_dict)
len(a_string)
Default Return
---------------
A Python function that does not have any explicit return statement will return None after completing. This means that
all functions in Python return something, whether it’s explicit or not.
eg. print() returns None
*args vs **kwargs
-----------------
Positional Argument vs Keyword Argument
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment