Python Notes

Link: https://colab.research.google.com/drive/17cavGpF0hKKSmMnwKpDwMAAoM5j2ZKZ6?usp=sharing

Python Class 1 (17-March)

Python Class 1

17-March

Titash De

https://www.linkedin.com/in/titashde14

titas.de_1@scaler.com

check before 45, (lost connection)


Low-Level Language – Interacts directly with harware (C, C++)

High-level language –
At high level, logic is simple,
but later it is converted into series of instruction or command (which may not be understood by the user),
that converted instructions are then communicated with hardware.

High level become low level language, to interact with hardware.


Data Structure –

  1. Integer and float –

Single Data -16, 3.5

It can be stored in single variable.

variable means like a glass.

It can change the value, like a glass hold water or juice or any liquid.


  1. String
    “apple” – double quote for string
    ‘c’ – single character
  2. Boolean data

var=true

  1. Date Time
    var=2023-03-17 date data type

quotes can change the data type…


Data Collection:

  1. Array/List – collection of data with same data type
  2. Tuple – collection of data with different data type
  3. Set – Collection of dynamic data type which can include tuple and array both.

print all numbers from 1 to 10

for i in range (1,10+1,1):
print (i)

1 – starting point
10 – end point

end point is not included in the condition.

1 in the end is 1 step at a time,

result
1
2
3
4
5
6
7
8
9
10


range(start point, count of number to be printed, step)

step is optional
default step is 1
it will always include first value.


to make it horizontal

print (i,end=” “)

end=” ” – print horizontally with value separate by whatever is put between quotes.
it will


\n – new line – escape character


for i in range(1,10,1):
print(i,end=”,”)
print(10)


Python Class 2 (22-March)

There are mainly 3 Operators in Python:

1) Arithmetic Operators

4 Types of Arithmetic Operators:

a) Plus +

b) Minus –

c) Multiply *

d) Divide /

**********************************************************************************************************************

Point to Note with Division:

-> 3 + 3 = 6 (Result is Integer)
-> 3-3 = 0 (Result is Integer)

-> 3 * 3 = 9 (Result is Integer)

-> 6/3 = 2.0 (But Result is Float)

Because there is always a chances that information is lost in integer, for example – 10/3 = 3.333

But if it comes as integer, then it is 3 where we can see 0.333 information is lost.
So it is better to have result as float rather than integer in division operator.

***********************************************************************************************************

Rule:

3.5 + 3.5 = 7.0

1) 7
2) 7.0 – correct answer
3) “7”

Rule:
float + float = float
integer + float = float
Integer / Integer = float

Note: If any operand is float, then result will always be float.


% – remainder

15%3 = 0
10%3 = 1

  • Integer%Integer = remainder
  • float%float = no remainder (There is no remainder)
  • Remainder will be converted into decimal, so no remainder while dividing float numbers.

  • Remainder cannot be negative, because it is showing only what is left while dividing, not the result of division.

-minus or plus, remainder will always be in positive.

-10%3= cannot be -1, but it is +1.

  • modulas means remainder. (what is not divisible)

When the number is negative, calculating remainder is different:

-Negative calculation is tricky.

-17 % 7
= (-21 + 4) % 7
Remainder/Modulas is -4 because -21 is completely divisble by 7


‘**’ – Power Operator (two stars)

2**8 = 8 (2)³

5**2 means (5)2 = 25 = (5)² power of 2

25**0.5 = 5 (2√5) (Square root) (square root will be float)

8**(1/3)= 2.0 (cube root) = 3√8


Integer ** float = float


Integer division = //

15/5 = 3.0 (result is float)
15//5= 3 (result is Integer)

so if we don’t want .0 after the result and don’t want to make it float then we use integer division.

16//7 = 2 (2 is result because it is before decimal)

-16//7 =
(-21 +5 // 7
= -2.285 = -3(rounded version)


-16/5 = -3.2

-16//5 = -4 (-3.2 rounded down)(floor value)


-18/4 = 4.5

-18//4 = -5 (-4.5 rounded down)


Step Function, Number Line


a=5
print(type(a))

output: integer


a=”5.0″
print(type(a))

output: float


a=False
print(type(a))

output: bool


type casting

  • means converting from one data type to another data type

converting float to integer:

a=5.0
print(type(a))

b= int(a) # type casting operation -> float to int

print(type(a))

output:

float

integer


convert string to float
a=”123″
print(type(a))
b=float (a)
print(b)
print(type(b))

output is float


convert boolean to integer

True becomes 1
False becomes 2

Note: Python is case sensitive


convert integer to boolean

0 becomes false
but any non-zero value becomes true

0 – false
1 – true
2- true
3 – true
4 – true

even with negative integer, it will be true.
Only 0 is false, rest all value will become true.


string to boolean

empty string means false
if there is any string , then it is true


NoneType

a= None
print (print(a))

It is a default value, sometiems being given when datatype or actual values are not known.

none to string = “None” (string)
none to integer = no conversion. It shows error.

“1234”(number string) to 123 (Integer)

“123abc” (text including string) to integer = will show error. cannot convert.


bolean data type will

True – Boolean
true – shows error


10**-1 = 0.1

1/10


10//0 = error

whenever there is division by 0, it will always show error.
division by 0 is not possible.

  • check that b is non-zero, otherwise your code will break. we need to make sure

BODMAS

Bracket Order (Power Of) Division Multiplication Addition Substraction


PEMDAS

Parenthesis – ()
Exponent (Power of) – **
Multiply
Divide
Add
Substract

  • Divide and Multple can be done in any order. They are in same group.
  • Add and Minus can also be done in any order. They are also in same group.

Note: whenever there is power of or division in calculation, then it will be float data type most of the time.


2) Comparison Operators

