SlideShare a Scribd company logo
1 of 32
Learn Python the Hard Way
Exercises 27 – 34
http://learnpythonthehardway.org/
New things in ex. 27–34
• Booleans: True, False, logic, operators
• if – elif – else: Note the relationship to True
and False
• loops: 2 kinds, for and while
• lists and how to
– create a new list
– add and delete things from lists
– find out what’s in a list
How the Boolean AND works
There is a very long bungee jump above a deep
river gorge in Africa. You say:
“If the bungee jump looks safe and it is cheap,
then I will do it.”
How the Boolean AND works
“If the bungee jump looks safe and it is cheap,
then I will do it.”
looks safe = False (you won’t do it)
is cheap = False (you won’t do it)
You’ll only do it if both conditions are TRUE.
How the Boolean OR works
There is a great party Tuesday night, but you are
in danger of failing your Wednesday test.
You say:
“If I finish studying in time or the test is
canceled, then I will go to the party.”
How the Boolean OR works
“If I finish studying in time or the test is
canceled, then I will go to the party.”
finish studying = True (can go)
test canceled = True (can go)
You can go if only one of the conditions is TRUE.
Or both. But one is enough.
and
True and True : True
True and False :
False
False and True :
False
False and False :
False
True or True : True
True or False : True
False or True : True
False or False : False
“If the bungee jump looks safe and it is cheap,
then I will do it.”
“If I finish studying in time or the test is canceled, then I
will go to the party.”
or
Boolean operators (symbols)
1 != 0
1 == (3 – 2)
5 >= 1
10 <= 100
1 != (3 – 2)
1 == 0
5 <= 1
10 >= 100
True
True
True
True
False
False
False
False
Exercise 28
if – elif – else
(if statements)
Exercises 29 and 30
Exercises 29 and 30
Exercise 30
Loops
Lists
Loops
• Every programming language has loops
• A loop typically runs over and over until
something makes it stop (different from a
usual function, which runs only once)
• The “for” loop is a standard kind of loop
• for-loops can appear inside a function
Exercise 32
Loops
• Standard syntax for starting a for-loop in
Python:
for fruit in fruits:
Exercise 32
Note that fruit could be any variable name, like x or a or cat.
In this case, there must already be a list named
fruits
(more about lists in a minute)
Loops
• Also standard syntax (but different) for
starting a for-loop in Python:
for i in range(0, 9):
Exercise 32
In this case, we don’t know the name of the list
yet. Or maybe this loop does not even use a list.
So, 2 different for-loops
for fruit in fruits:
print fruit
Exercise 32
for i in range(0, 9):
print "Hello!"
Like functions, loops must be indented. They can have many
lines. These are short just to make them simple.
while-loops
Exercise 33
• The “while” loop is another standard kind of
loop
• while-loops can appear inside a function
• If you can figure out how to do what you want
with a for-loop, then use a for-loop.
• If you must use a while-loop, be careful that it
will not run forever. If it does, it’s an infinite
loop (which is NOT good).
Lists
• In many languages, a “list” is called an “array”
(but Zed says we should say “list” for Python)
• Lists can be gigantic—there can be thousands
of items in one list, or none
• The standard format of a list in Python:
fruits = ['apples', 'oranges', 'pears',
'apricots']
Exercise 32
Note: If there are numbers in the list, they won’t have quotes around them.
Loops and Lists
These two for-loops do exactly the same thing:
fruits = ['apples', 'oranges', 'pears',
'apricots']
for fruit in fruits:
print "A fruit of type: %s" % fruit
for y in fruits:
print "A fruit of type: %s" % y
Exercise 32
Lists
• You actually already saw a list in Exercise 25,
when you did this:
words = stuff.split(' ')
• After that, words contained a list:
['All', 'good', 'things', 'come', 'to',
'those', 'who', 'wait.']
• You can use pop() and len() on any list
Exercise 32
Some things we do with lists
fruits.pop()
fruits.append("bananas")
fruits.extend(["plums", "mangoes"])
del fruits[2]
print fruits
With append() you can add only one item at a time to the list.
Exercises 32, 34
Items in lists
Exercise 34:
Items in lists can be counted.
Items in lists can be referenced by number, but the first
number is not 1 — it is 0.
Back to while-loops
• You might think the while-loops act a lot like
the for-loops that used range (and you would
be right)
• However, the while-loops are different
• The condition at the start of a while-loop
could test for something not numeric, such as
“while we are not yet at the end of the file”
• Note: for-loops are very common, and
while-loops are less so (as Zed says: “Usually a
for-loop is better”)
Exercise 33
Learning … while-loops
• You really need to play with a lot of the extra
credit or “study drills” in Exercise 33 to get this
into your brain
• I made four different .py files to test all the
comparisons that Zed recommends
• If you play with this, you can really understand
how for-loops and while-loops are different
Exercise 33
Zed’s Exercise 33
A word of advice
So Exercise 31 is long, but easy. You might feel
like now it’s all getting easy …
BUT WAIT! No, it’s not.
• Exercise 32 introduces the for-loop.
• Exercise 33 introduces the while-loop.
• Exercise 34 introduces how we navigate
through the elements in a list.
These last 3 exercises are QUITE challenging!
Indents in Python
• The usual way is to indent 4 spaces (not a tab
indent — actually type 4 spaces)
• If you accidentally type 3, or 5, or something
else, and all the others are 4, Python will
throw an error
• Most programming languages require multiple
levels of indents, and these levels (and the
format of indenting) are important, so take
care
An example of multiple
indent levels within a
Python program
Learn Python the Hard Way
Exercises 27 – 34
(now we know some stuff)

