Introduction to Python Week 3: Dictionaries, Files and Errors
The Week 2 Recap of Week 1, Recapped 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.
Recap of Week 2 Strings. Lists. Looping with for. We will only need some basic stuff on strings for this session. Lists. Lists are like houses on a street; you can access them by number (like when you write a letter) or by walking up the street sequentially (when you deliver flyers).# Lists can be sliced using [a:b] – this works on strings, too. Looping with for. This can be used to loop over a list or just over a range of numbers.
I added a line break here to make it easier to read. Make sure you understand everything here before moving on!
…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).
Dictionaries Arrays with better keys
But this isn’t always what we want. students John Maria Faizal Janet 1 2 3 Here’s our list of students from last time. We can loop through it or access a particular student by their number. But this isn’t always what we want. Suppose instead we want to store these students’ grades. We want to look up the grade by the student’s name, not by some arbitrary index number. We could do it with lists, but it would be ugly and inefficient code.
This is one of the things Python’s dictionaries are made to do. grades 46 57 79 64 John Maria Faizal Janet This is what we want – variables that store grades, and that we access by name instead of by number. This is one of the things Python’s dictionaries are made to do. If a list is like a street with numbered houses, a dictionary is like a village that doesn’t have proper roads but all the houses have names.
Challenge Shop Stock Dictionary Basic Version Extensions Look carefully at Week-03-DictionariesAndExceptions. This contains everything you need to know about dictionaries. When you first run the script, it crashes with an error. Fix this using a try block! Now create a new script to manage the stock of a shop. It should ask the user for the name of a product and the number in stock (two input statements) and then store the result in a dictionary. After each stock item has been added, print the dictionary. Use a while loop to allow multiple items to be added. Extensions Instead of replacing the stock count with a new one, add it. Thus, if the dictionary currently has “Apples”: 5 and the user types “Apples” and “3”, the dictionary should now have “Apples”: 8. The above works with negative numbers too (this could represent sales in the shop). Print a message if the user enters something that would take the stock for an item below zero. Add a second dictionary to store the price of each item. (This will need a third input from the user each time a new item is created, but not when an item is updated). Print the total value of the stock (quantity times price for each item) whenever it changes.
Exceptions Using “try” to stop your code crashing
This is an error. The code has been asked to do something it can’t do This is an error. The code has been asked to do something it can’t do. It has crashed (the script has stopped running) and printed this ugly message. This is OK if something catastrophic has happened. You usually expect your script to crash like this is the computer runs out of disk space. But usually you don’t want this to happen. You want to say something like “Try do do this thing, but if you run into a problem do these things instead”. That’s called exception handling. This is not so important if you’re writing little scripts for yourself, although it’s still often useful. But if you want to write commercial-standard software, it’s mandatory.
Try this. You’ll get an error, because you can’t divide by zero, but it isn’t very friendly. In a real programme this zero could have come from anywhere – user input, a file, other data etc. This could happen any time and will crash your programme if it does. Here’s we say that if any of the code inside the try block causes a ZeroDivisionError, the code there should stop running and we jump to the except block instead. The user never sees the Python error.
Files Accessing and writing files
Opening, Reading, Writing and Closing Open up Week03-files. Don’t run it yet; we will talk through it in detail in class. IMPORTANT This is the only part of the course where you could, in theory, do something nasty to your computer. For example, in theory you could write a Python script that will literally try to delete every file on your computer – including system files that may make it stop working completely. If you stick with the commands I’ve given you, you’ll be fine. Although you’re unlikely to do anything very bad by accident, I suggest that you get plenty of coding practice before using the full power of Python’s file management capabilities. When you feel ready, this web page will be useful: https://www.tutorialspoint.com/python/python_files_io.htm
Functions Making your code more modular
This Section is Optional Functions are an important part of programming in Python, but they could be considered a bit more advanced than most of what we do on this course. If you’d prefer to practice what we’ve been doing already and tune out of this section, that’s fine. However, it might clear up a few things that have been mysterious to you.
Here’s some code you might use to “clean up” text. Suppose you have to do this often in various places in your code. You’d have to copy and paste it each time. What a hassle! Plus, what if later you noticed that you missed out “£”, and needed to add it? You’d have to find all the places where you pasted the same code and change each one. You could miss some examples, or make other mistakes that cause weird problems.
What we’d like to do is take that code, package it up somewhere and give it a name. Then we can just invoke it by name each time we need it. Maybe like this: The label I’m using for this block of code The input I want it to work on
“I’m defining a function called tidyString that takes in one input, called “s” This is exactly the code we had before. Notice it works with “s”, which is whatever gets passed to the function. This outputs the result to whoever called the function in the first place.
Python has quite a few built-in functions, such as print(). You don’t have to know how they work internally, just what to pass in (a string) and what it does (outputs your string on the terminal).