<,>,>=,<=,==,

output will be in boolean data type i.e. True or False

With the comparision operator, the output will always be boolean.

5>6 = false
6>5 = true
6>=5 = true

6==5 = false (doube equal to means LHS=RHS)

== means equal to
!=means not equal to

6!=6 = false
6==6 = true


3) Assignment Operators

a -> 5

a = it is value
5 = Memory location ( it is a location where the value ‘a’ is stored)


How to update a value??

a = 5
b = 7
a = a + b

a (new value) = a (old value) + b

Update old value of a

a new value = 5 + 7 = 12

Update old value of a


another way to update value

a += b
it is same as a = a + b

‘+=’- this is called shorthand operators


a = 5

a – container/variable/name of memory location

= – assignment operator

5 – value


there are no infinity in python,
there is only error using 0.

like – 1/0 gives error (anything divided by 0 gives error) (when 0 is below in division, it gives error)

and 0/1 gives 0.0


when comparing string:

a= “apple”
b= “apple”

a=b – true


a= “apple”
b= “banana”

a=b – true (alphabetical order) (a comes before b)
ab = false

apple>apples – false
apple<apples – true

apples<banana – true


Upper case comes before lower case

ABC…Z abc…z

A<a

Print(“A”<“a”)

Python Class 3 (24-March)

Input()

input() – when you put it in code, it will ask the input before coding calculation.

example –

a = input()
print (a)
print (type(a))

  • By default, the output comes in String data type. If you want to do some calculation, then the data type needs to be changed to suitable data type such as integer, float, bool.

Type casting from string to integer:

a = int(input())

print (type(a))

print (a**3)

Input: 2

Output:

<class ‘int’>

8

  • then it will ask to enter the input, then it will calculate

***********************

a = input()

print (type(a))

print (a**3)

Input: 2

Output: Error


  • We are trying to do calculation using “2” string data type, so it will give error here.
  • First we will need to convert it into Integer, then we can do any mathematical calculation.

Converting to Boolean:

When it will give True:

a = bool(input())

print (type(a))

print (a)

Input: 0

Output:

<class ‘bool’>

True

  • Even if you put value “0” or empty space, you will get True and not get False.
  • Because 0 or empty space is also counted as some value.
  • As long as you put something, it will always give True.
  • If you don’t enter any value, then only you will get False.

*********************************************************

When it will give False:

a = bool(input())

print (type(a))

print (a)

Input: (enter without any value)

Output:

<class ‘bool’>

False

  • here we have not entered any value, so we are getting False.

Converting to Float:

a = float(input())

print (type(a))

print (a**3)

Input: 2

Output:

<class ‘float’>

8.0


Concatenating in Python:

str1 = input()
str2 = input()
print(str1 + ” ” + str2) # concatenation
print (str1,str2)

  • This is method of concatenation in Python

Combining Without Space:

a = “apple”
b = “banana”
print(a,end=””)
print(b)

Output:
applebanana

  • here it will not go to second line, because there is no space in end=””

Combining With Space:

But if you put
print (a,end=” “)
print(b)
Output:
apple banana

  • space comes between both words

How to Print in Separate Lines using “\n”?

print (a,end=”/n”)
print(b)
Output:
apple
banana

  • Even if we don’t put /n, then it will work as /n(means put enter)
  • by default it is /n, but when we define it in end=””, then the output changes and don’t go to next line. It will work according to what we put in end=””.

How to Print in separate lines without using “\n”?

print (a)
print(b)
Output:
apple
banana

  • work same as without end=/n

HomeWork (Escape Character):

Read for homework:

escape character


AND – &

  • Instead of typing “and”, we can also type “&”.
  • capital “AND” operator wont work in Google Collab
  • small case “and” will work in Google collab
  • & – ampersand
  • AND – Multiplication
  • if we use &, then we need to use bracket
  • if we use and, then we don’t need to use bracket.

