SlideShare ist ein Scribd-Unternehmen logo
1 von 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.

Weitere ähnliche Inhalte

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Catalogue ONG NUOC PPR DE NHAT .pdf
Catalogue ONG NUOC PPR DE NHAT      .pdfCatalogue ONG NUOC PPR DE NHAT      .pdf
Catalogue ONG NUOC PPR DE NHAT .pdfOrient Homes
 
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts ServiceVip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Serviceankitnayak356677
 
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...lizamodels9
 
Cash Payment 9602870969 Escort Service in Udaipur Call Girls
Cash Payment 9602870969 Escort Service in Udaipur Call GirlsCash Payment 9602870969 Escort Service in Udaipur Call Girls
Cash Payment 9602870969 Escort Service in Udaipur Call GirlsApsara Of India
 
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...lizamodels9
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst SummitHolger Mueller
 
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdfCatalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdfOrient Homes
 
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | DelhiFULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | DelhiMalviyaNagarCallGirl
 
A.I. Bot Summit 3 Opening Keynote - Perry Belcher
A.I. Bot Summit 3 Opening Keynote - Perry BelcherA.I. Bot Summit 3 Opening Keynote - Perry Belcher
A.I. Bot Summit 3 Opening Keynote - Perry BelcherPerry Belcher
 
Banana Powder Manufacturing Plant Project Report 2024 Edition.pptx
Banana Powder Manufacturing Plant Project Report 2024 Edition.pptxBanana Powder Manufacturing Plant Project Report 2024 Edition.pptx
Banana Powder Manufacturing Plant Project Report 2024 Edition.pptxgeorgebrinton95
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...lizamodels9
 
Sales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessSales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessAggregage
 
Case study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detailCase study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detailAriel592675
 
(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCR(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCRsoniya singh
 
NewBase 22 April 2024 Energy News issue - 1718 by Khaled Al Awadi (AutoRe...
NewBase  22 April  2024  Energy News issue - 1718 by Khaled Al Awadi  (AutoRe...NewBase  22 April  2024  Energy News issue - 1718 by Khaled Al Awadi  (AutoRe...
NewBase 22 April 2024 Energy News issue - 1718 by Khaled Al Awadi (AutoRe...Khaled Al Awadi
 
RE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechRE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechNewman George Leech
 
Islamabad Escorts | Call 03274100048 | Escort Service in Islamabad
Islamabad Escorts | Call 03274100048 | Escort Service in IslamabadIslamabad Escorts | Call 03274100048 | Escort Service in Islamabad
Islamabad Escorts | Call 03274100048 | Escort Service in IslamabadAyesha Khan
 
Non Text Magic Studio Magic Design for Presentations L&P.pptx
Non Text Magic Studio Magic Design for Presentations L&P.pptxNon Text Magic Studio Magic Design for Presentations L&P.pptx
Non Text Magic Studio Magic Design for Presentations L&P.pptxAbhayThakur200703
 
Pitch Deck Teardown: NOQX's $200k Pre-seed deck
Pitch Deck Teardown: NOQX's $200k Pre-seed deckPitch Deck Teardown: NOQX's $200k Pre-seed deck
Pitch Deck Teardown: NOQX's $200k Pre-seed deckHajeJanKamps
 

Kürzlich hochgeladen (20)

Catalogue ONG NUOC PPR DE NHAT .pdf
Catalogue ONG NUOC PPR DE NHAT      .pdfCatalogue ONG NUOC PPR DE NHAT      .pdf
Catalogue ONG NUOC PPR DE NHAT .pdf
 
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts ServiceVip Female Escorts Noida 9711199171 Greater Noida Escorts Service
Vip Female Escorts Noida 9711199171 Greater Noida Escorts Service
 
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
Call Girls In Connaught Place Delhi ❤️88604**77959_Russian 100% Genuine Escor...
 
Cash Payment 9602870969 Escort Service in Udaipur Call Girls
Cash Payment 9602870969 Escort Service in Udaipur Call GirlsCash Payment 9602870969 Escort Service in Udaipur Call Girls
Cash Payment 9602870969 Escort Service in Udaipur Call Girls
 
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
Call Girls In Radisson Blu Hotel New Delhi Paschim Vihar ❤️8860477959 Escorts...
 
Progress Report - Oracle Database Analyst Summit
Progress  Report - Oracle Database Analyst SummitProgress  Report - Oracle Database Analyst Summit
Progress Report - Oracle Database Analyst Summit
 
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdfCatalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
Catalogue ONG NƯỚC uPVC - HDPE DE NHAT.pdf
 
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | DelhiFULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
FULL ENJOY - 9953040155 Call Girls in Chhatarpur | Delhi
 
A.I. Bot Summit 3 Opening Keynote - Perry Belcher
A.I. Bot Summit 3 Opening Keynote - Perry BelcherA.I. Bot Summit 3 Opening Keynote - Perry Belcher
A.I. Bot Summit 3 Opening Keynote - Perry Belcher
 
Banana Powder Manufacturing Plant Project Report 2024 Edition.pptx
Banana Powder Manufacturing Plant Project Report 2024 Edition.pptxBanana Powder Manufacturing Plant Project Report 2024 Edition.pptx
Banana Powder Manufacturing Plant Project Report 2024 Edition.pptx
 
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
Call Girls In Sikandarpur Gurgaon ❤️8860477959_Russian 100% Genuine Escorts I...
 
Sales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for SuccessSales & Marketing Alignment: How to Synergize for Success
Sales & Marketing Alignment: How to Synergize for Success
 
Case study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detailCase study on tata clothing brand zudio in detail
Case study on tata clothing brand zudio in detail
 
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCREnjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
 
(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCR(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Hauz Khas 🔝 Delhi NCR
 
NewBase 22 April 2024 Energy News issue - 1718 by Khaled Al Awadi (AutoRe...
NewBase  22 April  2024  Energy News issue - 1718 by Khaled Al Awadi  (AutoRe...NewBase  22 April  2024  Energy News issue - 1718 by Khaled Al Awadi  (AutoRe...
NewBase 22 April 2024 Energy News issue - 1718 by Khaled Al Awadi (AutoRe...
 
RE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman LeechRE Capital's Visionary Leadership under Newman Leech
RE Capital's Visionary Leadership under Newman Leech
 
Islamabad Escorts | Call 03274100048 | Escort Service in Islamabad
Islamabad Escorts | Call 03274100048 | Escort Service in IslamabadIslamabad Escorts | Call 03274100048 | Escort Service in Islamabad
Islamabad Escorts | Call 03274100048 | Escort Service in Islamabad
 
Non Text Magic Studio Magic Design for Presentations L&P.pptx
Non Text Magic Studio Magic Design for Presentations L&P.pptxNon Text Magic Studio Magic Design for Presentations L&P.pptx
Non Text Magic Studio Magic Design for Presentations L&P.pptx
 
Pitch Deck Teardown: NOQX's $200k Pre-seed deck
Pitch Deck Teardown: NOQX's $200k Pre-seed deckPitch Deck Teardown: NOQX's $200k Pre-seed deck
Pitch Deck Teardown: NOQX's $200k Pre-seed deck
 

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.