SlideShare a Scribd company logo
1 of 5
Download to read offline
WEEK
TWO
Python Loops and String Manipulation
Last week, we showed you some basic Python programming and gave you some intriguing problems to solve.
But it is hard to do anything really exciting until you have mastered what we are covering this week. So read on
...
1 Loopy Python
The thing about computers is that they aren’t very smart, but they are extremely fast — fast at doing exactly what
we tell them to do over and over (and over and over...) again.
Last week, we introduced the if control structure that decides whether an (indented) block of code should run or
not. Any control structure that repeats a block of statements is called a loop. We call each individual repetition
an iteration of the loop.
Almost all programming languages provide one (or more) loop control structures. Python provides two different
types, the while loop and the for loop. We’ll look at while loops now and save for loops for next week!
2 while loops
Let’s start with a simple example:
>>> i = 0
>>> while i < 3:
... print i
... i = i + 1
...
0
1
2
A while loop is basically a repetitive version of an if statement. In fact, it uses almost exactly the same syntax:
it starts with the while keyword, followed by a conditional expression i < 3 and a colon. On the next line, the
block is indented to indicate which statement(s) the while controls, just like if.
It works like this: while the conditional expression i < 3 is True, the body of the loop is run. Here, the body
consists of two statements, a print statement and i = i + 1.
The variable i holds the number of times the body has been executed. When the program first reaches the while
statement, i has the value 0. The conditional i < 3 is True this time, so print i and i = i + 1 are run.
At first, the i = i + 1 line might seem confusing. How can i have the same value as i + 1? The trick is to
remember this is not an equality test, but an assignment statement! So, we calculate the right hand side first (take
the value of i and add 1 to it), and then we assign that back into the variable i.
The i = i + 1 simply adds one to (or increments) the value of i every time we go through the loop so we know
how many iterations we have completed. So after the first iteration, i holds the value 1 and we go back to the top
of the loop. We then recheck the conditional expression to decide whether to run the body again.
When used this way, the variable i is called a loop counter. The loop keeps executing until the value of i has
been incremented to 3. When this happens, the conditional expression i < 3 now False and so we jump to the
statement after the loop body (that is, the end of the program in this case).
c National Computer Science School 2005-2009 1
NCSS Challenge (Beginners) WEEK TWO
3 Anatomy of a Loop
There are four things to think about when writing your own loops:
starting Are there any variables we need to setup before we start a loop? This is often called loop initialisation.
stopping How do we know when to stop? This is called the termination condition.
doing What are the instructions we want to repeat. This will become the body of the loop control structure.
changing Do the instructions change in any way between each repetition. For example, we might need to keep
track of how many times we have repeated the body of the loop, that is, the number of iterations.
You can use these four like a checklist to make sure the loops you write are doing what you want them to.
Let’s look at another example:
>>> i = 0
>>> while i < 7:
... print i
... i += 2
...
0
2
4
6
The initialisation involves setting the loop variable to zero in i = 0. The loop will terminate when i is no longer
smaller than seven i < 7. There are two statements in the body.
The second one is a little different this time. Firstly, we’re using a special abbreviation += for adding to an
existing variable. So i += 2 is actually the same as i = i + 2. It can be used whenever you want to add
something to an existing variable, and so you’ll often see it for incrementing loop variables.
Secondly, we’re adding more than one at a time. The result is the loop will now print out all even numbers less
than seven.
4 Reading multiple lines from the user
So far we’ve only seen examples where you know when you want to stop (e.g. before a number gets too large).
However, they also work well when you don’t know how many iterations you’ll need in advance. For example,
when you’re reading multiple lines of input from the user:
>>> command = raw_input(’enter a command: ’)
>>> while command != ’quit’:
... print ’your command was ’ + command
... command = raw_input(’enter a command: ’)
...
enter a command: run
your command was run
enter a command: quit
Here it depends on how many times it takes for the user to enter quit as the command. Rather than incrementing
a loop counter, the thing that’s changing involves asking the user for a new command inside the loop.
5 Common loop mistakes
Loops (especially while loops) can be rather tricky to get right. Here is one mistake that is particularly common.
This program is going to run for a long time:
c National Computer Science School 2005-2009 2
NCSS Challenge (Beginners) WEEK TWO
i = 0
while i < 3:
print i
This program will run forever — well until you turn your computer off, producing a continuous stream of
0’s. In fact, the only way to stop this infinite loop is to press Ctrl-C which terminates the program with an
KeyboardInterrupt exception, which will look something like this:
Traceback (most recent call last):
File "example1.py", line 3, in -toplevel-
print i
KeyboardInterrupt
The cause of the infinite loop is a very common mistake — forgetting to increment the loop counter. Most loop
mistakes involve starting, stopping or changing, so use the loop checklist to help debug your loops.
6 Getting pieces of a string
Often we need to access individual characters or groups of characters in a string. Accessing a single character is
done using the square bracket subscripting or indexing operation:
>>> x = "hello world"
>>> x[0]
’h’
>>> x[1]
’e’
You can also access strings from the other end using a negative index:
>>> x = "hello world"
>>> x[-1]
’d’
>>> x[-5]
’w’
A longer part of the string (called a substring) can be accessed by using an extended square bracket notation with
two indices called a slice:
>>> x = "hello world"
>>> x[0:5]
’hello’
>>> len(x)
11
>>> x[6:11]
’world’
A slice starts from the first index and includes characters up to but not including the second index. So, the slice
x[0:5] starts from the x[0] and goes up to x[5] (the space) but doesn’t include it. There are a couple of
shortcuts too:
>>> x[:5]
’hello’
>>> x[6:]
’world’
c National Computer Science School 2005-2009 3
NCSS Challenge (Beginners) WEEK TWO
When the first index is zero (when taking a prefix of the sequence) the zero can be left out (like x[:5]). When
the last index is the length of the string, (when taking a suffix of the sequence) the last index can be left out (like
x[6:]).
Negative indices work in the same way that they do for indexing. Slicing is slightly more general than indexing.
The index values must fall within the length of the string, but slice indices do not have to. If the slice indices fall
outside the length of the string then the empty string will be returned for all or part of the slice.
Strings are also immutable, which means that once the string is constructed, it cannot be modified. For example,
you cannot change a character in an existing string by assigning a new character to a subscript:
>>> x[0] = ’X’
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ’str’ object does not support item assignment
>>>
You must instead create a new string by slicing up the string and concatenating the pieces, and then assigning the
result back to the original variable:
>>> x = ’X’ + x[1:]
>>> x
’Xello world’
Every operation that looks like it is modifying a string is actually returning a new string.
7 Checking the contents of strings
To check whether a string contains a particular character, all you need is the in conditional operator, like this:
>>> x = ’hello world’
>>> ’h’ in x
True
>>> ’z’ in x
False
The not in operator does the opposite. It returns True when the string does not contain the particular character:
>>> ’z’ not in x
True
These operators also work for substrings:
>>> ’hello’ in x
True
>>> ’howdy’ not in x
True
These conditional expressions can then be used with Python if and while loops:
name = raw_input(’Enter your name? ’)
if ’X’ in name:
print ’Your name contains an X’
c National Computer Science School 2005-2009 4
NCSS Challenge (Beginners) WEEK TWO
8 Calling methods on strings
Not only can you create new strings using operators like slicing (s[1:3]), addition ("hello" + "world")
and multiplication ("abc"*3), but you can also call special functions on strings which create new strings with
different properties. For instance, we can convert a string to lowercase or uppercase:
>>> s = "I know my ABC"
>>> s.lower()
’i know my abc’
>>> s.upper()
’I KNOW MY ABC’
We can also replace a particular substring with another substring:
>>> s = "hello world"
>>> s.replace(’l’, ’X’)
’heXXo worXd’
>>> s.replace(’hello’, ’goodbye’)
’goodbye world’
Notice that the convention for calling these string manipulation functions is different – the string that we are
manipulating comes first, followed by a period (or full stop), then the function name appears with any other info
required in parentheses. These special functions that apply to a particular type of value are called methods.
So for example, the s.replace(’l’, ’X’) is calling the replace method on the string stored in variable s.
replace needs two additional pieces of information: the bit of the string to replace, in this case ’l’ and what to
replace it with, in this case ’X’.
c National Computer Science School 2005-2009 5