OR – |
| – pipe symbol

  • OR – Addition
  • small case “or” will work in google collab and not Capital Case “OR”

NOT –

reverse value will come of the true or false

not(6<5)

output: false (reverse of true)


Order of Execution (AND, OR, NOT)

First: N – Not,
Second: A – then AND,
Third: O – then OR

  • Short form to remember the Order of Execution: NAO / NANDOR

IF ELSE Condition

time = float(input())

if time>9 and time<=12:

  print(“good morning”) 

else:

  if time>12 and time<=17: # 17 -> 5 pm as 12+5 = 17

    print(“good afternoon”) 

  else:

    if time>17 and time<=20: # 20 -> 8 pm as 12+8 = 20

      print(“good evening”)

    else:

      if time>20 and time<=24: # 24 -> 12 mid-night as 12+12 = 24

        print(“good night”)

      else:

        print(“go to bed”)

  • When you run it, it will ask to input the number(time) because in the beginning time is given as input() in float data type.
  • Tab – Tab Space to Right
  • Shift + Tab – Tab Space to Left
  • shift + tab used for else to give second condition

Another way to put IF ELSE Condition using “ELIF”

time = float(input()) # time in 24 hour clock -> 0 to 24 not AM and PM

if time>9 and time<=12:

  print(“good morning”) 

elif time>12 and time<=17: # 17 -> 5 pm as 12+5 = 17

  print(“good afternoon”) 

elif time>17 and time<=20: # 20 -> 8 pm as 12+8 = 20

  print(“good evening”)

elif time>20 and time<=24: # 24 -> 12 mid-night as 12+12 = 24

  print(“good night”)

else:

  print(“go to bed”)

  • Here the “Else IF” can be written as “ELIF”. This method of writing less code is called short hand.

How to Optimize the Condition of Greater Than and Lesser Than:

time = float(input()) # time in 24 hour clock -> 0 to 24 not AM and PM

if 9<time<=12:

  print(“good morning”) 

elif 12<time<=17: # 17 -> 5 pm as 12+5 = 17

  print(“good afternoon”) 

elif 17<time<=20: # 20 -> 8 pm as 12+8 = 20

  print(“good evening”)

elif 20<time<=24: # 24 -> 12 mid-night as 12+12 = 24

  print(“good night”)

else:

  print(“go to bed”)

  • Here we have written “time>9 and time<=12” as “9<time<=12”

Difference Between No Space and Empty Space String:

  • bool(” “) – True,
    because there is empty space which is treated as some value. All the non-zero are treated as True or 1.
  • bool(“”) – False,
    because there is no space and no value(Null) inside it. It is treated as 0.

Concatenation:

print(str(9)+”\n”+str(9))
Output:
9
9

  • Here we are concatenating the string. Integer cannot be concatented. Integer needs to be converted to Strings to be concatenated.

SEP

sep means seperate line. Whatever we put in the sep will come between the given values:

print(“A”,”B”,”C”,”D”,sep=”\n”)

Output:

A

B

C

D

**********************************

print(,1,2,3,4,5,6,7,8,9, sep=”-“)

Output:

1-2-3-4-5-6-7-8-9


Rounding Off Error (Precision Error):

0.1 + 0.2 = 0.3

Output = False

****************************************

if we run –> 0.7+0.2+0.1, out is 0.999999 and not 1.0.

but if i write 0.7+0.1+0.2 it is working

some rounding off error is happening in python. Do research.

*************************************

https://python.plainenglish.io/floating-point-arithmetic-precision-error-in-python-decimal-comes-for-rescue-8803d1290601

https://docs.python.org/3/tutorial/floatingpoint.html

Python Class (3-May)

Python Class: 3rd May

ch.isupper()
ch.islower()

s=”My name is Rovin. What is your name? I am doing fine”
s.split()
s.replace(” “,”-“).split(“-“) # method chaining

split() – if we don’t put anything inside, then by default it will split based on space. If there is no space in the string, then whole string will be the output.


Join – convert list into string (reverse of split)

data=[“there”,”1″, “a”,”dog”]
” “.join(data) #put what you want to put in between elements. If you want to join using space.
“-“.join(data)
“,”.join(data)

It won’t work with numeric or integer data in the list.


st= “the quick brown fox jumps over the lazy dog”

st.find(“the”)
output: 0

st.find(“f”)
output:16

st.find(“za”)
output:-1 # not present, then returns -1

S.find(sub[, start[, end]])

It will give output of first occurence only.

If we want second occurence, we need to remove the starting position by doing +1.

such as:

st.find(“a”,st.find(“a”)+1,) # second occurence

st.find(“a”,st.find(“a”)+-1,) # last occurence


aw=”Rovin”
id(aw)
aw=”rovin”
id(aw)


IN operator:

s=”My name is Rovin”
Rovin in s
Output: True