More Related Content

Similar to Learning Python - Week 4

Course Design Best Practices
Course Design Best PracticesCourse Design Best Practices
Course Design Best PracticesKeitaro Matsuoka
 
Brixton Library Technology Initiative Week1 Recap
Brixton Library Technology Initiative Week1 RecapBrixton Library Technology Initiative Week1 Recap
Brixton Library Technology Initiative Week1 RecapBasil Bibi
 
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdfProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdflailoesakhan
 
Learn python
Learn pythonLearn python
Learn pythonmocninja
 
Fuzzy mathematics:An application oriented introduction
Fuzzy mathematics:An application oriented introductionFuzzy mathematics:An application oriented introduction
Fuzzy mathematics:An application oriented introductionNagasuri Bala Venkateswarlu
 
Py4inf 05-iterations (1)
Py4inf 05-iterations (1)Py4inf 05-iterations (1)
Py4inf 05-iterations (1)karan saini
 
Py4inf 05-iterations (1)
Py4inf 05-iterations (1)Py4inf 05-iterations (1)
Py4inf 05-iterations (1)karan saini
 
Py4inf 05-iterations
Py4inf 05-iterationsPy4inf 05-iterations
Py4inf 05-iterationskaran saini
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 
Memory basics 1
Memory basics 1Memory basics 1
Memory basics 1cofritz
 
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdfProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdflailoesakhan
 
Introduction To Algorithms
Introduction To AlgorithmsIntroduction To Algorithms
Introduction To AlgorithmsSpotle.ai
 
Presentation phinney abrf 2019
Presentation phinney abrf 2019Presentation phinney abrf 2019
Presentation phinney abrf 2019UC Davis
 
Mixed Effects Models - Empirical Logit
Mixed Effects Models - Empirical LogitMixed Effects Models - Empirical Logit
Mixed Effects Models - Empirical LogitScott Fraundorf
 
powerpoint 1-19.pdf
powerpoint 1-19.pdfpowerpoint 1-19.pdf
powerpoint 1-19.pdfJuanPicasso7
 