More Related Content

What's hot (20)

L06
L06L06
L06
 
Python Math Concepts Book
Python Math Concepts BookPython Math Concepts Book
Python Math Concepts Book
 
Sequence Types in Python Programming
Sequence Types in Python ProgrammingSequence Types in Python Programming
Sequence Types in Python Programming
 
VB Script
VB ScriptVB Script
VB Script
 
Loops in java script
Loops in java scriptLoops in java script
Loops in java script
 
Introduction to Python (part 1/2)
Introduction to Python (part 1/2)Introduction to Python (part 1/2)
Introduction to Python (part 1/2)
 
QTP VB Script Trainings
QTP VB Script TrainingsQTP VB Script Trainings
QTP VB Script Trainings
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
 
Python course
Python coursePython course
Python course
 
Python slide.1
Python slide.1Python slide.1
Python slide.1
 
Python
PythonPython
Python
 
Python study material
Python study materialPython study material
Python study material
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
Vbs
VbsVbs
Vbs
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Vb script tutorial
Vb script tutorialVb script tutorial
Vb script tutorial
 
Python programming
Python  programmingPython  programming
Python programming
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Python programing
Python programingPython programing
Python programing
 

Viewers also liked

University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs emailhccit
 
Week04
Week04Week04
Week04hccit
 
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr123 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12hccit
 
