SlideShare ist ein Scribd-Unternehmen logo
1 von 36
Python Basics
Data Science for Beginners, Session 2
Session 2: your 5-7 things
• What is Python?
• Ways to run Python code
• Variables and strings
• Python collections
• Getting inputs from outside
What is Python?
Python
• Programming language
• You write instructions to the computer
• Python “interpreter” runs those instructions
Python Code looks like this
For example...
• Open your terminal window, and type this:
ipython
1 + 2.5
print('hello world!')
exit()
4 Ways to Run Python
Code
Python in the Terminal Window
3 ways to run the python interpreter from the
terminal window:
• type ‘python’
• type ‘ipython’
• type ‘python helloworld.py’
iPython Notebooks
• browser-based (Chrome, Safari, Firefox etc)
• Can contain code (Python, R, etc)
• Can contain formatted notes
iPython Notebook
In the terminal window:
• ‘cd’ to the directory containing a .ipynb file
• Type “ipython notebook”
iPython Dashboard
Directories
‘New’
iPython file
iPython notebook: print view
Variables and Strings
First, Bugz!
Beware the quote characters! If you cut and paste code from text files (like
these slides), you might see one of these error messages:
“SyntaxError: Non-ASCII character 'xe2' in file helloworld.py on line 1”
"SyntaxError: invalid character in identifier"
This happens because the symbols “ and ” above aren’t the same as the ones
in your code editor. It’s annoying, but easily fixed: just delete them and type “
and ” in the right places in the editor.
Comments
# This is a comment
print('Hello World!') # this is a comment too
Variables
my_string = 'Hello World!'
my_boolean = True
my_number = 10
type(my_number)
my_number = 15.523
Strings
my_string = 'Hello World!'
len(my_string)
my_string[3]
Functions
my_string = 'Hello World!'
stringlength = len(my_string)
lowstring = my_string.lower()
print('My number is {}. And btw {}'.format(15.2, lowstring))
Writing your own functions
def my_function(my_text):
new_text = my_text + 'bananas'
return new_text
new_sentence = my_function('sara likes ')
print(new_sentence)
Python collections
Lists
rowvals = [1, 3, 5, 6, 4, 7, 3, 1, 3]
rowvals[3]
max(rowvals)
Inplace Functions
rowvals = [1, 3, 5, 6, 4, 7, 3, 1, 3]
print('{}'.format(rowvals))
rowvals.sort()
print('{}'.format(rowvals))
Iterators
alist = [1,2,3,4]
for item in alist:
print(item)
print(item+2)
print(“I'm done now”)
Dictionaries
iso3166 = {'SLE': 'Sierra Leone', 'NGA': 'Nigeria', 'LBR': 'Liberia' }
iso3166['LBR']
iso3166.keys()
'NGA' in iso3166
'USA' in iso3166
Dictionary Iterators
iso3166 = {'SLE': 'Sierra Leone', 'NGA': 'Nigeria', 'LBR': 'Liberia' }
for key, val in iso3166.items():
print('The key is: {}'.format(key))
print('The value for this key is: {}'.format(val))
Getting input from
outside
Getting input from the user
user_text = input('Give me some text> ')
lower_text = user_text.lower()
text_length = len(user_text)
print('Your text is {}, its length is {}'.format(user_text, text_length))
Libraries
• Pieces of code that do something you need
–e.g. the CSV library helps you read and write CSVs
• To include a library, use this in your code:
import libraryname
Getting input from a CSV file
import csv
fin = open('example_data/ebola-data-db-format.csv', 'r')
csvin = csv.reader(fin)
headers = next(csvin)
for row in csvin:
print(‘{}’.format(row))
fin.close()
Conditionals
import csv
fin = open('example_data/ebola-data-db-format.csv', 'r')
csvin = csv.reader(fin)
for row in csvin:
if row[1] == 'Liberia':
print('Found a {} datapoint about Liberia!'.format(row[2]))
fin.close()
More Help with Python
http://learnpythonthehardway.org/book/
Lots of other suggestions in the “course reading list” file
(google folder “Reference”)
Exercises
iPython Notebook
In the terminal window:
• ‘cd’ to the directory containing the code
example files (.ipynb files)
• Type “ipython notebook”
• Run each code cell in the example files
(optional) Reading CSVs
If you already know Python and iPython:
Find a variety of CSV files; try reading each of them into python, and see if you
get any errors or strange behaviours. Bonus points if you find CSV files
containing accents or multiple languages.

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonKHNOG
 
201705 metaprogramming in julia
201705 metaprogramming in julia201705 metaprogramming in julia
201705 metaprogramming in julia岳華 杜
 
Python - File operations & Data parsing
Python - File operations & Data parsingPython - File operations & Data parsing
Python - File operations & Data parsingFelix Z. Hoffmann
 
Python-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming LanguageRohan Gupta
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MoreMatt Harrison
 
Python for-unix-and-linux-system-administration
Python for-unix-and-linux-system-administrationPython for-unix-and-linux-system-administration
Python for-unix-and-linux-system-administrationVictor Marcelino
 
What's New in PHP 5.5
What's New in PHP 5.5What's New in PHP 5.5
What's New in PHP 5.5Corey Ballou
 
4 b file-io-if-then-else
4 b file-io-if-then-else4 b file-io-if-then-else
4 b file-io-if-then-elseMalik Alig
 
From 0 to mine sweeper in pyside
From 0 to mine sweeper in pysideFrom 0 to mine sweeper in pyside
From 0 to mine sweeper in pysideDinesh Manajipet
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)Matt Harrison
 
Unix And C
Unix And CUnix And C
Unix And CDr.Ravi
 
