SlideShare a Scribd company logo
1 of 22
OVERVIEW OF TODAY’S SESSION
• While loops – a quick bit of unfinished
business from last week!
• Review of highlights from last week.
• Some useful tricks with strings.
• Working with ASCII codes to do more with
strings.
• Iteration with for loops.
• Lots of coding!
WHAT DOES THIS DO?
INFINITE WHILE LOOPS
SAVE ALL YOUR FILES before running this one.
The only difference is the condition in the while loop.
What do you think will happen?
Now run the code and see if you were right.
Use Ctrl-C to cancel running code (NB this doesn’t always work)
STOP:
Don’t run this until
you’ve read the
instructions below.
A QUICK RECAP
(If you’re already happy with all this material, feel free to go back to any Challenges
from last week that you haven’t finished, or work on a project of your own choice.
This part won’t last very long.)
• Every Python script you write will use variables.
• A variable is a label (which you choose) that points to a
location in memory. That location holds data of a certain type.
• The commonest types are int, float, string and bool.
• You can change a variable from one type to another if Python
knows how to do that.
• A Python script is a list of instructions. Usually the
instructions run in sequence from to top bottom.
• We saw how to use if to make decisions about whether to
run a block of code or skip it.
• We also saw how to use while to run a block of code
multiple times.
• We also used randint, which will be useful again today.
• Remember we must import random to use it.
Make sure you understand
everything here before moving on!
WHAT TO DO IF…
…You need more time on what we just
reviewed:
• Follow along with the class for now. When it’s time for you to
write some code, take your time and ask for help on the parts
that you’re stuck on. There’s lots of coding time this week.
…You want to move more quickly through
the upcoming material:
• Feel free to skim through the slides to the end of the section,
where you’ll find more difficult challenges (some are pretty
tough).
CONVERTING OTHER TYPES TO STRINGS
Most things in Python provide a way to
convert them into strings.
Remember, you do this using str().
So if x is something you want to turn into
a string, str(x) usually does the job.
Here are some of the built-in functions Python provides for doing things with
strings. Notice that most of them use a dot after the variable name; we might
talk more about this next week.
This code is in the shared drive – no need to type it out.
There are more powerful, “lower-level” techniques that we’ll look at later.
There’s also a string library with more functions that we’ll mention in Week 4.
COMBINING OPERATIONS
The functions on the previous slide are all non-destructive, meaning they don’t
change the original string.
If you want to make multiple changes, you can use something like the above.
Remember m = m + 1 from last week? This is the same thing.
CHALLENGE
Nonsense Generator
Basic Version
• Write a script that takes input from the user and replaces some letters with
others to make nonsense.
• A good start is to change all the vowels into other vowels.
• Remember you can use numbers, spaces and punctuation as well as letters.
Extensions
• Use a while loop to make it run repeatedly.
• Make your nonsense reversible: if I type x and it outputs y, typing y should
make it output x again.
• Experiment with s.center(50) on various strings. What does it do?
• Look at the information on this page and try out various advanced string
formatting techniques: https://pyformat.info/.
• (Advanced) Look at this page and try out some of Python’s regular
expressions: https://docs.python.org/2/howto/regex.html
RANGES
If you just want to loop over a range of integers, this is the easiest way.
Run this and see what it prints. Think carefully about why this isn’t
surprising!
You may be surprised how often this is useful. There are lots of
challenges that need this coming up, especially the more tricky ones.
MORE FUN WITH STRINGS: CHR
Computer memory is only really good for storing numbers,
so everything else must be converted into a number before
being stored.
The standard way to convert letters and other text
characters into numbers is ASCII. You can use the chr()
function to convert an ACII number into its corresponding
character.
MORE FUN WITH STRINGS: ORD
The ord() function does the opposite of chr(): it
converts a character into its ASCII number.
Look carefully at this code, it contains several things that
we’ve learned this week.
AN EASIER WAY TO LOOP OVER A STRING
This is a bit more elegant than the previous one, but it only
gives us the string one letter at a time. If you need to know
where you are in the string, the version on the previous
slide is still needed.
CAESAR CIPHERS
We end this session with an
extended challenge based on
the Caesar cipher.
This is a way of encrypting a
message made up of letters
and spaces.
We leave the spaces alone.
The letters on the outer wheel
are exchanged for the ones
on the inner wheel.
How many steps the inner
wheel is rotated is the “key” to
the cipher.
Decode this message using the code wheel set as it is
on the previous slide:
IRMAHG BL XTLR
If you want more practice, encode a simple sentence yourself (by
swapping each letter on the outer ring for the matching one on
the inner) and then check you can decode it (by reversing the
process).
CHALLENGE
Caesar Cipher
Basic Version
• Get input from the user and print the result of applying the Caesar cipher to it
with a fixed key of your choice.
• This is tricky, so take your time and plan carefully. There’s more guidance on
the next slide if you need it.
Extensions
• Let the user choose the key by typing, e.g., KEY=T to mean that the cipher
“wheel” should be turned so that “A” matches “T”. Hint: use an if statement to
check whether s[:4]==“KEY=“
• Similarly, if the user types “DEC=“ at the start of their input have your script
decode it instead, using the current key.
• Anyone who intercepts both the encrypted message and the key can decode
the message if they can guess what your cipher code does. A Caesar cipher
is very simple and easy to guess. Think about various ways you could make
the cipher more complicated.
HELP!
• Start by creating an empty string that we’ll use to build up the output letter-by-
letter.
• Decide on a “key”, which is the number of steps the inner wheel has been
turned. Store this in a variable.
• Convert the input to uppercase and store this in another variable.
• Note that the ASCII values of A-Z go from 65(=A) to 90 (=Z).
• Now loop through this new variable character-by-character (you can use the
“nice” version of looping through a string here). For each letter do this:
• Check whether it’s a space. If it is, just add it to the output string
• Else:
• get its ASCII value using ord.
• Add the key to the ASCII value.
• If the result is more than 90, subtract 26 from it. This brings it back to the
start of the alphabet again.
• Convert this number to a letter using chr and add it to the output string.
• When the loop has finished, print the output string.
Here is a step-by-step guide to completing
this challenge, in case you feel really stuck.