Week05
Week05Week05
Week05hccit
 
Week03
Week03Week03
Week03hccit
 
Notes5
Notes5Notes5
Notes5hccit
 
10 ict gm_game_assignment_2013
10 ict gm_game_assignment_201310 ict gm_game_assignment_2013
10 ict gm_game_assignment_2013hccit
 

Viewers also liked (7)

University partnerships programs email
University partnerships programs emailUniversity partnerships programs email
University partnerships programs email
 
Week04
Week04Week04
Week04
 
3 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr123 d modelling_task_sheet_2014_yr12
3 d modelling_task_sheet_2014_yr12
 
Week05
Week05Week05
Week05
 
Week03
Week03Week03
Week03
 
Notes5
Notes5Notes5
Notes5
 
10 ict gm_game_assignment_2013
10 ict gm_game_assignment_201310 ict gm_game_assignment_2013
10 ict gm_game_assignment_2013
 

Similar to Notes2

Similar to Notes2 (20)

C++ Loops General Discussion of Loops A loop is a.docx
C++ Loops  General Discussion of Loops A loop is a.docxC++ Loops  General Discussion of Loops A loop is a.docx
C++ Loops General Discussion of Loops A loop is a.docx
 
While loop
While loopWhile loop
While loop
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
 
Loops_in_Rv1.2b
Loops_in_Rv1.2bLoops_in_Rv1.2b
Loops_in_Rv1.2b
 
Mastering Python lesson 3a
Mastering Python lesson 3aMastering Python lesson 3a
Mastering Python lesson 3a
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
 
Notes3
Notes3Notes3
Notes3
 
Acm aleppo cpc training second session
Acm aleppo cpc training second sessionAcm aleppo cpc training second session
Acm aleppo cpc training second session
 
Going loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptxGoing loopy - Introduction to Loops.pptx
Going loopy - Introduction to Loops.pptx
 
Coding in Disaster Relief - Worksheet (Advanced)
Coding in Disaster Relief - Worksheet (Advanced)Coding in Disaster Relief - Worksheet (Advanced)
Coding in Disaster Relief - Worksheet (Advanced)
 
Control structures
Control structuresControl structures
Control structures
 
130707833146508191
130707833146508191130707833146508191
130707833146508191
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Init() Lesson 3
Init() Lesson 3Init() Lesson 3
Init() Lesson 3
 
Python basics
Python basicsPython basics
Python basics
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 

More from hccit

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syllhccit
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guidehccit
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11hccit
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014hccit
 
Photoshop
PhotoshopPhotoshop
Photoshophccit
 
Flash
FlashFlash
Flashhccit
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overviewhccit
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochurehccit
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exerciseshccit
 
Repairs questions
Repairs questionsRepairs questions
Repairs questionshccit
 
Movies questions
Movies questionsMovies questions
Movies questionshccit
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questionshccit
 
Section b
Section bSection b
Section bhccit
 
Section a
Section aSection a
Section ahccit
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5hccit
 
Case study report mj
Case study report mjCase study report mj
Case study report mjhccit
 
Mj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedqMj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedqhccit
 
Case study plan mj
Case study plan mjCase study plan mj
Case study plan mjhccit
 

More from hccit (20)

Snr ipt 10_syll
Snr ipt 10_syllSnr ipt 10_syll
Snr ipt 10_syll
 
Snr ipt 10_guide
Snr ipt 10_guideSnr ipt 10_guide
Snr ipt 10_guide
 
3 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr113 d modelling_task_sheet_2014_yr11
3 d modelling_task_sheet_2014_yr11
 
10 ict photoshop_proj_2014
10 ict photoshop_proj_201410 ict photoshop_proj_2014
10 ict photoshop_proj_2014
 
Photoshop
PhotoshopPhotoshop
Photoshop
 
Flash
FlashFlash
Flash
 
Griffith sciences pathway programs overview
Griffith sciences pathway programs overviewGriffith sciences pathway programs overview
Griffith sciences pathway programs overview
 
