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

BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,noida100girls
 
Call Girls in Mehrauli Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Mehrauli Delhi 💯Call Us 🔝8264348440🔝Call Girls in Mehrauli Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Mehrauli Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
7.pdf This presentation captures many uses and the significance of the number...
7.pdf This presentation captures many uses and the significance of the number...7.pdf This presentation captures many uses and the significance of the number...
7.pdf This presentation captures many uses and the significance of the number...Paul Menig
 
/:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc...
/:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc.../:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc...
/:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc...lizamodels9
 
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
 
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...lizamodels9
 
Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999
Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999
Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999Tina Ji
 
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
 
Pharma Works Profile of Karan Communications
Pharma Works Profile of Karan CommunicationsPharma Works Profile of Karan Communications
Pharma Works Profile of Karan Communicationskarancommunications
 
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
 
The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024christinemoorman
 
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
 
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
 
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableCall Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableDipal Arora
 
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
 
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
Tech Startup Growth Hacking 101  - Basics on Growth MarketingTech Startup Growth Hacking 101  - Basics on Growth Marketing
Tech Startup Growth Hacking 101 - Basics on Growth MarketingShawn Pang
 
Eni 2024 1Q Results - 24.04.24 business.
Eni 2024 1Q Results - 24.04.24 business.Eni 2024 1Q Results - 24.04.24 business.
Eni 2024 1Q Results - 24.04.24 business.Eni
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfpollardmorgan
 
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
 

Kürzlich hochgeladen (20)

BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
BEST Call Girls In Old Faridabad ✨ 9773824855 ✨ Escorts Service In Delhi Ncr,
 
Call Girls in Mehrauli Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Mehrauli Delhi 💯Call Us 🔝8264348440🔝Call Girls in Mehrauli Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Mehrauli Delhi 💯Call Us 🔝8264348440🔝
 
7.pdf This presentation captures many uses and the significance of the number...
7.pdf This presentation captures many uses and the significance of the number...7.pdf This presentation captures many uses and the significance of the number...
7.pdf This presentation captures many uses and the significance of the number...
 
/:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc...
/:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc.../:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc...
/:Call Girls In Jaypee Siddharth - 5 Star Hotel New Delhi ➥9990211544 Top Esc...
 
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...
 
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
Lowrate Call Girls In Sector 18 Noida ❤️8860477959 Escorts 100% Genuine Servi...
 
Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999
Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999
Russian Faridabad Call Girls(Badarpur) : ☎ 8168257667, @4999
 
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
 
Pharma Works Profile of Karan Communications
Pharma Works Profile of Karan CommunicationsPharma Works Profile of Karan Communications
Pharma Works Profile of Karan Communications
 
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
 
The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024The CMO Survey - Highlights and Insights Report - Spring 2024
The CMO Survey - Highlights and Insights Report - Spring 2024
 
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...
 
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...
 
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableCall Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
 
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
 
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
Tech Startup Growth Hacking 101  - Basics on Growth MarketingTech Startup Growth Hacking 101  - Basics on Growth Marketing
Tech Startup Growth Hacking 101 - Basics on Growth Marketing
 
Best Practices for Implementing an External Recruiting Partnership
Best Practices for Implementing an External Recruiting PartnershipBest Practices for Implementing an External Recruiting Partnership
Best Practices for Implementing an External Recruiting Partnership
 
Eni 2024 1Q Results - 24.04.24 business.
Eni 2024 1Q Results - 24.04.24 business.Eni 2024 1Q Results - 24.04.24 business.
Eni 2024 1Q Results - 24.04.24 business.
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
 
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
 

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.