More Related Content

Similar to IntroPython-Week02-StringsIteration.pptx

Web development basics (Part-3)
Web development basics (Part-3)Web development basics (Part-3)
Web development basics (Part-3)Rajat Pratap Singh
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfMichpice
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageAzilen Technologies Pvt. Ltd.
 
Rails development environment talk
Rails development environment talkRails development environment talk
Rails development environment talkReuven Lerner
 
Note for Java Programming////////////////
Note for Java Programming////////////////Note for Java Programming////////////////
Note for Java Programming////////////////MeghaKulkarni27
 
Brixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 RecapBrixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 RecapBasil Bibi
 
SPARKNaCl: A verified, fast cryptographic library
SPARKNaCl: A verified, fast cryptographic librarySPARKNaCl: A verified, fast cryptographic library
SPARKNaCl: A verified, fast cryptographic libraryAdaCore
 
RSYSLOG v8 improvements and how to write plugins in any language.
RSYSLOG v8 improvements and how to write plugins in any language.RSYSLOG v8 improvements and how to write plugins in any language.
RSYSLOG v8 improvements and how to write plugins in any language.Rainer Gerhards
 
TypeScript-SPS-melb.pptx
TypeScript-SPS-melb.pptxTypeScript-SPS-melb.pptx
TypeScript-SPS-melb.pptxaccordv12
 
General Programming Concept
General Programming ConceptGeneral Programming Concept
General Programming ConceptHaris Bin Zahid
 

Similar to IntroPython-Week02-StringsIteration.pptx (20)

Web development basics (Part-3)
Web development basics (Part-3)Web development basics (Part-3)
Web development basics (Part-3)
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
l2-es6-160830040119.pdf
l2-es6-160830040119.pdfl2-es6-160830040119.pdf
l2-es6-160830040119.pdf
 
Rails development environment talk
Rails development environment talkRails development environment talk
Rails development environment talk
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Note for Java Programming////////////////
Note for Java Programming////////////////Note for Java Programming////////////////
Note for Java Programming////////////////
 
Brixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 RecapBrixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 Recap
 
Swift
SwiftSwift
Swift
 
Software + Babies
Software + BabiesSoftware + Babies
Software + Babies
 
SPARKNaCl: A verified, fast cryptographic library
SPARKNaCl: A verified, fast cryptographic librarySPARKNaCl: A verified, fast cryptographic library
SPARKNaCl: A verified, fast cryptographic library
 
ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1ACM init() Spring 2015 Day 1
ACM init() Spring 2015 Day 1
 
RSYSLOG v8 improvements and how to write plugins in any language.
RSYSLOG v8 improvements and how to write plugins in any language.RSYSLOG v8 improvements and how to write plugins in any language.
RSYSLOG v8 improvements and how to write plugins in any language.
 
Vba Class Level 1
Vba Class Level 1Vba Class Level 1
Vba Class Level 1
 
TypeScript-SPS-melb.pptx
TypeScript-SPS-melb.pptxTypeScript-SPS-melb.pptx
TypeScript-SPS-melb.pptx
 
Mit6 094 iap10_lec01
Mit6 094 iap10_lec01Mit6 094 iap10_lec01
Mit6 094 iap10_lec01
 