Getting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGetting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGDSCKYAMBOGO
 
File handling in C
File handling in CFile handling in C
File handling in CRabin BK
 
Turning Your Iterators Up to 11: New Features for Complex Iterator Implementa...
Turning Your Iterators Up to 11: New Features for Complex Iterator Implementa...Turning Your Iterators Up to 11: New Features for Complex Iterator Implementa...
Turning Your Iterators Up to 11: New Features for Complex Iterator Implementa...Accumulo Summit
 
Wildcards, Simple Shell Programs and Shell Variables
Wildcards, Simple Shell Programs and Shell VariablesWildcards, Simple Shell Programs and Shell Variables
Wildcards, Simple Shell Programs and Shell VariablesGaurav Bisht
 
Using Unix
Using UnixUsing Unix
Using UnixDr.Ravi
 
[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output StreamGhadeer AlHasan
 

Was ist angesagt? (20)

Workshop programs
Workshop programsWorkshop programs
Workshop programs
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
201705 metaprogramming in julia
201705 metaprogramming in julia201705 metaprogramming in julia
201705 metaprogramming in julia
 
Python - File operations & Data parsing
Python - File operations & Data parsingPython - File operations & Data parsing
Python - File operations & Data parsing
 
Python-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming Language
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
Python for-unix-and-linux-system-administration
Python for-unix-and-linux-system-administrationPython for-unix-and-linux-system-administration
Python for-unix-and-linux-system-administration
 
What's New in PHP 5.5
What's New in PHP 5.5What's New in PHP 5.5
What's New in PHP 5.5
 
4 b file-io-if-then-else
4 b file-io-if-then-else4 b file-io-if-then-else
4 b file-io-if-then-else
 
From 0 to mine sweeper in pyside
From 0 to mine sweeper in pysideFrom 0 to mine sweeper in pyside
From 0 to mine sweeper in pyside
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)
 
Unix And C
Unix And CUnix And C
Unix And C
 
Getting started in Python presentation by Laban K
Getting started in Python presentation by Laban KGetting started in Python presentation by Laban K
Getting started in Python presentation by Laban K
 
File handling in C
File handling in CFile handling in C
File handling in C
 
Turning Your Iterators Up to 11: New Features for Complex Iterator Implementa...
Turning Your Iterators Up to 11: New Features for Complex Iterator Implementa...Turning Your Iterators Up to 11: New Features for Complex Iterator Implementa...
Turning Your Iterators Up to 11: New Features for Complex Iterator Implementa...
 
File in C language
File in C languageFile in C language
File in C language
 
Wildcards, Simple Shell Programs and Shell Variables
Wildcards, Simple Shell Programs and Shell VariablesWildcards, Simple Shell Programs and Shell Variables
Wildcards, Simple Shell Programs and Shell Variables
 
Using Unix
Using UnixUsing Unix
Using Unix
 
