CH1 Introduction To Python
CH1 Introduction To Python
Data Science and Machine Learning# Introduction to Python # Declaring Variables # Conditional Statements #
Generating Sequence Numbers # Control Flow Statements # Working with Collections # Dealing with Strings #
Functional Programming # Modules and Packages
In [1]:
a=3
In [2]:
print(a)
In [3]:
a=5
In [4]:
print(a)
In [5]:
In [6]:
value of var 1 : 2
value of var 2 : 5.0
value of var 3 : True
value of var 4 : Data Science and Machine Learning
In [7]:
Out[7]:
int
In [8]:
type(var2)
Out[8]:
float
In [9]:
type(var3)
Out[9]:
bool
In [10]:
type(var4)
Out[10]:
str
In [11]:
print(type(var1))
print(type(var2))
print(type(var3))
print(type(var4))
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'str'>
In [12]:
if var1 >1:
print("Bigger than 1")
Bigger than 1
In [13]:
x=10
y=12
# if x is greater than y
if x > y:
print("x is greater than y")
# if x is lesser than y
elif x < y:
print("x is lesser than y")
# if x is equarl to y
else:
print("x = y")
x is lesser than y
# Ternary operator
In [14]:
# Intialize x
x = 5
In [15]:
False
# Generating Sequence Numbers # Three parameters to be specified # Start number # Stop number (last
number is not included) # Step number (optional value, default step is 1)
In [16]:
numbers = range(1,10)
In [17]:
for i in numbers:
print(i)
1
2
3
4
5
6
7
8
9
In [18]:
numbers = range(1,20,2)
In [19]:
for i in numbers:
print(i)
1
3
5
7
9
11
13
15
17
19
#initialize i
i = 1
In [21]:
1
2
3
4
Done
# Functions # Functions are created using "def" keyword # Function signature should contain the function name
followed by input parameters and end with : # Function ends with a return statement # Function may also not
end with a return statement
In [22]:
def addElements(a,b):
return a+b
In [23]:
result = addElements(2,3)
print(result)
In [24]:
result = addElements(2.5,3.5)
print(result)
6.0
In [25]:
result = addElements("DataScience","MachineLearning")
print(result)
DataScienceMachineLearning
In [26]:
def addElements(a,b=4):
return a+b
In [27]:
print(addElements(2))
In [28]:
print(addElements(2,5))
# Working with Collections Collections are useful containers or data structures to store and manipulate list of
homogeneous or heterogeneous elements. Popular collections are 1. List 2. Tuple 3. Set 4. Dictionary# List # A
list can contrin heterogeneous items
In [29]:
batsmen = ['Rohit','Dhawan','Kohli','Rahane','Rayadu','Dhoni']
In [30]:
type(batsmen)
Out[30]:
list
In [31]:
batsmen[0]
Out[31]:
'Rohit'
In [32]:
batsmen[0:2]
Out[32]:
['Rohit', 'Dhawan']
In [33]:
batsmen[-1]
Out[33]:
'Dhoni'
In [34]:
batsmen[-2]
Out[34]:
'Rayadu'
In [35]:
Out[35]:
In [36]:
bowlers = ['Bumrah','Shami','Bhuvi','Kuldeep','Chahal']
In [37]:
In [38]:
print(all_players)
In [39]:
Out[39]:
True
In [40]:
Out[40]:
In [41]:
#Reversing a List
all_players.reverse()
print(all_players)
In [42]:
# Tuples Tuple is also a list, but is immutable. Once a tuple is created it cannot be modified. For,example a tuple
containing ODI player and his/her debut year.
In [43]:
In [44]:
type(odiDebut)
Out[44]:
tuple
In [45]:
odiDebut[0]
Out[45]:
'Kohli'
In [46]:
In [47]:
In [48]:
type(all_players)
Out[48]:
list
In [49]:
type(players)
Out[49]:
tuple
# Set # A set is a collection of unique elements (elements cannot repeat unlike a tuple or a list)
In [50]:
wc2011 = {'Dhoni','Sehwag','Tendulkar','Gambhir','Kohli','Raina','Yuvraj','Yusu
f'}
In [51]:
wc2015 = {'Dhoni','Dhawan','Rohit','Kohli','Vijay','Jadeja','Rahane'}
In [52]:
type(wc2011)
Out[52]:
set
In [53]:
In [54]:
{'Kohli', 'Dhoni'}
In [55]:
# Dictionary # Dictionary is a list of keys and values. All the keys in a dictionary are unique.
In [56]:
In [57]:
wcWinners[1983]
Out[57]:
'India'
In [58]:
wcWinners.values()
Out[58]:
set(wcWinners.values())
Out[59]:
In [60]:
wcWinners[2015] = 'Australia'
In [61]:
wcWinners
Out[61]:
In [62]:
# Declaring Strings
string0 = 'python'
string1 = "machine learning"
string2 = """This is a
multiline string"""
In [63]:
print(string0)
print(string1)
print(string2)
python
machine learning
This is a
multiline string
In [64]:
Out[64]:
'PYTHON'
In [65]:
Out[65]:
'python'
In [66]:
# Split Strings
tokens = string1.split(' ')
tokens
Out[66]:
['machine', 'learning']
# Functional Programming # A concept where a function is passed as a paramter to another function# Map
function
In [67]:
In [68]:
intList = [1,2,3,4,5,6,7,8,9]
In [69]:
In [70]:
type(squareList)
Out[70]:
map
In [71]:
list(squareList)
Out[71]:
# Normal way
squareList = []
for x in intList:
squareList.append(pow(x,2))
squareList
Out[72]:
# Anonymous function # Anonymous function is a function without a name and is defined using lambda keyword
In [73]:
In [74]:
list(squareList)
Out[74]:
# Filter Function
In [75]:
In [76]:
type(evenInts)
Out[76]:
filter
In [77]:
list(evenInts)
Out[77]:
[2, 4, 6, 8]
# Modules and Packages # A Module is a file that consists of functions, classes and variables. A set of modules
become a package. A module can be imported into another module (code).
In [78]:
#sqrt(16)
#will not work as module containing sqrt is not imported.
In [79]:
import math
math.sqrt(16)
Out[79]:
4.0
In [80]:
In [81]:
sample(range(0,11),3)
Out[81]:
[5, 3, 4]
In [82]:
randomList = sample(range(0,100),20)
randomList
Out[82]:
[86, 18, 89, 56, 53, 35, 28, 26, 98, 7, 54, 23, 94, 81, 8, 92, 36,
9, 49, 31]
In [83]:
In [84]:
def getMeanMedian(listNum):
return mean(listNum), median(listNum)
In [85]:
In [86]:
In [87]:
In [88]:
# create list
list_1 = [1,2,3,4]
list_2 = [1,2,3,4,'a','b','c']
print(type(list_1))
print(type(list_2))
print("")
print("_____________________")
print("")
print(list_1)
print(list_2)
<class 'list'>
<class 'list'>
_____________________
[1, 2, 3, 4]
[1, 2, 3, 4, 'a', 'b', 'c']
In [90]:
# create array
from numpy import array
array_1 = array([1,2,3,4])
array_2 = array([1,2,3,4,'a','b','c'])
print(type(array_1))
print(type(array_2))
print("")
print("_____________________")
print("")
print(array_1)
print(array_2)
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
_____________________
[1 2 3 4]
['1' '2' '3' '4' 'a' 'b' 'c']