Python
Python
Python
Shortcuts for jupyter notebook
Shortcuts Functionality
v paste
c copy
z undo
Markdown cell
A cell that contains strictly documentation and it would never be executed.
Datatypes in python
int - Refers to the integer
float - Refers to the floating point number or decimal
bool - This is boolean - ‘True’ or ‘False’ value
string - Text values composed of sequence of characters
Python 1
Typecasting
Converting from one datatype to other
x = 5
type(x)
int
float(x)
5.0
type(var)
z = 1
z = 6
z
Comments
New line
Just use a backslash, forward slash is divide so can’t use
Python 2
5*2 \
+3
13
Indexing elements
"u"
Operators
Arithmetic operators
Operator
+ Addition
- Subtraction
* Multiplication
** Power
% Remainder
Comparison Operators
Equal to ==
Not equal to !=
Python 3
Operators Usage
Priority of operators -
1. not
2. and
3. or
Identity Operators
Operator Meaning
is ==
is not !=
Conditional statements
1st type
if condition:
conditional code
else:
else code
Python 4
2nd type
if condition:
conditional code
if condition:
conditional code
3rd type
if condition:
condition code
elif condition:
condition code
else:
condition code
Main difference
Feature if-elif if if
Functions
Defining function
Python 5
def function_name():
function body
function_name()
Eg without parameter
def aditya():
print("He is great")
aditya()
He is great
Defining function
def function_name(parameter):
function body
Function calling
function_name(argument)
Eg
def plus_two(x):
return x+10
Python 6
plus_two(4)
14
3. print() vs return
Main difference
1. print()
Purpose: It displays something on the screen.
Example:
python
Copy code
def say_hello():
print("Hello, Aditya!")
say_hello()
Copy code
Hello, Aditya!
2. return
Python 7
Purpose: It sends a value back to the part of the code where
the function was called.
Usage: Used when you want to use the result later in your
program.
Example:
python
Copy code
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result)
Key Difference
print: Outputs something for the user to see but doesn't allow
the program to use that output.
return : Gives a result to the program for further use but doesn't
display it unless you explicitly print it.
Extra note
Python 8
💡 We can return only a single result out of function
def plus_ten(a):
result = a*10
return "Outcome"
return result
plus_ten(3)
'Outcome'
def plus_ten(a):
result = a*10
print("Outcome")
return result
plus_ten(3)
Outcome
30
Python 9
def wage(hours):
return hours*10
def with_bonus(hours):
return wage(hours)+50
wage(10), with_bonus(10)
(100, 150)
def add_money(m):
if m>=100:
m = m+10
return m
else:
return "Save more, man!"
add_money(90)
def parameters(a,b,c):
result = a-b*c
print("Parameter a equals to ", a)
print("Parameter b equals to ", b)
print("Parameter c equals to ", c)
return result
Python 10
parameters(b=2,c=3,a=10)
Parameter a equals to 10
Parameter b equals to 2
Parameter c equals to 3
4
7. Built-In functions
5. abs() : Returns the absolute value of its argument. Ex. abs(-20) —>
20
9. len() : Returns the length of the string and not for numbers. It can
even count the number of elements in list. Ex. len(”power”) —> 5
Storing Data
Lists
Introduction
Python 11
And between this, you’ve to separate the items using ‘ ‘.
If you’ve extract the element from the end, you can use the
indexing as -1. -2…
Creating a list
Ex. 1
'John'
Ex. 2
'Andrew'
Python 12
print(participants)
Built-in method
Syntax
object.method()
2. method() --> The main method that will work for what's
needed
Methods
list_name.append()
list_name.extend()
Python 13
This in-built function is used for extending the list or
combining two list into one
list_name.index()
list_name.sort()
Python 14
participants
In ascending order
numbers = [2, 1, 3, 4, 5]
numbers.sort()
numbers
[1, 2, 3, 4, 5]
In descending order
numbers = [2, 1, 3, 4, 5]
numbers.sort(reverse = True)
numbers
[5, 4, 3, 2, 1]
List slicing
Python 15
This is done to extract a particular list from the bigger list. It’s
inclusive of the initial numbers and exclusive of the 2nd number.
['Laila', 'Jack']
['John', 'Laila']
Python 16
[['John', 'Laila', 'Jack', 'Andrew', 'Aditya', 'Georg
['Keshav', 'Mahima', 'Shreya', 'Siddharth']]
Tuples
Introduction
They are immutable that means their value can’t be update once
they’re formed
Creating a tuple
y = 1, 2, 3
y
(1, 2, 3)
OR
x = (3, 4, 5)
x
(3, 4, 5)
List1 = [x, y]
List1
Python 17
Extracting from tuple
23
10
Tuple in function
def area_or_perimeter(x):
area = x**2
perimeter = x*4
print("The area and perimeter is ")
return area, perimeter
area_or_perimeter(5)
Dictionaries
Introduction
Creating a dictionary
Python 18
{'Name': 'Aditya', 'Age': '22', 'Salary': '90,000'}
dict['Name']
'Aditya'
dict['gender'] = 'Male'
dict
.get() method
'Aditya'
Python 19
dict = {'Name' : 'Aditya', 'Age' : '22', 'Salary'
print(dict.get('Gender'))
None
Iterations
Iteration is the ability to execute certain code repeatedly.
for loop
Eg syntax
list = [3,4,7,8,9]
for n in list:
print(n)
3
4
7
8
9
OR
list = [3,4,7,8,9]
for n in list:
print(n, end = " ")
3 4 7 8 9
x = [1,2,3]
for item in x:
print(item, end = " ")
Python 20
1 2 3
OR
x = [1,2,3]
for item in range(len(x)):
print(item+1, end = " ")
1 2 3
x = [1,2,3]
for item in range(len(x)):
print(x[item], end = " ")
1 2 3
while loop
x = 0
while x<=20:
print(x, end = " ")
x=x+2
0 2 4 6 8 10 12 14 16 18 20
range()
Introduction
If you don’t provide a start value, then it takes the default value
as 0, and step value as 1 as well.
Python 21
list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def count(numbers):
total = 0
for a in numbers:
if a<20:
total+=1
return total
list_1 = [17, 15, 21, 34]
count(list_1)
nums = [1,35,12,24,31,51,70,100]
def count(number):
while len(number)<len(number)+1:
total = 0
for a in number:
if a<20:
total+=1
return total
Python 22
print(count(nums))
prices = {
"box_of_spaghetti" : 4,
"lasagna" : 5,
"hamburger" : 2
}
quantity = {
"box_of_spaghetti" : 6,
"lasagna" : 10,
"hamburger" : 0
}
money_spent = 0
for i in prices:
money_spent= money_spent + (prices[i]*quantity[i])
print(money_spent)
It basically iterates for key and so based on the indexing of the key, we
got the values
74
Definition
Object
Class
Defines the rule of creating an object
Python 23
Eg
Function vs method
Function Method
1. Module
2. Package or library
Importing module eg
Method 1
import math
math.sqrt(4)
2.0
Python 24
Method 2
4.0
Method 3
5.0
Method 4
import math as m
m.sqrt(36)
6.0
Software documentation
Python 25
assists its users.
Scalar
import numpy as np
v = np.array(5)
v
array(5)
Vectors
It’s 1*m or m*1
import numpy as np
v = np.array([2,3,-4])
v
array([ 2, 3, -4])
Matrices
1. It’s m*n
Python 26
3. It’s collection of vectors or scalars
import numpy as np
m = np.array([[2,3,4], [5,-2,-6]])
m
array([[ 2, 3, 4],
[ 5, -2, -6]])
type(m)
numpy.ndarray
1D Array
v = np.array([2, 3, 4])
print(v.shape) # Output: (3,)
2D Array
v = np.array([[2, 3, 4]])
print(v.shape) # Output: (1, 3)
Python 27
print(v.shape) # Output: (3, 1)
💡 The other variables such as int, float won’t have any shape
and they will throw an error but if you make them using array,
python won’t show any error
object.reshape() method
import numpy as np
v = np.array([1,2,3])
print(v.shape)
print(v.reshape(3,1))
print(v.reshape(1,3))
(3,)
[[1]
[2]
[3]]
[[1 2 3]]
Tensors
This is an overall generalization or scalar, vector and matrices
import numpy as np
v = np.array([[3,2,4],[4,-2,1]])
m = np.array([[2,6,7],[1,-7,2]])
t = np.array([v,m])
Python 28
print(t)
print(t.shape)
array([[[ 3, 2, 4],
[ 4, -2, 1]],
[[ 2, 6, 7],
[ 1, -7, 2]]])
array([[[ 3, 2, 4],
[ 4, -2, 1]],
[[ 2, 6, 7],
[ 1, -7, 2]]])
Python 29
Addition and subtraction
Addition
import numpy as np
v = np.array([[3,2,4],[4,-2,1]])
m = np.array([[2,6,7],[1,-7,2]])
v+m
array([[ 5, 8, 11],
[ 5, -9, 3]])
Subtraction
import numpy as np
v = np.array([[3,2,4],[4,-2,1]])
m = np.array([[2,6,7],[1,-7,2]])
v-m
import numpy as np
v = np.array([[3,2,4],[4,-2,1])
v+1
array([[ 4, 3, 5],
[ 5, -1, 2]])
Python 30
import numpy as np
v = np.array([[3,2,4],[4,-2,1]])
m = np.array([1])
v+m
array([[ 4, 3, 5],
[ 5, -1, 2]])
Transposing vectors
Introduction
Python 31
Syntax
import numpy as np
v = np.array([[3,2,4],[4,-2,1]])
v.T #.T is what needed for transposing
array([[ 3, 4],
[ 2, -2],
[ 4, 1]])
Introduction
Syntax
import numpy as np
v = np.array([2,8,-4])
m = np.array([1,-7,3])
np.dot(v,m)
np.int64(-66)
Scalar*Scalar
import numpy as np
np.dot(5,6)
Python 32
np.int64(30)
Scalar*vector
import numpy as np
x = np.array([5,2,3])
print(x)
print(x*5)
[5 2 3]
[25 10 15]
Introduction
Ex. m*n and n*k can undergo dot product and would result in
m*k matrix
Python 33
Syntax
import numpy as np
x = np.array([[5,2,3],[1,2,3]])
y = np.array([[3,2],[4,3],[5,7]])
np.dot(x,y)
array([[38, 37],
[26, 29]])
NumPy (Numeric+Python)
Python 34
Introduction
6. Arrays look similar to python’s list but array is more useful when
computing values because they work element wise (array)
7. NumPy functions and methods are faster than python methods and
functions
Syntax
import numpy as np
np.__version__
import numpy as np
array_hw_1 = np.array([4,5,7,10])
print(array_hw_1)
Python 35
[ 4 5 7 10]
import numpy as np
array_hw_1 = np.array([[4,5,7,10], [2,3,6,7]])
array_hw_1
array([[ 4, 5, 7, 10],
[ 2, 3, 6, 7]])
Mean of array
Syntax
Normal mean
import numpy as np
array_hw_1 = np.array([[4,5,7,10], [2,3,6,7]])
np.mean(array_hw_1)
np.float64(5.5)
import numpy as np
array_hw_1 = np.array([[4,5,7,10], [2,3,6,7]])
np.mean(array_hw_1, axis = 0)
Python 36
import numpy as np
array_hw_1 = np.array([[4,5,7,10], [2,3,6,7]])
np.mean(array_hw_1, axis = 1)
array([6.5, 4.5])
import numpy as np
array_hw_1 = np.array([[4,5,7,10], [2,3,6,7]])
np.mean(array_hw_1, axis = 1, dtype = int)
array([6, 4])
import numpy as np
array_hw_1 = np.array([[4,5,7,10], [2,3,6,7]])
np.mean(array_hw_1, axis = 1, dtype = float)
array([6.5, 4.5])
Pandas (Panel+Data)
Introduction
Python 37
4. pandas need the computational power and abilities of NumPy to
perform its computations so that you can focus on the analytical
task and less on the underlying mathematical computations
5. Two data structures are at the core They store the data and allow us
to the manipulations on it. They are -
Attributes vs methods
Example
object.attribute object.method()
Syntax
Python 38
import pandas as pd
product = ['A','B','C','D']
product_category = pd.Series(product)
product_category
0 A
1 B
2 C
3 D
dtype: object
import pandas as pd
product = ['A','B','C','D']
product_category = pd.Series(product)
type(product_category)
pandas.core.series.Series
import numpy as np
array_1 = np.array([1,2,3,4,5])
array_2 = pd.Series(array_1)
array_2
0 1
1 2
2 3
3 4
4 5
dtype: int64
Python 39
Introduction
a. Data
b. Metadata
c. related functionalities
object_name.dtype
import pandas as pd
product_category = pd.Series([1,2,3,4,5])
product_category.dtype
dtype('int64')
import pandas as pd
product_category = pd.Series(['A','B','C','D'])
product_category.dtype
dtype('O')
object_name.size
import pandas as pd
product_category = pd.Series(['A','B','C','D'])
product_category.size
Python 40
One of the most interesting thing about attribute is that it can be
used for further calculation.
import pandas as pd
product_category = pd.Series(['A','B','C','D'])
type(product_category.size)
int
object_name.name
import pandas as pd
product_category = pd.Series(['A','B','C','D'])
product_category.name = "Product Category"
product_category
0 A
1 B
2 C
3 D
Name: Product Category, dtype: object
import pandas as pd
product_category = pd.Series(['A','B','C','D'])
product_category.name = "Product Category"
print(product_category.name)
Product Category
object_name.to_numpy()
Python 41
The method to_numpy() in Pandas converts the data in a Pandas
object (like a Series or DataFrame) into a NumPy array.
import pandas as pd
product_category = pd.Series(['A','B','C','D'])
x = product_category.to_numpy()
print(type(x))
Indexing in pandas
Introduction
Product A 22500
Product B 23000
Product C 25240
dtype: object
index
type of index
Python 42
prices_per_category = {'Product A':'22500',
'Product B':'23000','Product C':'25240'}
prices_per_category = pd.Series(prices_per_catego
type(prices_per_category.index)
pandas.core.indexes.base.Index
Python 43