[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream[Java] #7 - Input & Output Stream
[Java] #7 - Input & Output Stream
 

Andere mochten auch

Potencial De Membrana Plasmatica
Potencial De Membrana PlasmaticaPotencial De Membrana Plasmatica
Potencial De Membrana PlasmaticaSobeida J Machado C
 
Measure of safety culture
Measure of safety cultureMeasure of safety culture
Measure of safety cultureSalim Solanki
 
Опис досвіду роботи
Опис досвіду роботиОпис досвіду роботи
Опис досвіду роботи20022017
 
Session 10 handling bigger data
Session 10 handling bigger dataSession 10 handling bigger data
Session 10 handling bigger dataSara-Jayne Terp
 
Female faculty members awareness about retirement planning avenues
Female faculty members   awareness about retirement planning avenuesFemale faculty members   awareness about retirement planning avenues
Female faculty members awareness about retirement planning avenuesDr. Gargi Pant Shukla
 
Decálogo de las férulas miorrelajantes
Decálogo de las férulas miorrelajantesDecálogo de las férulas miorrelajantes
Decálogo de las férulas miorrelajantesDavid Isla
 
0610 w16 qp_42
0610 w16 qp_420610 w16 qp_42
0610 w16 qp_42Omniya Jay
 

Andere mochten auch (11)

Potencial De Membrana Plasmatica
Potencial De Membrana PlasmaticaPotencial De Membrana Plasmatica
Potencial De Membrana Plasmatica
 
Resume
ResumeResume
Resume
 
Encuesta de Salarios
Encuesta de SalariosEncuesta de Salarios
Encuesta de Salarios
 
Measure of safety culture
Measure of safety cultureMeasure of safety culture
Measure of safety culture
 
Опис досвіду роботи
Опис досвіду роботиОпис досвіду роботи
Опис досвіду роботи
 
Session 10 handling bigger data
Session 10 handling bigger dataSession 10 handling bigger data
Session 10 handling bigger data
 
Female faculty members awareness about retirement planning avenues
Female faculty members   awareness about retirement planning avenuesFemale faculty members   awareness about retirement planning avenues
Female faculty members awareness about retirement planning avenues
 
Final gallery
Final galleryFinal gallery
Final gallery
 
Decálogo de las férulas miorrelajantes
Decálogo de las férulas miorrelajantesDecálogo de las férulas miorrelajantes
Decálogo de las férulas miorrelajantes
 
Transportes do Brasil
Transportes do BrasilTransportes do Brasil
Transportes do Brasil
 
0610 w16 qp_42
0610 w16 qp_420610 w16 qp_42
0610 w16 qp_42
 

Ähnlich wie Session 02 python basics

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE Saraswathi Murugan
 
1B-Introduction_to_python.ppt
1B-Introduction_to_python.ppt1B-Introduction_to_python.ppt
1B-Introduction_to_python.pptAmritMarwaha1
 
python-an-introduction
python-an-introductionpython-an-introduction
python-an-introductionShrinivasan T
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutesSumit Raj
 
Coding in Kotlin with Arrow NIDC 2018
Coding in Kotlin with Arrow NIDC 2018Coding in Kotlin with Arrow NIDC 2018
Coding in Kotlin with Arrow NIDC 2018Garth Gilmour
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Learn Python 3 for absolute beginners
Learn Python 3 for absolute beginnersLearn Python 3 for absolute beginners
Learn Python 3 for absolute beginnersKingsleyAmankwa
 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!Fariz Darari
 
Python_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txPython_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txvishwanathgoudapatil1
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Simplilearn
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for BioinformaticsJosé Héctor Gálvez
 

Ähnlich wie Session 02 python basics (20)

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Pythonppt28 11-18
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
1B-Introduction_to_python.ppt
1B-Introduction_to_python.ppt1B-Introduction_to_python.ppt
1B-Introduction_to_python.ppt
 
python-an-introduction
python-an-introductionpython-an-introduction
python-an-introduction
 
python_class.pptx
python_class.pptxpython_class.pptx
python_class.pptx
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
 
Coding in Kotlin with Arrow NIDC 2018
Coding in Kotlin with Arrow NIDC 2018Coding in Kotlin with Arrow NIDC 2018
Coding in Kotlin with Arrow NIDC 2018
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Basic use of Python
Basic use of PythonBasic use of Python
Basic use of Python
 
Learn Python 3 for absolute beginners
Learn Python 3 for absolute beginnersLearn Python 3 for absolute beginners
Learn Python 3 for absolute beginners
 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
 
Python_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txPython_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. tx
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
Biopython: Overview, State of the Art and Outlook
Biopython: Overview, State of the Art and OutlookBiopython: Overview, State of the Art and Outlook
Biopython: Overview, State of the Art and Outlook
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Introduction to Python for Bioinformatics
Introduction to Python for BioinformaticsIntroduction to Python for Bioinformatics
Introduction to Python for Bioinformatics
 
Python slide
Python slidePython slide
Python slide
 

Mehr von Sara-Jayne Terp

Distributed defense against disinformation: disinformation risk management an...
Distributed defense against disinformation: disinformation risk management an...Distributed defense against disinformation: disinformation risk management an...
Distributed defense against disinformation: disinformation risk management an...Sara-Jayne Terp
 
Risk, SOCs, and mitigations: cognitive security is coming of age
Risk, SOCs, and mitigations: cognitive security is coming of ageRisk, SOCs, and mitigations: cognitive security is coming of age
Risk, SOCs, and mitigations: cognitive security is coming of ageSara-Jayne Terp
 
disinformation risk management: leveraging cyber security best practices to s...
disinformation risk management: leveraging cyber security best practices to s...disinformation risk management: leveraging cyber security best practices to s...
disinformation risk management: leveraging cyber security best practices to s...Sara-Jayne Terp
 
Cognitive security: all the other things
Cognitive security: all the other thingsCognitive security: all the other things
Cognitive security: all the other thingsSara-Jayne Terp
 
The Business(es) of Disinformation
The Business(es) of DisinformationThe Business(es) of Disinformation
The Business(es) of DisinformationSara-Jayne Terp
 
2021-05-SJTerp-AMITT_disinfoSoc-umaryland
2021-05-SJTerp-AMITT_disinfoSoc-umaryland2021-05-SJTerp-AMITT_disinfoSoc-umaryland
2021-05-SJTerp-AMITT_disinfoSoc-umarylandSara-Jayne Terp
 
2021 IWC presentation: Risk, SOCs and Mitigations: Cognitive Security is Comi...
2021 IWC presentation: Risk, SOCs and Mitigations: Cognitive Security is Comi...2021 IWC presentation: Risk, SOCs and Mitigations: Cognitive Security is Comi...
2021 IWC presentation: Risk, SOCs and Mitigations: Cognitive Security is Comi...Sara-Jayne Terp
 
2021-02-10_CogSecCollab_UBerkeley
2021-02-10_CogSecCollab_UBerkeley2021-02-10_CogSecCollab_UBerkeley
2021-02-10_CogSecCollab_UBerkeleySara-Jayne Terp
 
Using AMITT and ATT&CK frameworks
Using AMITT and ATT&CK frameworksUsing AMITT and ATT&CK frameworks
Using AMITT and ATT&CK frameworksSara-Jayne Terp
 
2020 12 nyu-workshop_cog_sec
2020 12 nyu-workshop_cog_sec2020 12 nyu-workshop_cog_sec
2020 12 nyu-workshop_cog_secSara-Jayne Terp
 
2019 11 terp_mansonbulletproof_master copy
2019 11 terp_mansonbulletproof_master copy2019 11 terp_mansonbulletproof_master copy
2019 11 terp_mansonbulletproof_master copySara-Jayne Terp
 
BSidesLV 2018 talk: social engineering at scale, a community guide
BSidesLV 2018 talk: social engineering at scale, a community guideBSidesLV 2018 talk: social engineering at scale, a community guide
BSidesLV 2018 talk: social engineering at scale, a community guideSara-Jayne Terp
 
Social engineering at scale
Social engineering at scaleSocial engineering at scale
Social engineering at scaleSara-Jayne Terp
 
engineering misinformation
engineering misinformationengineering misinformation
engineering misinformationSara-Jayne Terp
 
Online misinformation: they're coming for our brainz now
Online misinformation: they're coming for our brainz nowOnline misinformation: they're coming for our brainz now
Online misinformation: they're coming for our brainz nowSara-Jayne Terp
 
Sj terp ciwg_nyc2017_credibility_belief
Sj terp ciwg_nyc2017_credibility_beliefSj terp ciwg_nyc2017_credibility_belief
Sj terp ciwg_nyc2017_credibility_beliefSara-Jayne Terp
 
Belief: learning about new problems from old things
Belief: learning about new problems from old thingsBelief: learning about new problems from old things
Belief: learning about new problems from old thingsSara-Jayne Terp
 
risks and mitigations of releasing data
risks and mitigations of releasing datarisks and mitigations of releasing data
risks and mitigations of releasing dataSara-Jayne Terp
 
Session 09 learning relationships.pptx
Session 09 learning relationships.pptxSession 09 learning relationships.pptx
Session 09 learning relationships.pptxSara-Jayne Terp
 

Mehr von Sara-Jayne Terp (20)

Distributed defense against disinformation: disinformation risk management an...
Distributed defense against disinformation: disinformation risk management an...Distributed defense against disinformation: disinformation risk management an...
Distributed defense against disinformation: disinformation risk management an...
 
Risk, SOCs, and mitigations: cognitive security is coming of age
Risk, SOCs, and mitigations: cognitive security is coming of ageRisk, SOCs, and mitigations: cognitive security is coming of age
Risk, SOCs, and mitigations: cognitive security is coming of age
 
disinformation risk management: leveraging cyber security best practices to s...
disinformation risk management: leveraging cyber security best practices to s...disinformation risk management: leveraging cyber security best practices to s...
disinformation risk management: leveraging cyber security best practices to s...
 
Cognitive security: all the other things
Cognitive security: all the other thingsCognitive security: all the other things
Cognitive security: all the other things
 
The Business(es) of Disinformation
The Business(es) of DisinformationThe Business(es) of Disinformation
The Business(es) of Disinformation
 
2021-05-SJTerp-AMITT_disinfoSoc-umaryland
2021-05-SJTerp-AMITT_disinfoSoc-umaryland2021-05-SJTerp-AMITT_disinfoSoc-umaryland
2021-05-SJTerp-AMITT_disinfoSoc-umaryland
 
2021 IWC presentation: Risk, SOCs and Mitigations: Cognitive Security is Comi...
2021 IWC presentation: Risk, SOCs and Mitigations: Cognitive Security is Comi...2021 IWC presentation: Risk, SOCs and Mitigations: Cognitive Security is Comi...
2021 IWC presentation: Risk, SOCs and Mitigations: Cognitive Security is Comi...
 
2021-02-10_CogSecCollab_UBerkeley
2021-02-10_CogSecCollab_UBerkeley2021-02-10_CogSecCollab_UBerkeley
2021-02-10_CogSecCollab_UBerkeley
 
Using AMITT and ATT&CK frameworks
Using AMITT and ATT&CK frameworksUsing AMITT and ATT&CK frameworks
Using AMITT and ATT&CK frameworks
 
2020 12 nyu-workshop_cog_sec
2020 12 nyu-workshop_cog_sec2020 12 nyu-workshop_cog_sec
2020 12 nyu-workshop_cog_sec
 
2020 09-01 disclosure
2020 09-01 disclosure2020 09-01 disclosure
2020 09-01 disclosure
 
2019 11 terp_mansonbulletproof_master copy
2019 11 terp_mansonbulletproof_master copy2019 11 terp_mansonbulletproof_master copy
2019 11 terp_mansonbulletproof_master copy
 
BSidesLV 2018 talk: social engineering at scale, a community guide
BSidesLV 2018 talk: social engineering at scale, a community guideBSidesLV 2018 talk: social engineering at scale, a community guide
BSidesLV 2018 talk: social engineering at scale, a community guide
 
Social engineering at scale
Social engineering at scaleSocial engineering at scale
Social engineering at scale
 
engineering misinformation
engineering misinformationengineering misinformation
engineering misinformation
 
Online misinformation: they're coming for our brainz now
Online misinformation: they're coming for our brainz nowOnline misinformation: they're coming for our brainz now
Online misinformation: they're coming for our brainz now
 
Sj terp ciwg_nyc2017_credibility_belief
Sj terp ciwg_nyc2017_credibility_beliefSj terp ciwg_nyc2017_credibility_belief
Sj terp ciwg_nyc2017_credibility_belief
 
Belief: learning about new problems from old things
Belief: learning about new problems from old thingsBelief: learning about new problems from old things
Belief: learning about new problems from old things
 
risks and mitigations of releasing data
risks and mitigations of releasing datarisks and mitigations of releasing data
risks and mitigations of releasing data
 
Session 09 learning relationships.pptx
Session 09 learning relationships.pptxSession 09 learning relationships.pptx
Session 09 learning relationships.pptx
 

Kürzlich hochgeladen

办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一fhwihughh
 
Predicting Salary Using Data Science: A Comprehensive Analysis.pdf
Predicting Salary Using Data Science: A Comprehensive Analysis.pdfPredicting Salary Using Data Science: A Comprehensive Analysis.pdf
Predicting Salary Using Data Science: A Comprehensive Analysis.pdfBoston Institute of Analytics
 
2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSING
2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSING2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSING
2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSINGmarianagonzalez07
 
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...limedy534
 
While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in collegessuser7a7cd61
 
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...dajasot375
 
GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]📊 Markus Baersch
 
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)jennyeacort
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...Florian Roscheck
 
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDINTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDRafezzaman
 