Assignement2 - Three techniques to be a better learner
Assignement2  - Three techniques to be a better learnerAssignement2  - Three techniques to be a better learner
Assignement2 - Three techniques to be a better learnerAbdelkrim Berkous
 

Similar to Learning Python - Week 4 (20)

Course Design Best Practices
Course Design Best PracticesCourse Design Best Practices
Course Design Best Practices
 
Brixton Library Technology Initiative Week1 Recap
Brixton Library Technology Initiative Week1 RecapBrixton Library Technology Initiative Week1 Recap
Brixton Library Technology Initiative Week1 Recap
 
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdfProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
ProgPrinc_Lecture_3_Data_Structures_and_Iteration-2.pdf
 
Learn python
Learn pythonLearn python
Learn python
 
Fuzzy mathematics:An application oriented introduction
Fuzzy mathematics:An application oriented introductionFuzzy mathematics:An application oriented introduction
Fuzzy mathematics:An application oriented introduction
 
Algorithms
Algorithms Algorithms
Algorithms
 
Py4inf 05-iterations (1)
Py4inf 05-iterations (1)Py4inf 05-iterations (1)
Py4inf 05-iterations (1)
 
Py4inf 05-iterations (1)
Py4inf 05-iterations (1)Py4inf 05-iterations (1)
Py4inf 05-iterations (1)
 
Py4inf 05-iterations
Py4inf 05-iterationsPy4inf 05-iterations
Py4inf 05-iterations
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Memory basics 1
Memory basics 1Memory basics 1
Memory basics 1
 
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdfProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
ProgFund_Lecture_3_Data_Structures_and_Iteration-1.pdf
 
Introduction To Algorithms
Introduction To AlgorithmsIntroduction To Algorithms
Introduction To Algorithms
 
Presentation phinney abrf 2019
Presentation phinney abrf 2019Presentation phinney abrf 2019
Presentation phinney abrf 2019
 
4535092.ppt
4535092.ppt4535092.ppt
4535092.ppt
 
Mixed Effects Models - Empirical Logit
Mixed Effects Models - Empirical LogitMixed Effects Models - Empirical Logit
Mixed Effects Models - Empirical Logit
 
Lu decomposition
Lu decompositionLu decomposition
Lu decomposition
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
 
powerpoint 1-19.pdf
powerpoint 1-19.pdfpowerpoint 1-19.pdf
powerpoint 1-19.pdf
 
Assignement2 - Three techniques to be a better learner
Assignement2  - Three techniques to be a better learnerAssignement2  - Three techniques to be a better learner
Assignement2 - Three techniques to be a better learner
 

More from Mindy McAdams

Multimedia Journalism Innovations in the Classroom
Multimedia Journalism Innovations in the ClassroomMultimedia Journalism Innovations in the Classroom
Multimedia Journalism Innovations in the ClassroomMindy McAdams
 
Summary of journalism faculty curriculum workshop
Summary of journalism faculty curriculum workshopSummary of journalism faculty curriculum workshop
Summary of journalism faculty curriculum workshopMindy McAdams
 
U.S. j-schools and digital skills
U.S. j-schools and digital skills U.S. j-schools and digital skills
U.S. j-schools and digital skills Mindy McAdams
 
New skill sets for journalism
New skill sets for journalismNew skill sets for journalism
New skill sets for journalismMindy McAdams
 
Journalism blogs: An introduction
Journalism blogs: An introduction Journalism blogs: An introduction
Journalism blogs: An introduction Mindy McAdams
 
Why Your Newsroom Should Be Using WordPress - ONA13
Why Your Newsroom Should Be Using WordPress - ONA13Why Your Newsroom Should Be Using WordPress - ONA13
Why Your Newsroom Should Be Using WordPress - ONA13Mindy McAdams
 
Journalism's Future: Journalism, Not Newspapers
Journalism's Future: Journalism, Not NewspapersJournalism's Future: Journalism, Not Newspapers
Journalism's Future: Journalism, Not NewspapersMindy McAdams
 