DAA Unit 1.pdf
DAA Unit 1.pdfDAA Unit 1.pdf
DAA Unit 1.pdf
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
General Programming Concept
General Programming ConceptGeneral Programming Concept
General Programming Concept
 

Recently uploaded

Regression analysis: Simple Linear Regression Multiple Linear Regression
Regression analysis:  Simple Linear Regression Multiple Linear RegressionRegression analysis:  Simple Linear Regression Multiple Linear Regression
Regression analysis: Simple Linear Regression Multiple Linear RegressionRavindra Nath Shukla
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Neil Kimberley
 
Grateful 7 speech thanking everyone that has helped.pdf
Grateful 7 speech thanking everyone that has helped.pdfGrateful 7 speech thanking everyone that has helped.pdf
Grateful 7 speech thanking everyone that has helped.pdfPaul Menig
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsP&CO
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxpriyanshujha201
 
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyThe Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyEthan lee
 
Famous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st CenturyFamous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st Centuryrwgiffor
 
VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒anilsa9823
 
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...Lviv Startup Club
 
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLSeo
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesDipal Arora
 
It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayNZSG
 
Insurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageInsurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageMatteo Carbone
 
Organizational Transformation Lead with Culture
Organizational Transformation Lead with CultureOrganizational Transformation Lead with Culture
Organizational Transformation Lead with CultureSeta Wicaksana
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...anilsa9823
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangaloreamitlee9823
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Dave Litwiller
 

Recently uploaded (20)

Regression analysis: Simple Linear Regression Multiple Linear Regression
Regression analysis:  Simple Linear Regression Multiple Linear RegressionRegression analysis:  Simple Linear Regression Multiple Linear Regression
Regression analysis: Simple Linear Regression Multiple Linear Regression
 
Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023Mondelez State of Snacking and Future Trends 2023
Mondelez State of Snacking and Future Trends 2023
 