Not In operator:

It also work like in sql


Starts with – means string is starting with the given word or not?

message = “Not Hello World!”
print(message.startswith(“Not”))
Output: True


https://www.interviewbit.com/python-cheat-sheet/

Python Class (10-May)

Python Class; 10-May

Dictionary:

Empty Dictionary – {}


Dictionary syntax:
{
‘key’: ‘value’
‘key’: ‘value’
}

key:value(meaning of the key)


food.menu =

{
“Samosa”:15,
“Burger”: 50,
“Pizza”: 100,
“Juice”: [20, 30, 40] #Small juice, medium juice, large juice
}

len(food.menu) = 4


Extracting or indexing or reading the dictionary

food.menu[‘Samosa’]
Output: 15

food.menu[‘1’] – Indexing using position won’t work


indexing happens only with square bracket.


Adding key:

food.menu[‘Momos’] = 100


Modifying value:

food.menu[‘Samosa’] = 20


food_menu.keys() – shows key only
food_menu.value() – shows value only

convert into list:

list(food_menu.keys())
list(food_menu.value())


food_menu.items() – shows both keys and value
list(food_menu.items())

for k,v in food_menu.items:
print(k,’->’,v)


Dictonary can have only immutable data type such as:

string, integer, tuple, list, float, dictionary, boolean

Sets are mutable so can’t be stored in dictionary.


we can only use string, float, integer, boolean

LSD – List, Set, Dictionary

LSD can’t be used as Key.


string.count

Python Numpy Class (19-May)

Python; Numpy Class; 19-May

Instructor – Nikhil Sanghi
Full time instructor at Scaler
Primary Focus on Advanced Deep Learning techniques and ares which is Natural Language Processing
Graduated from Bits Pilani

What kind of startup you had?
Why you sold it?
Why not started a startup again?

Email id – nikhil.sanghi@scaler.com
Phone: 90358 52260

Teach – Python Library, Probability, Statistics, Maths, ML, Hypothesis Testing, DL, Neural Network, Computer Vision (CV), NLP

Before 36 min
Started at 36 min…

Telling about the feedback rating from 1 to 10 and groups are made based on rating i.e. detractors, passives and promoters.

He is telling that rating group can change based on industry or company.

0-6 = detractors
7-8 = passives
9-10 = promoters

Net Promoter Score (NPS) = % Promoters – % Detractors

Note: We are not considering passives because they are neutral. There is neither criticism nor appreciation.


NumPy – Library/Module

NumPy – Numerical Python

Sum, Diff, Multiply, Division – Math Library

Library or Module stores frequently used functions so that it helps in efficiency without wasting time or energy to create new function every time.

Similar types of functions are stored together


NumPy Array is a collection of homogenous data type. It means only same data type can come in a list of NumPy Array.

[‘Scaler’, ‘Rovin’, ‘Data’] – Possible (All Strings)
[1, 2, 3] – Possible (All Integers)

[‘Scaler’, 1 , 1.111] – Not Possible in NumPy Array (Different Data Types)


Integer Caching (Garbage Collection)

Storing most frequent used number


How NumPy Array is different from Normal List ?

From -5 to 255 it is stored in one address.

id(255)
id(15)

NumPy arrays are faster than List even with same value.

A = [100, 1, 2, 3]


How to install numpy
pip install numpy – in terminal
!pip install numpy – in jupyter notebook
with !, you can use terminal command in notebook

import numpy
import numpy as np – we can give alias so we don’t waste time 5 character of numpy everytime with function.

we need to import library and it is not there by default because there are many function with same name in different library.


[i**2 for i in a] # list comprehension

for i in a:
b.append(i**2)

lamda function


d=np.array([1,2,3,4,5])

d**2
Above is advantage of numpy without using for loop

d+1

Two things happening in background

Vectorization + Broadcasting

%timeit – it tells time taken for implementing a function or code

ms – millisecond
us – microsecond


numpy array stores in sequence or continuous memory block depending on the byte taken.

but normal list will have random address.

It means time taken to travel or search from one point to another is more in normal list and less in numpy array.


Pandas is for String and Numbers
NumPy is better for Numbers mostly and not preferred for Strings(Pandas is better)

Pandas has some NumPy functions also, NumPy is faster than Pandas.


for mathematical functions, numpy is faster


Magic Function – https://ipython.readthedocs.io/en/stable/interactive/magics.html

Python vs IPython


Vectorx AI

Python Numpy Class (22-May)

Python; Numpy Class; 22-May

from 13 mins

Boolean – 1 byte
integer – 4 bytes
float – 8 bytes

string – 32 bytes

strings are represented by unicode – U32

Upto 32 character it can stores string with 32 bytes.


bool to int is possible
string to int is not possible.

size – no. of values
shape – (3,3)


dtype=”U10″

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top