Introduction to HTML5 Canvas
Introduction to HTML5 CanvasIntroduction to HTML5 Canvas
Introduction to HTML5 CanvasMindy McAdams
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOMMindy McAdams
 
HTML and Responsive Design
HTML and Responsive Design HTML and Responsive Design
HTML and Responsive Design Mindy McAdams
 
Design Concepts and Web Design
Design Concepts and Web DesignDesign Concepts and Web Design
Design Concepts and Web DesignMindy McAdams
 
Freedom of Speech - Louis Brandeis
Freedom of Speech - Louis BrandeisFreedom of Speech - Louis Brandeis
Freedom of Speech - Louis BrandeisMindy McAdams
 
Networked Information Economy / Benkler
Networked Information Economy / BenklerNetworked Information Economy / Benkler
Networked Information Economy / BenklerMindy McAdams
 
Convergence Culture / Jenkins
Convergence Culture / JenkinsConvergence Culture / Jenkins
Convergence Culture / JenkinsMindy McAdams
 
How to Share Your Digital Stories
How to Share Your Digital StoriesHow to Share Your Digital Stories
How to Share Your Digital StoriesMindy McAdams
 

More from Mindy McAdams (20)

Just Enough Code
Just Enough CodeJust Enough Code
Just Enough Code
 
Multimedia Journalism Innovations in the Classroom
Multimedia Journalism Innovations in the ClassroomMultimedia Journalism Innovations in the Classroom
Multimedia Journalism Innovations in the Classroom
 
Summary of journalism faculty curriculum workshop
Summary of journalism faculty curriculum workshopSummary of journalism faculty curriculum workshop
Summary of journalism faculty curriculum workshop
 
Crowdsourcing
CrowdsourcingCrowdsourcing
Crowdsourcing
 
U.S. j-schools and digital skills
U.S. j-schools and digital skills U.S. j-schools and digital skills
U.S. j-schools and digital skills
 
New skill sets for journalism
New skill sets for journalismNew skill sets for journalism
New skill sets for journalism
 
Journalism blogs: An introduction
Journalism blogs: An introduction Journalism blogs: An introduction
Journalism blogs: An introduction
 
Why Your Newsroom Should Be Using WordPress - ONA13
Why Your Newsroom Should Be Using WordPress - ONA13Why Your Newsroom Should Be Using WordPress - ONA13
Why Your Newsroom Should Be Using WordPress - ONA13
 
Journalism's Future: Journalism, Not Newspapers
Journalism's Future: Journalism, Not NewspapersJournalism's Future: Journalism, Not Newspapers
Journalism's Future: Journalism, Not Newspapers
 
Introduction to HTML5 Canvas
Introduction to HTML5 CanvasIntroduction to HTML5 Canvas
Introduction to HTML5 Canvas
 
Beginning jQuery
Beginning jQueryBeginning jQuery
Beginning jQuery
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
HTML and Responsive Design
HTML and Responsive Design HTML and Responsive Design
HTML and Responsive Design
 
Design Concepts and Web Design
Design Concepts and Web DesignDesign Concepts and Web Design
Design Concepts and Web Design
 
Learning Python
Learning PythonLearning Python
Learning Python
 
Freedom of Speech - Louis Brandeis
Freedom of Speech - Louis BrandeisFreedom of Speech - Louis Brandeis
Freedom of Speech - Louis Brandeis
 
Networked Information Economy / Benkler
Networked Information Economy / BenklerNetworked Information Economy / Benkler
Networked Information Economy / Benkler
 
Convergence Culture / Jenkins
Convergence Culture / JenkinsConvergence Culture / Jenkins
Convergence Culture / Jenkins
 
How to Share Your Digital Stories
How to Share Your Digital StoriesHow to Share Your Digital Stories
How to Share Your Digital Stories
 

Recently uploaded

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 

