Download presentation
Presentation is loading. Please wait.
1
Introduction to Python
Week 2: Strings and Lists
2
Overview of Today’s Session
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
Review The main points from last week Time for questions
4
A quick Recap Every Python script you write will use variables.
(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.
5
Make sure you understand everything here before moving on!
6
…You need more time on what we just reviewed:
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).
7
Strings Working with ASCII codes Tricks with Strings
8
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.
9
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.
10
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.
11
Adding Strings This is a nice, simple thing you will probably use very often. Try it and see what it does (it’s almost certainly what you expect it to do).
12
Challenge Nonsense Generator Basic Version Extensions
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. Use a while loop to make it run repeatedly. Extensions 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: (Advanced) Look at this page and try out some of Python’s regular expressions:
13
Lists Creating and Working with lists Concepts and Motivation
14
Why Lists? So far we’ve been creating variables one at a time.
Sometimes that’s not good enough. For example, think about how the register for this class works. Imagine it was your job to write the code for a register like this. Never mind about making it look nice, let’s just think about how we’d store the information. We have a list of names, which could be stored as strings. But do you want a different variable for each string? What if a new student enrols late? What if someone leaves the course? You don’t want to have to rewrite your code if those things happen!
15
Why Lists? Also, sometimes we just need to store a LOT of variables. For example, when you start working with graphics you’ll often need to store the colour of each pixel on the screen. My laptop’s screen is 1366x768 pixels. That means there are 1,049,088 pixels, and each can be a different colour. Do I really want to write code with that many variables defined one by one? Of course not! There must be a better way.
16
This is NOT a list Maria John Faizal Janet This is what we DON’T want!
student1 student2 student3 student4 Each string is pointed to by its own variable and there’s no connection between them.
17
This is a list! John Maria Faizal Janet
students John Maria Faizal Janet 1 2 3 Now we have one variable, students, pointing at all the students’ names, which are just identified by number. NOTICE the numbers start at 0, not 1. Let’s see how this helps us.
18
Challenge List Slicing Basic Version
Go through the code in Week-02-ListExamples.py looking carefully at what each line of code does. (Be sure to run it and use the output to help you) Write your own script that starts with a list of five fruits and asks the user for the name of a fruit. It then adds this to the start of the list and prints the list. Use a while loop to allow the user to add multiple fruits to the list. If the user enters the name of a fruit that’s already on the list, remove it completely. Extensions With the above code: If the user enters “COUNT”, print how many fruits are in the list. Do not allow the size of the list to grow to more than 10. Make it case-insensitive; i.e., Apple, apple and APPLE should all be treated as the same fruit. Similarly, make it strip out any spaces and punctuation from the input. (Fiddly) Copy this list and turn it into a Python array: Reject input from the user if it doesn’t match one of these.
19
Start here Stop here List Slicing John Maria Faizal Janet Leslie Bob
students John Maria Faizal Janet Leslie Bob 1 2 3 4 5 Start here Stop here This gives us an array that starts at entry 2 of students and copies everything up to but not including entry 5.
20
Challenge List Slicing Basic Version
Go through the code in Week-02-ListSlicing.py looking carefully at what each line of code does. (Be sure to run it and use the output to help you). Slicing works on strings, too! Write a script that takes input from the user and outputs the following: The first three letters of the input The last three letters of the input The third, fourth and fifth letters of the input Extensions With the above code: Output the input with letters 3, 4 and 5 swapped with letters 6, 7 and 8. Output the input, but with its halves swapped over (i.e. second half first, first half second). Output the input, but with the second half in all capitals. Output the input, but with the middle third scrambled using your nonsense generator code from earlier (the first and last thirds should be untouched).
21
Looping Tricks with for loops and ranges
22
Introducing For Loops The real power of lists comes from the ability to loop (or “iterate”) through their elements one by one. This can be done with a while loop (it’s a challenge at the end) but this syntax is neater.
23
Challenge List Iteration Basic Version
Print the list of students, but convert each one to uppercase first. Print the list of students, but only the first three letters of each name (this could be part code that generates computer logons, for example). Print the list of students but miss out the last two. Hint: use slicing! Extensions As above but: Print the names in a numbered list. Hint: you’ll need another variable to keep count as you loop. Print the names but print the first name in uppercase, the second in lower, the third in upper etc. Hint: the modulus operator will help here.
24
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.
25
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.
26
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.
27
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.
28
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.
29
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).
30
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.
31
Help! Here is a step-by-step guide to completing this challenge, in case you feel really stuck. 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.
32
Harder Challenges! Easy-ish: Write a programme that tells the user if the text they entered is a palindrome (i.e. reads the same backwards as forwards). Moderate: Write a programme to convert any input text into Morse code. Harder version: make it capable of decoding Morse code as well. Moderate: Have a look at this web page and implement as many of the ciphers as you can: (NB they get very difficult lower down the list!) Moderate: Change your code to replace each character in the message with three identical copies of the encrypted character (you’ll need to change your decoding algorithm too, of course). Now simulate “noise” as follows: after encryption, randomly change 1% of the characters in the output to another, random character. When decrypting, use the fact that each character should be repeated three times to automatically “fix” errors introduced by the noise. This is an “error-correcting code”. Hard: Find a large piece of English text – perhaps a novel downloaded from Project Gutenberg. Convert it into all capitals and remove all spaces and punctuation (use Python to automate these tiresome tasks!). Write a programme to calculate the percentage of times each letter of the alphabet appears in the text. Save this information. Now write a programme that can crack a code written in the Caesar cipher using the information here: If you do use a big piece of text you’ll need to look up how to open and read from a file. Hard: As above but print the longest palindrome the text contains.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.