Predictive Analysis for Loan Default Presentation : Data Analysis Project PPT
Predictive Analysis for Loan Default  Presentation : Data Analysis Project PPTPredictive Analysis for Loan Default  Presentation : Data Analysis Project PPT
Predictive Analysis for Loan Default Presentation : Data Analysis Project PPTBoston Institute of Analytics
 
Top 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In QueensTop 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In Queensdataanalyticsqueen03
 
Learn How Data Science Changes Our World
Learn How Data Science Changes Our WorldLearn How Data Science Changes Our World
Learn How Data Science Changes Our WorldEduminds Learning
 
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝DelhiRS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhijennyeacort
 
DBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdfDBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdfJohn Sterrett
 
Heart Disease Classification Report: A Data Analysis Project
Heart Disease Classification Report: A Data Analysis ProjectHeart Disease Classification Report: A Data Analysis Project
Heart Disease Classification Report: A Data Analysis ProjectBoston Institute of Analytics
 
Student profile product demonstration on grades, ability, well-being and mind...
Student profile product demonstration on grades, ability, well-being and mind...Student profile product demonstration on grades, ability, well-being and mind...
Student profile product demonstration on grades, ability, well-being and mind...Seán Kennedy
 
Semantic Shed - Squashing and Squeezing.pptx
Semantic Shed - Squashing and Squeezing.pptxSemantic Shed - Squashing and Squeezing.pptx
Semantic Shed - Squashing and Squeezing.pptxMike Bennett
 
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改yuu sss
 