Recently uploaded (20)

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 

Learning Python - Week 4

  • 1. Learn Python the Hard Way Exercises 27 – 34 http://learnpythonthehardway.org/
  • 2. New things in ex. 27–34 • Booleans: True, False, logic, operators • if – elif – else: Note the relationship to True and False • loops: 2 kinds, for and while • lists and how to – create a new list – add and delete things from lists – find out what’s in a list
  • 3. How the Boolean AND works There is a very long bungee jump above a deep river gorge in Africa. You say: “If the bungee jump looks safe and it is cheap, then I will do it.”
  • 4. How the Boolean AND works “If the bungee jump looks safe and it is cheap, then I will do it.” looks safe = False (you won’t do it) is cheap = False (you won’t do it) You’ll only do it if both conditions are TRUE.
  • 5. How the Boolean OR works There is a great party Tuesday night, but you are in danger of failing your Wednesday test. You say: “If I finish studying in time or the test is canceled, then I will go to the party.”
  • 6. How the Boolean OR works “If I finish studying in time or the test is canceled, then I will go to the party.” finish studying = True (can go) test canceled = True (can go) You can go if only one of the conditions is TRUE. Or both. But one is enough.
  • 7. and True and True : True True and False : False False and True : False False and False : False True or True : True True or False : True False or True : True False or False : False “If the bungee jump looks safe and it is cheap, then I will do it.” “If I finish studying in time or the test is canceled, then I will go to the party.” or
  • 8. Boolean operators (symbols) 1 != 0 1 == (3 – 2) 5 >= 1 10 <= 100 1 != (3 – 2) 1 == 0 5 <= 1 10 >= 100 True True True True False False False False
  • 10. if – elif – else (if statements)
  • 15. Loops • Every programming language has loops • A loop typically runs over and over until something makes it stop (different from a usual function, which runs only once) • The “for” loop is a standard kind of loop • for-loops can appear inside a function Exercise 32
  • 16. Loops • Standard syntax for starting a for-loop in Python: for fruit in fruits: Exercise 32 Note that fruit could be any variable name, like x or a or cat. In this case, there must already be a list named fruits (more about lists in a minute)
  • 17. Loops • Also standard syntax (but different) for starting a for-loop in Python: for i in range(0, 9): Exercise 32 In this case, we don’t know the name of the list yet. Or maybe this loop does not even use a list.
  • 18. So, 2 different for-loops for fruit in fruits: print fruit Exercise 32 for i in range(0, 9): print "Hello!" Like functions, loops must be indented. They can have many lines. These are short just to make them simple.
  • 19. while-loops Exercise 33 • The “while” loop is another standard kind of loop • while-loops can appear inside a function • If you can figure out how to do what you want with a for-loop, then use a for-loop. • If you must use a while-loop, be careful that it will not run forever. If it does, it’s an infinite loop (which is NOT good).
  • 20. Lists • In many languages, a “list” is called an “array” (but Zed says we should say “list” for Python) • Lists can be gigantic—there can be thousands of items in one list, or none • The standard format of a list in Python: fruits = ['apples', 'oranges', 'pears', 'apricots'] Exercise 32 Note: If there are numbers in the list, they won’t have quotes around them.
  • 21. Loops and Lists These two for-loops do exactly the same thing: fruits = ['apples', 'oranges', 'pears', 'apricots'] for fruit in fruits: print "A fruit of type: %s" % fruit for y in fruits: print "A fruit of type: %s" % y Exercise 32
  • 22. Lists • You actually already saw a list in Exercise 25, when you did this: words = stuff.split(' ') • After that, words contained a list: ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.'] • You can use pop() and len() on any list Exercise 32
  • 23. Some things we do with lists fruits.pop() fruits.append("bananas") fruits.extend(["plums", "mangoes"]) del fruits[2] print fruits With append() you can add only one item at a time to the list.
  • 25. Items in lists Exercise 34: Items in lists can be counted. Items in lists can be referenced by number, but the first number is not 1 — it is 0.
  • 26. Back to while-loops • You might think the while-loops act a lot like the for-loops that used range (and you would be right) • However, the while-loops are different • The condition at the start of a while-loop could test for something not numeric, such as “while we are not yet at the end of the file” • Note: for-loops are very common, and while-loops are less so (as Zed says: “Usually a for-loop is better”) Exercise 33
  • 27. Learning … while-loops • You really need to play with a lot of the extra credit or “study drills” in Exercise 33 to get this into your brain • I made four different .py files to test all the comparisons that Zed recommends • If you play with this, you can really understand how for-loops and while-loops are different Exercise 33
  • 29. A word of advice So Exercise 31 is long, but easy. You might feel like now it’s all getting easy … BUT WAIT! No, it’s not. • Exercise 32 introduces the for-loop. • Exercise 33 introduces the while-loop. • Exercise 34 introduces how we navigate through the elements in a list. These last 3 exercises are QUITE challenging!
  • 30. Indents in Python • The usual way is to indent 4 spaces (not a tab indent — actually type 4 spaces) • If you accidentally type 3, or 5, or something else, and all the others are 4, Python will throw an error • Most programming languages require multiple levels of indents, and these levels (and the format of indenting) are important, so take care
  • 31. An example of multiple indent levels within a Python program
  • 32. Learn Python the Hard Way Exercises 27 – 34 (now we know some stuff)

