Introduction-to-Python-Chapter-1-3-Functions-and-Packages
Introduction-to-Python-Chapter-1-3-Functions-and-Packages
Introduction to Python
Hugo Bowne-
Anderson
Data Scientist at DataCamp
Functions
• Nothing new!
• type()
• Piece of reusable code
• Solves particular task
• Call function instead of writing code yourself
Example
fam = [1.73, 1.68, 1.71, 1.89]
fam
[1.73, 1.68, 1.71, 1.89]
max(fam)
1.89
Example
fam = [1.73, 1.68, 1.71, 1.89]
fam
[1.73, 1.68, 1.71, 1.89]
max(fam)
1.89
Example
fam = [1.73, 1.68, 1.71, 1.89]
fam
[1.73, 1.68, 1.71, 1.89]
max(fam)
1.89
Example
fam = [1.73, 1.68, 1.71, 1.89]
fam
[1.73, 1.68, 1.71, 1.89]
max(fam)
1.89
tallest = max(fam)
tallest
1.89
round()
round(1.68, 1)
1.7
round(1.68)
• round(number)
• round(number, ndigits)
Find functions
• How to know?
• Standard task -> probably function exists!
• The internet is your friend
Questions?
Methods
INTRODUCTION TO PYTHON
Hugo Bowne-
Anderson
Data Scientist at DataCamp
Built-in Functions
• Maximum of list: max()
• Length of list or string: len()
• Get index in list: ?
• Reversing a list: ?
Back 2 Basics
sister = "liz"
height = 1.73
sister = "liz"
height = 1.73
sister = "liz"
height = 1.73
fam.count(1.68)
1
str methods
sister
'liz'
sister.capitalize()
'Liz'
sister.replace("z", "sa")
'lisa'
Methods
• Everything = object
• Object have methods associated, depending on type
sister.replace("z", "sa")
'lisa'
fam.replace("mom", "mommy")
fam.index("mom")
4
Methods (2)
fam
fam.append("me")
fam
fam.append(1.79)
fam
['liz', 1.73, 'emma', 1.68, 'mom', 1.71, 'dad', 1.89, 'me', 1.79]
Summary
Functions
type(fam)
list
6
Questions?
Packages
INTRODUCTION TO PYTHON
Hugo Bowne-
Anderson
Data Scientist at DataCamp
Motivation
• Functions and methods are powerful
• All code in Python distribution?
o Huge code base: messy
o Lots of code you won’t use
o Maintenance problem
Packages
• Directory of Python Scripts
• Each script = module
• Specify functions, methods, types
• Thousands of packages available
o NumPy
o Matplotlib
o Pandas
o scikit-learn
Install package
• http://pip.readthedocs.org/en/stable/installing/
• Download get-pip.py
• Terminal:
o python3 get-pip.py
numpy.array([1, 2, 3])
array([1, 2, 3])
np_fam = array(fam_ext)