Kürzlich hochgeladen (20)

Call Girls in Saket 99530🔝 56974 Escort Service
Call Girls in Saket 99530🔝 56974 Escort ServiceCall Girls in Saket 99530🔝 56974 Escort Service
Call Girls in Saket 99530🔝 56974 Escort Service
 
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
办理学位证纽约大学毕业证(NYU毕业证书)原版一比一
 
Predicting Salary Using Data Science: A Comprehensive Analysis.pdf
Predicting Salary Using Data Science: A Comprehensive Analysis.pdfPredicting Salary Using Data Science: A Comprehensive Analysis.pdf
Predicting Salary Using Data Science: A Comprehensive Analysis.pdf
 
2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSING
2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSING2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSING
2006_GasProcessing_HB (1).pdf HYDROCARBON PROCESSING
 
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
Effects of Smartphone Addiction on the Academic Performances of Grades 9 to 1...
 
While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in college
 
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
Indian Call Girls in Abu Dhabi O5286O24O8 Call Girls in Abu Dhabi By Independ...
 
GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]GA4 Without Cookies [Measure Camp AMS]
GA4 Without Cookies [Measure Camp AMS]
 
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
Call Us ➥97111√47426🤳Call Girls in Aerocity (Delhi NCR)
 
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...From idea to production in a day – Leveraging Azure ML and Streamlit to build...
From idea to production in a day – Leveraging Azure ML and Streamlit to build...
 
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTDINTERNSHIP ON PURBASHA COMPOSITE TEX LTD
INTERNSHIP ON PURBASHA COMPOSITE TEX LTD
 
Predictive Analysis for Loan Default Presentation : Data Analysis Project PPT
Predictive Analysis for Loan Default  Presentation : Data Analysis Project PPTPredictive Analysis for Loan Default  Presentation : Data Analysis Project PPT
Predictive Analysis for Loan Default Presentation : Data Analysis Project PPT
 
Top 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In QueensTop 5 Best Data Analytics Courses In Queens
Top 5 Best Data Analytics Courses In Queens
 
Learn How Data Science Changes Our World
Learn How Data Science Changes Our WorldLearn How Data Science Changes Our World
Learn How Data Science Changes Our World
 
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝DelhiRS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
RS 9000 Call In girls Dwarka Mor (DELHI)⇛9711147426🔝Delhi
 
DBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdfDBA Basics: Getting Started with Performance Tuning.pdf
DBA Basics: Getting Started with Performance Tuning.pdf
 
Heart Disease Classification Report: A Data Analysis Project
Heart Disease Classification Report: A Data Analysis ProjectHeart Disease Classification Report: A Data Analysis Project
Heart Disease Classification Report: A Data Analysis Project
 
Student profile product demonstration on grades, ability, well-being and mind...
Student profile product demonstration on grades, ability, well-being and mind...Student profile product demonstration on grades, ability, well-being and mind...
Student profile product demonstration on grades, ability, well-being and mind...
 
Semantic Shed - Squashing and Squeezing.pptx
Semantic Shed - Squashing and Squeezing.pptxSemantic Shed - Squashing and Squeezing.pptx
Semantic Shed - Squashing and Squeezing.pptx
 
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
专业一比一美国俄亥俄大学毕业证成绩单pdf电子版制作修改
 