Editor's Notes

  1. SOURCE http://learnpythonthehardway.org/book/
  2. The way AND and OR work in programming languages is pretty much the same as the way we use them in real life.
  3. When you say IF with AND, you usually mean that both things have to happen.
  4. Again, the way AND and OR work in programming languages is pretty much the same as the way we use them in real life.
  5. When you say IF with OR, you usually mean that only one of the things has to happen.
  6. Questions?
  7. Questions?
  8. CODE EXAMPLE. LPTHW Exercise 28. Zed gives you lots of examples to play with. PLAY. It works!
  9. CODE EXAMPLE. LPTHW Exercises 29 and 30. Introduction to IF and IF – ELSE.
  10. CODE EXAMPLE. LPTHW Exercises 29 and 30. Introduction to IF and IF – ELSE.
  11. CODE EXAMPLE. LPTHW Exercise 30. Note that when the condition is met, none of the other “elifs” after that are executed. They do not run.
  12. NOTE: I’m skipping over Exercise 31 because it is just more of the same from Exercise 30.
  13. Just a quick hop forward to exercise 33 – we will come back to it later.
  14. Review LPTHW Exercise 25 and try to play with lists, using things you did in Ex. 25. WHY DID WE SPLIT? By turning freetext into a list, we can examine it in all kinds of ways. We are sort (alphabetical order), pop() words off the ends, move words from one list to another. And more.
  15. CODE EXAMPLE. LPTHW Exercise 32. Adding “range” allows you to make a different kind of “for” loop, with a limited number of times that it will run. This version (0, 100), would run 100 times, except that I built in a “break.”
  16. LPTHW Exercise 34 -- The most important thing to understand about this is that you can pluck out any item in a list, but you must remember that the first one is item “0” and not item “1.”
  17. LPTHW Exercise 33
  18. LPTHW Exercise 33
  19. LPTHW Exercise 33 -- notice how I write comments for myself. I find them to be VERY helpful to me when I look at the code weeks or months later.
  20. These things are really important in programming – AND you will see all of them AGAIN in JavaScript and jQuery, after Spring Break. So it’s in your best interest to spend time with them NOW and really try to understand them.
  21. This comes from an example in the book Visualize This, by Nathan Yau, pp. 288ff. The exercise is to color-code a U.S. map using data on unemployment in each U.S. county.
  22. Mindy McAdams - CONTACT – http://mindymcadams.com/