Grateful 7 speech thanking everyone that has helped.pdf
Grateful 7 speech thanking everyone that has helped.pdfGrateful 7 speech thanking everyone that has helped.pdf
Grateful 7 speech thanking everyone that has helped.pdf
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and pains
 
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptxB.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
B.COM Unit – 4 ( CORPORATE SOCIAL RESPONSIBILITY ( CSR ).pptx
 
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Greater Kailash ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
 
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyThe Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
 
Famous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st CenturyFamous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st Century
 
VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒
 
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
Yaroslav Rozhankivskyy: Три складові і три передумови максимальної продуктивн...
 
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRLMONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
MONA 98765-12871 CALL GIRLS IN LUDHIANA LUDHIANA CALL GIRL
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
 
It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 May
 
Insurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usageInsurers' journeys to build a mastery in the IoT usage
Insurers' journeys to build a mastery in the IoT usage
 
Organizational Transformation Lead with Culture
Organizational Transformation Lead with CultureOrganizational Transformation Lead with Culture
Organizational Transformation Lead with Culture
 
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
Lucknow 💋 Escorts in Lucknow - 450+ Call Girl Cash Payment 8923113531 Neha Th...
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
 
unwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabi
unwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabiunwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabi
unwanted pregnancy Kit [+918133066128] Abortion Pills IN Dubai UAE Abudhabi
 
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pillsMifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
Mifty kit IN Salmiya (+918133066128) Abortion pills IN Salmiyah Cytotec pills
 

IntroPython-Week02-StringsIteration.pptx

  • 1.
  • 2. OVERVIEW OF TODAY’S SESSION • While loops – a quick bit of unfinished business from last week! • Review of highlights from last week. • Some useful tricks with strings. • Working with ASCII codes to do more with strings. • Iteration with for loops. • Lots of coding!
  • 3.
  • 5. INFINITE WHILE LOOPS SAVE ALL YOUR FILES before running this one. The only difference is the condition in the while loop. What do you think will happen? Now run the code and see if you were right. Use Ctrl-C to cancel running code (NB this doesn’t always work) STOP: Don’t run this until you’ve read the instructions below.
  • 6.
  • 7. A QUICK RECAP (If you’re already happy with all this material, feel free to go back to any Challenges from last week that you haven’t finished, or work on a project of your own choice. This part won’t last very long.) • Every Python script you write will use variables. • A variable is a label (which you choose) that points to a location in memory. That location holds data of a certain type. • The commonest types are int, float, string and bool. • You can change a variable from one type to another if Python knows how to do that. • A Python script is a list of instructions. Usually the instructions run in sequence from to top bottom. • We saw how to use if to make decisions about whether to run a block of code or skip it. • We also saw how to use while to run a block of code multiple times. • We also used randint, which will be useful again today. • Remember we must import random to use it.
  • 8. Make sure you understand everything here before moving on!
  • 9. WHAT TO DO IF… …You need more time on what we just reviewed: • Follow along with the class for now. When it’s time for you to write some code, take your time and ask for help on the parts that you’re stuck on. There’s lots of coding time this week. …You want to move more quickly through the upcoming material: • Feel free to skim through the slides to the end of the section, where you’ll find more difficult challenges (some are pretty tough).
  • 10.
  • 11. CONVERTING OTHER TYPES TO STRINGS Most things in Python provide a way to convert them into strings. Remember, you do this using str(). So if x is something you want to turn into a string, str(x) usually does the job.
  • 12. Here are some of the built-in functions Python provides for doing things with strings. Notice that most of them use a dot after the variable name; we might talk more about this next week. This code is in the shared drive – no need to type it out. There are more powerful, “lower-level” techniques that we’ll look at later. There’s also a string library with more functions that we’ll mention in Week 4.
  • 13. COMBINING OPERATIONS The functions on the previous slide are all non-destructive, meaning they don’t change the original string. If you want to make multiple changes, you can use something like the above. Remember m = m + 1 from last week? This is the same thing.
  • 14. CHALLENGE Nonsense Generator Basic Version • Write a script that takes input from the user and replaces some letters with others to make nonsense. • A good start is to change all the vowels into other vowels. • Remember you can use numbers, spaces and punctuation as well as letters. Extensions • Use a while loop to make it run repeatedly. • Make your nonsense reversible: if I type x and it outputs y, typing y should make it output x again. • Experiment with s.center(50) on various strings. What does it do? • Look at the information on this page and try out various advanced string formatting techniques: https://pyformat.info/. • (Advanced) Look at this page and try out some of Python’s regular expressions: https://docs.python.org/2/howto/regex.html
  • 15. RANGES If you just want to loop over a range of integers, this is the easiest way. Run this and see what it prints. Think carefully about why this isn’t surprising! You may be surprised how often this is useful. There are lots of challenges that need this coming up, especially the more tricky ones.
  • 16. MORE FUN WITH STRINGS: CHR Computer memory is only really good for storing numbers, so everything else must be converted into a number before being stored. The standard way to convert letters and other text characters into numbers is ASCII. You can use the chr() function to convert an ACII number into its corresponding character.
  • 17. MORE FUN WITH STRINGS: ORD The ord() function does the opposite of chr(): it converts a character into its ASCII number. Look carefully at this code, it contains several things that we’ve learned this week.
  • 18. AN EASIER WAY TO LOOP OVER A STRING This is a bit more elegant than the previous one, but it only gives us the string one letter at a time. If you need to know where you are in the string, the version on the previous slide is still needed.
  • 19. CAESAR CIPHERS We end this session with an extended challenge based on the Caesar cipher. This is a way of encrypting a message made up of letters and spaces. We leave the spaces alone. The letters on the outer wheel are exchanged for the ones on the inner wheel. How many steps the inner wheel is rotated is the “key” to the cipher.
  • 20. Decode this message using the code wheel set as it is on the previous slide: IRMAHG BL XTLR If you want more practice, encode a simple sentence yourself (by swapping each letter on the outer ring for the matching one on the inner) and then check you can decode it (by reversing the process).
  • 21. CHALLENGE Caesar Cipher Basic Version • Get input from the user and print the result of applying the Caesar cipher to it with a fixed key of your choice. • This is tricky, so take your time and plan carefully. There’s more guidance on the next slide if you need it. Extensions • Let the user choose the key by typing, e.g., KEY=T to mean that the cipher “wheel” should be turned so that “A” matches “T”. Hint: use an if statement to check whether s[:4]==“KEY=“ • Similarly, if the user types “DEC=“ at the start of their input have your script decode it instead, using the current key. • Anyone who intercepts both the encrypted message and the key can decode the message if they can guess what your cipher code does. A Caesar cipher is very simple and easy to guess. Think about various ways you could make the cipher more complicated.
  • 22. HELP! • Start by creating an empty string that we’ll use to build up the output letter-by- letter. • Decide on a “key”, which is the number of steps the inner wheel has been turned. Store this in a variable. • Convert the input to uppercase and store this in another variable. • Note that the ASCII values of A-Z go from 65(=A) to 90 (=Z). • Now loop through this new variable character-by-character (you can use the “nice” version of looping through a string here). For each letter do this: • Check whether it’s a space. If it is, just add it to the output string • Else: • get its ASCII value using ord. • Add the key to the ASCII value. • If the result is more than 90, subtract 26 from it. This brings it back to the start of the alphabet again. • Convert this number to a letter using chr and add it to the output string. • When the loop has finished, print the output string. Here is a step-by-step guide to completing this challenge, in case you feel really stuck.