Session 02 python basics

  • 1. Python Basics Data Science for Beginners, Session 2
  • 2. Session 2: your 5-7 things • What is Python? • Ways to run Python code • Variables and strings • Python collections • Getting inputs from outside
  • 4. Python • Programming language • You write instructions to the computer • Python “interpreter” runs those instructions
  • 5. Python Code looks like this
  • 6. For example... • Open your terminal window, and type this: ipython 1 + 2.5 print('hello world!') exit()
  • 7. 4 Ways to Run Python Code
  • 8. Python in the Terminal Window 3 ways to run the python interpreter from the terminal window: • type ‘python’ • type ‘ipython’ • type ‘python helloworld.py’
  • 9. iPython Notebooks • browser-based (Chrome, Safari, Firefox etc) • Can contain code (Python, R, etc) • Can contain formatted notes
  • 10. iPython Notebook In the terminal window: • ‘cd’ to the directory containing a .ipynb file • Type “ipython notebook”
  • 13.
  • 16. First, Bugz! Beware the quote characters! If you cut and paste code from text files (like these slides), you might see one of these error messages: “SyntaxError: Non-ASCII character 'xe2' in file helloworld.py on line 1” "SyntaxError: invalid character in identifier" This happens because the symbols “ and ” above aren’t the same as the ones in your code editor. It’s annoying, but easily fixed: just delete them and type “ and ” in the right places in the editor.
  • 17. Comments # This is a comment print('Hello World!') # this is a comment too
  • 18. Variables my_string = 'Hello World!' my_boolean = True my_number = 10 type(my_number) my_number = 15.523
  • 19. Strings my_string = 'Hello World!' len(my_string) my_string[3]
  • 20. Functions my_string = 'Hello World!' stringlength = len(my_string) lowstring = my_string.lower() print('My number is {}. And btw {}'.format(15.2, lowstring))
  • 21. Writing your own functions def my_function(my_text): new_text = my_text + 'bananas' return new_text new_sentence = my_function('sara likes ') print(new_sentence)
  • 23. Lists rowvals = [1, 3, 5, 6, 4, 7, 3, 1, 3] rowvals[3] max(rowvals)
  • 24. Inplace Functions rowvals = [1, 3, 5, 6, 4, 7, 3, 1, 3] print('{}'.format(rowvals)) rowvals.sort() print('{}'.format(rowvals))
  • 25. Iterators alist = [1,2,3,4] for item in alist: print(item) print(item+2) print(“I'm done now”)
  • 26. Dictionaries iso3166 = {'SLE': 'Sierra Leone', 'NGA': 'Nigeria', 'LBR': 'Liberia' } iso3166['LBR'] iso3166.keys() 'NGA' in iso3166 'USA' in iso3166
  • 27. Dictionary Iterators iso3166 = {'SLE': 'Sierra Leone', 'NGA': 'Nigeria', 'LBR': 'Liberia' } for key, val in iso3166.items(): print('The key is: {}'.format(key)) print('The value for this key is: {}'.format(val))
  • 29. Getting input from the user user_text = input('Give me some text> ') lower_text = user_text.lower() text_length = len(user_text) print('Your text is {}, its length is {}'.format(user_text, text_length))
  • 30. Libraries • Pieces of code that do something you need –e.g. the CSV library helps you read and write CSVs • To include a library, use this in your code: import libraryname
  • 31. Getting input from a CSV file import csv fin = open('example_data/ebola-data-db-format.csv', 'r') csvin = csv.reader(fin) headers = next(csvin) for row in csvin: print(‘{}’.format(row)) fin.close()
  • 32. Conditionals import csv fin = open('example_data/ebola-data-db-format.csv', 'r') csvin = csv.reader(fin) for row in csvin: if row[1] == 'Liberia': print('Found a {} datapoint about Liberia!'.format(row[2])) fin.close()
  • 33. More Help with Python http://learnpythonthehardway.org/book/ Lots of other suggestions in the “course reading list” file (google folder “Reference”)
  • 35. iPython Notebook In the terminal window: • ‘cd’ to the directory containing the code example files (.ipynb files) • Type “ipython notebook” • Run each code cell in the example files
  • 36. (optional) Reading CSVs If you already know Python and iPython: Find a variety of CSV files; try reading each of them into python, and see if you get any errors or strange behaviours. Bonus points if you find CSV files containing accents or multiple languages.

Hinweis der Redaktion

  1. Today we’re looking at a programming language that’s used a lot by data scientists (and that many of the code examples will be written in). Some of the example code in the rest of these sessions will be in Python, so it will help for you to be able to read and understand what’s happening in that code.
  2. So let’s begin. Here are the 6 things we’ll talk about today.
  3. Before we talk about python, it helps to define it a bit.
  4. See http://learnpythonthehardway.org/book/ and https://www.python.org/ for way more about Python.
  5. We’ll cover the basics of Python in this session. The aim is to a) get you some useful tools, and b) not have you scared by something that looks like this. The toolset for this course (Python, R, offline tools) was chosen so you can still do something useful when you have no internet / have low bandwidth. There are many other tools out there if you have the bandwidth to run then, but at some point in your career you’ll find yourself somewhere like Arusha in Tanzania, desperately hoping that the page you need will load. We’ve based this toolkit on trying to minimise that experience. Plus it’s cool being able to do things for yourself!
  6. That was your first python code. You opened up the ipython interpreter, then typed in ‘commands’ (‘1+2’) and got back outputs (‘3’). Then, because we’re tidy, you closed the python interpreter again. We met several important things here. You met objects: “1” and “2.5” are numbers (“1” is an integer number; “2.5” is a floating point number); and “‘hello world!’” is a string. You also met an operator: “+” and a function: print(). * Operators do basic things to pairs of objects (or sometimes to single objects). For instance, “+” adds together the objects to the left and right of it. You’ll meet arthmetic operators (+ add, - subtract, * multiply, / divide) and logical operators (of which more soon). * Functions are pieces of pre-written code that (usually) do something that needs to be done often, like sending a friendly message.
  7. So you have some Python code - maybe written in these slides, maybe in a .py or .ipynb file. Let’s look at some of the ways you can run that code.
  8. ‘python’ runs the python interpreter. ‘ipython’ runs a version of the python interpeter that’s slightly friendlier to new users, e.g. it has better help. ‘python helloworld.py’ runs the python interpreter on a file called ‘helloworld.py’. If that file contains a set of python commands (e.g. “print(“Hello World!”)”), you’ll see the output of those commands. You can do the same thing with ipython, e.g. ‘ipython helloworld.py’. There’s a file called helloworld.py in your course notes. Try running it, then editing it (any text editor will do, although some, like Sublimetext, are set up to point out any coding errors to you), and running it again. There are other ways to run Python code (e.g. from another program), but we won’t be doing that in this course.
  9. Ipython notebooks are files that contain both formatted text and code; depending on how you set up your notebooks, they can run code written in Python, R or several other languages.
  10. All the code examples (both Python and R) for this course are in iPython notebooks, so you’ll need to know how to open one. cd (“change directory”) is the terminal window command to change directory. “cd ~” takes you to your ‘top’ directory, where typing “ls” (mac) or “dir” (windows) will show you directories like Desktop, Downloads or Documents. “cd dir1/dir2/dir3” takes you ‘down’ directories, to dir3 which is below dir2 which is below dir1. This is the terminal equivalent of starting in one directory, then clicking on dir1, dir2 then dir3. “cd ..” takes you ‘up’ directories: for instance, “cd ..” in dir3 will take you to dir2. “pwd” (mac) or “dir” (windows) will show you which directory you are in at the moment. If you get lost, “cd ~”.
  11. iPython starts with the Dashboard view. This lists all the files in the directory that you called iPython from, including directories. If you accidentally delete this view, open a web browser and type “localhost:8888” in the address window to get back to it. Things you need to know about in here: The “New” button on the top right hand side. Click on this, then “Python 3”, to create a new iPython notebook file. The file listing. Click on any file or directory to open it. The current directory (the grey bar above the files list): click on this to go back up from a directory.
  12. And this is what you see when you open an iPython file. The grey boxes are called ‘cells’. You create a new cell by clicking ‘Insert’ on the top menu. You change the cell type (to ‘Markdown’, or ‘Code’) by clicking the box that currently says ‘Code’ You run a cell by clicking in the cell, then clicking ‘cell’ -> ‘run cells’. You change your file’s name by clicking the name to the right of jupyter You save your shiny new file by clicking ‘File’ -> ‘Save and Checkpoint’.
  13. Don’t panic if your notebook looks like this when you open it. iPython has helpfully converted your markup cells into the way you’d see them if you printed the notebook. To edit any of these cells, click in the cell (you should then see the markdown code, ready to edit).
  14. Variables are one of the basic building blocks of Python code. We’ll look at some of these - what they look like, what they can do.
  15. But before we start, let’s talk about bugs. Bugs are errors that either stop your code from running, or make it run in ways that you weren’t expecting. You will meet many bugs when you’re coding. Don’t let them scare you: dealing with bugs is just one of the features of coding. You can do things to make this easier: for instance, if you use an editor like sublimetext to write your code, it has handy features like changing the colour of your code when you write something incorrectly. do this…
  16. Coders leave messages for each other (and themselves) in their code: these are called comments. They’re there for humans to read, and are completely ignored by the python interpreter. The comments you’ll see in this course are mostly the ones that start with the ‘#’ symbol. Everything from the ‘#’ to the end of the line it’s on is a comment. You *might* see magic comments in python files, e.g. #!/usr/bin/python # -*- coding: utf-8 -*- These tell the interpreter which type of file this is (python), and which character set it uses (remember the problem with ‘“‘ earlier?). utf-8 is a very commonly-used character set.
  17. Variables are places where you put objects that you don’t want to keep typing out. You do this because you don’t have to keep typing “Hello World” when you use it several times in your code it’s easier to read your code and see what’s going on it’s harder to make mistakes (e.g. if you put “10” everywhere in your code, and change your mind, then you might change some but not all of those “10”s to “11s”… if you put x=10 and then use x everywhere, you only have to change one thing). Variables have “types” that tell the interpreter what can be done with them (e.g. you can multiply numbers together, but you can’t do that with strings). Here are some common variable types: String: a set of characters, which could be letters, numbers or symbols. Strings can be as long as you like - in some datasets (e.g. reading in book texts) you’ll see strings thousands of characters long. Boolean: can be either True or False. Useful for when you want to do one thing if something is true (e.g. x == 10), and something else if it isn’t. Numbers: a number. This include integers (e.g. 10), and floating-point number (e.g. 15.523). Note how I reused the same variable name for two numbers. Try typing my_number = 10, then print(my_number), then my_number=15.523, then print(my_number) in ipython.
  18. Strings are a bit special. A string is made out of characters (e.g. “H” or “r”), so it makes sense to ask things like: len(string): how many characters are there in this string? my_string[4]: what’s the 5th character in this string? (NB python counts from 0, not 1, e.g. my_string[0] is H).
  19. Remember, functions are pieces of code that (often) do something that gets repeated lots. We already met the function “print()”. Here are some more functions. Functions generally have 3 parts: the function name (e.g. “len”), the function arguments (e.g. “my_string”) that tell the function what to do its thing on, and the the function return (e.g. stringlength), which is the variable (or variables) that the function puts its results into. You can use ‘string formatting’ to put other variables (numbers, other strings etc) into a string. Here, we’ve put a number (15.2) and a string (“Hello World!”) into a new string, and printed it. print(“{}”.format(x)) is very very useful for printing out more-complicated variables, where a simple print(x) will fail.
  20. You can write your own functions using the keyword “def”. Here, we’ve created a function (my_function) that takes an argument called my_text, adds some more text to it, puts that new text into variable new_text, and returns new_text to the person who called the function. Then we use the function. We call my_function with the argument “sara likes “: my_text is now set to “sara likes “ before we add “bananas” to it. The function returns “sara likes bananas”, which is put into the variable new_sentence.
  21. A collection is a group of python objects. We’re going to look at two collections here: lists, and dictionaries.
  22. A list is an ordered set of python objects. Here, rowvals is a list that contains numbers. Lists are ordered, e.g. rowvals[3] will always give you the 4th object in rowvals (currently “6”). This might seem wrong to you - you may be asking why it doesn’t give you the 3rd object in the list. The reason is that all counting in Python starts at zero, so the “indices” for the objects in this list are 0,1,2,3,4,5,6,7 and 8. You can’t use an index larger than the last index in the list: typing rowvals[9] will give you an error message. But you will sometimes see negative indices. rowvals[3] and max(rowvals) will both return an object to you, that you can ‘assign’ to a new variable.
  23. Some functions will change the object they’re applied to. list.sort() is one of these. rowvals.sort() changes the contents of rowvals itself. Try running this code to see how this happens.
  24. So sometimes you want to do something to every item in a list. Repeating the same command for alist[0], alist[1], alist[2] and alist[3] would be tiresome (and even more tiresome if you have 1000 items in your list), so we use iterators. An iterator (e.g. “for”) selects each item in a list in turn, and applies your code to it. For instance, in the code above, the line “for item in alist” selects each object in alist, calls that object “item” then runs the code “print(item)” on it. Note the 4 spaces before print(item). This is how Python groups code together: the spaces tell the Python interpreter that print(item) and print(item+2) are run on the items from alist, but “print(I’m done now)” isn’t. This can be very annoying at first, but makes sense after a while. The enumerate function can be very useful when you’re iterating over lists. This allows you to use both the index of an item, and the item in your loops. An example of this is: for index, item in enumerate(alist): print(“the list item at index {} is {}”.format(index, item))
  25. A python list is a collection that’s indexed by numbers (0,1,2,etc). A python dictionary is a container that’s indexed by anything you want to use. In this example, we’ve used ISO3166 country codes as indices, and the names of countries as the items in the list. Dictionaries are unordered, so iso3166[0] doesn’t make sense. But because we’ve created the indices SLE, NGA, LBR, we can use any of these to access the item connected with that index, e.g. iso3166[‘NGA’]. If we want to see all the indices (aka “keys”) in a dictionary, we use the “keys” function, e.g. iso3166.keys(). If we want to know if a key is in a dictionary, we can ask, for example using “‘NGA’ in iso3166”
  26. We can also iterate over dictionary keys, as seen here. Don’t forget those 4 spaces! Speaking of spaces… you’ll notice that I’ve added spaces here and there to make the code more readable. You can do this in most places, but there are code format rules (“style guides”) that Python coders follow so they don’t confuse each other - most Python coders use PEP8 https://www.python.org/dev/peps/pep-0008/ - which, amongst other things, tells coders to use 4 (not 1,2,3,5 or anything else) spaces as indents. Some text editors, like Sublime Text (https://www.sublimetext.com), have ways to switch on these rules so the text editor colour-highlights any time you’re breaking a rule.
  27. At some point, we’re going to need to pull data into our code: this might be input from the code’s user, or from a datafile, or from an API (application programming interface: more on that soon). Here’s how.
  28. You might want to ask the user for input (e.g. the name of the csv file they want your code to process). The function “input()” does this.
  29. First, a brief note about libraries. Places to look for libraries include: * https://docs.python.org/3/library/ (you already have these) * https://pypi.python.org/pypi
  30. Here, we’re using the Python library “CSV” to read in the contents of a CSV file. First, we need to tell our code to use the CSV library (“import CSV”) Then we tell it which file to open (“open()”), and that we’re reading from (not writing to) a file (“‘r’”). We’ve opened the file for input, but that’s not enough if we want to treat this file as a CSV file (instead of a text file, or Excel, json, xml etc). To do this, we create a CSV reader object, using “csv.reader()”. This object (that we’ve called “csvin”) knows about commands like “next()” (get me the next row of data from the csv, and put it into a list object), and that “for row in csvin” will loop over each remaining row in the CSV file, and input it as a list. The rest is grabbing each row in the CSV file, and printing out that row. When you’re done, fin.close() closes the link between this program and the file pointed at by the variable ‘fin’. Later in the course, you'll see other, shorter, ways to read in a CSV file (dictreader, and pandas.read_csv), but this is development data, and the CSV library can often read in difficult CSV files that other methods fail on.
  31. Sometimes we’ll want to process only some of the data that we see. In this case, we’re only interested in data about Liberia, so we test to see if the second entry in the row is ‘Liberia’. This test (if a == b) is called a conditional statement, because running the rows nested below the “if” statement (“nested” = using another 4 spaces, to show that the “print()” statement belongs to the “if” one) is conditional on whether the statement “row[1] == ‘Liberia’” is true. The conditions you’ll see in code include: a == b: a’s value is the same as b’s value a != b: a’s value is not the same as b’s value a < b: a is smaller than b a > b: a is bigger than b a<= b: a is smaller than or equal to b a >= b: a is bigger than or equal to b Beware the “==” in a conditional statement. “==” is used to test similarity; “=” is used to set the value of the thing on its left to the value of the thing on its right. Python will let you use either of these in a condition.
  32. We’ve just skimmed through the basics of Python - enough so you don’t get lost when I start showing example code. If you want to know more, there are lots of courses listed in the course reading list; IMHO the best of these is Jeff Knupp’s Learn Python the Hard Way (available online for free).
  33. Your exercises were all built into the class. But if you want more…
  34. The iPython notebooks (that you downloaded from github) are there for you to learn more about the subjects in each class. Go play with them: take copies, edit the code and see what happens.
  35. And make a list of those strange behaviours so we can talk about them in the next class.