Griffith info tech brochure
Griffith info tech brochureGriffith info tech brochure
Griffith info tech brochure
 
Pm sql exercises
Pm sql exercisesPm sql exercises
Pm sql exercises
 
Repairs questions
Repairs questionsRepairs questions
Repairs questions
 
Movies questions
Movies questionsMovies questions
Movies questions
 
Australian birds questions
Australian birds questionsAustralian birds questions
Australian birds questions
 
Section b
Section bSection b
Section b
 
B
BB
B
 
A
AA
A
 
Section a
Section aSection a
Section a
 
Ask manual rev5
Ask manual rev5Ask manual rev5
Ask manual rev5
 
Case study report mj
Case study report mjCase study report mj
Case study report mj
 
Mj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedqMj example case_study_layout_intro_completedq
Mj example case_study_layout_intro_completedq
 
Case study plan mj
Case study plan mjCase study plan mj
Case study plan mj
 

Recently uploaded

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 

Recently uploaded (20)

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 

Notes2

  • 1. WEEK TWO Python Loops and String Manipulation Last week, we showed you some basic Python programming and gave you some intriguing problems to solve. But it is hard to do anything really exciting until you have mastered what we are covering this week. So read on ... 1 Loopy Python The thing about computers is that they aren’t very smart, but they are extremely fast — fast at doing exactly what we tell them to do over and over (and over and over...) again. Last week, we introduced the if control structure that decides whether an (indented) block of code should run or not. Any control structure that repeats a block of statements is called a loop. We call each individual repetition an iteration of the loop. Almost all programming languages provide one (or more) loop control structures. Python provides two different types, the while loop and the for loop. We’ll look at while loops now and save for loops for next week! 2 while loops Let’s start with a simple example: >>> i = 0 >>> while i < 3: ... print i ... i = i + 1 ... 0 1 2 A while loop is basically a repetitive version of an if statement. In fact, it uses almost exactly the same syntax: it starts with the while keyword, followed by a conditional expression i < 3 and a colon. On the next line, the block is indented to indicate which statement(s) the while controls, just like if. It works like this: while the conditional expression i < 3 is True, the body of the loop is run. Here, the body consists of two statements, a print statement and i = i + 1. The variable i holds the number of times the body has been executed. When the program first reaches the while statement, i has the value 0. The conditional i < 3 is True this time, so print i and i = i + 1 are run. At first, the i = i + 1 line might seem confusing. How can i have the same value as i + 1? The trick is to remember this is not an equality test, but an assignment statement! So, we calculate the right hand side first (take the value of i and add 1 to it), and then we assign that back into the variable i. The i = i + 1 simply adds one to (or increments) the value of i every time we go through the loop so we know how many iterations we have completed. So after the first iteration, i holds the value 1 and we go back to the top of the loop. We then recheck the conditional expression to decide whether to run the body again. When used this way, the variable i is called a loop counter. The loop keeps executing until the value of i has been incremented to 3. When this happens, the conditional expression i < 3 now False and so we jump to the statement after the loop body (that is, the end of the program in this case). c National Computer Science School 2005-2009 1
  • 2. NCSS Challenge (Beginners) WEEK TWO 3 Anatomy of a Loop There are four things to think about when writing your own loops: starting Are there any variables we need to setup before we start a loop? This is often called loop initialisation. stopping How do we know when to stop? This is called the termination condition. doing What are the instructions we want to repeat. This will become the body of the loop control structure. changing Do the instructions change in any way between each repetition. For example, we might need to keep track of how many times we have repeated the body of the loop, that is, the number of iterations. You can use these four like a checklist to make sure the loops you write are doing what you want them to. Let’s look at another example: >>> i = 0 >>> while i < 7: ... print i ... i += 2 ... 0 2 4 6 The initialisation involves setting the loop variable to zero in i = 0. The loop will terminate when i is no longer smaller than seven i < 7. There are two statements in the body. The second one is a little different this time. Firstly, we’re using a special abbreviation += for adding to an existing variable. So i += 2 is actually the same as i = i + 2. It can be used whenever you want to add something to an existing variable, and so you’ll often see it for incrementing loop variables. Secondly, we’re adding more than one at a time. The result is the loop will now print out all even numbers less than seven. 4 Reading multiple lines from the user So far we’ve only seen examples where you know when you want to stop (e.g. before a number gets too large). However, they also work well when you don’t know how many iterations you’ll need in advance. For example, when you’re reading multiple lines of input from the user: >>> command = raw_input(’enter a command: ’) >>> while command != ’quit’: ... print ’your command was ’ + command ... command = raw_input(’enter a command: ’) ... enter a command: run your command was run enter a command: quit Here it depends on how many times it takes for the user to enter quit as the command. Rather than incrementing a loop counter, the thing that’s changing involves asking the user for a new command inside the loop. 5 Common loop mistakes Loops (especially while loops) can be rather tricky to get right. Here is one mistake that is particularly common. This program is going to run for a long time: c National Computer Science School 2005-2009 2
  • 3. NCSS Challenge (Beginners) WEEK TWO i = 0 while i < 3: print i This program will run forever — well until you turn your computer off, producing a continuous stream of 0’s. In fact, the only way to stop this infinite loop is to press Ctrl-C which terminates the program with an KeyboardInterrupt exception, which will look something like this: Traceback (most recent call last): File "example1.py", line 3, in -toplevel- print i KeyboardInterrupt The cause of the infinite loop is a very common mistake — forgetting to increment the loop counter. Most loop mistakes involve starting, stopping or changing, so use the loop checklist to help debug your loops. 6 Getting pieces of a string Often we need to access individual characters or groups of characters in a string. Accessing a single character is done using the square bracket subscripting or indexing operation: >>> x = "hello world" >>> x[0] ’h’ >>> x[1] ’e’ You can also access strings from the other end using a negative index: >>> x = "hello world" >>> x[-1] ’d’ >>> x[-5] ’w’ A longer part of the string (called a substring) can be accessed by using an extended square bracket notation with two indices called a slice: >>> x = "hello world" >>> x[0:5] ’hello’ >>> len(x) 11 >>> x[6:11] ’world’ A slice starts from the first index and includes characters up to but not including the second index. So, the slice x[0:5] starts from the x[0] and goes up to x[5] (the space) but doesn’t include it. There are a couple of shortcuts too: >>> x[:5] ’hello’ >>> x[6:] ’world’ c National Computer Science School 2005-2009 3
  • 4. NCSS Challenge (Beginners) WEEK TWO When the first index is zero (when taking a prefix of the sequence) the zero can be left out (like x[:5]). When the last index is the length of the string, (when taking a suffix of the sequence) the last index can be left out (like x[6:]). Negative indices work in the same way that they do for indexing. Slicing is slightly more general than indexing. The index values must fall within the length of the string, but slice indices do not have to. If the slice indices fall outside the length of the string then the empty string will be returned for all or part of the slice. Strings are also immutable, which means that once the string is constructed, it cannot be modified. For example, you cannot change a character in an existing string by assigning a new character to a subscript: >>> x[0] = ’X’ Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: ’str’ object does not support item assignment >>> You must instead create a new string by slicing up the string and concatenating the pieces, and then assigning the result back to the original variable: >>> x = ’X’ + x[1:] >>> x ’Xello world’ Every operation that looks like it is modifying a string is actually returning a new string. 7 Checking the contents of strings To check whether a string contains a particular character, all you need is the in conditional operator, like this: >>> x = ’hello world’ >>> ’h’ in x True >>> ’z’ in x False The not in operator does the opposite. It returns True when the string does not contain the particular character: >>> ’z’ not in x True These operators also work for substrings: >>> ’hello’ in x True >>> ’howdy’ not in x True These conditional expressions can then be used with Python if and while loops: name = raw_input(’Enter your name? ’) if ’X’ in name: print ’Your name contains an X’ c National Computer Science School 2005-2009 4
  • 5. NCSS Challenge (Beginners) WEEK TWO 8 Calling methods on strings Not only can you create new strings using operators like slicing (s[1:3]), addition ("hello" + "world") and multiplication ("abc"*3), but you can also call special functions on strings which create new strings with different properties. For instance, we can convert a string to lowercase or uppercase: >>> s = "I know my ABC" >>> s.lower() ’i know my abc’ >>> s.upper() ’I KNOW MY ABC’ We can also replace a particular substring with another substring: >>> s = "hello world" >>> s.replace(’l’, ’X’) ’heXXo worXd’ >>> s.replace(’hello’, ’goodbye’) ’goodbye world’ Notice that the convention for calling these string manipulation functions is different – the string that we are manipulating comes first, followed by a period (or full stop), then the function name appears with any other info required in parentheses. These special functions that apply to a particular type of value are called methods. So for example, the s.replace(’l’, ’X’) is calling the replace method on the string stored in variable s. replace needs two additional pieces of information: the bit of the string to replace, in this case ’l’ and what to replace it with, in this case ’X’. c National Computer Science School 2005-2009 5