Introduction to Python

Slides:



Advertisements
Similar presentations
JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Advertisements

Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Debugging Introduction to Computing Science and Programming I.
An Introduction to Textual Programming
by Chris Brown under Prof. Susan Rodger Duke University June 2012
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
Introduction to Computer Programming - Project 2 Intro to Digital Technology.
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
JavaScript: Conditionals contd.
CMSC201 Computer Science I for Majors Lecture 08 – Lists
JavaScript Controlling the flow of your programs with ‘if’ statements
Math operations 9/19/16.
The Little man computer
Development Environment
AP CSP: Cleaning Data & Creating Summary Tables
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Whatcha doin'? Aims: To start using Python. To understand loops.
User-Written Functions
Introduction to Python
Python Let’s get started!.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Arrays: Checkboxes and Textareas
ECS10 10/10
IF statements.
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
EET 2259 Unit 5 Loops Read Bishop, Sections 5.1 and 5.2.
Microsoft® Word 2010 Training
Create login screen Decide how you want you log in screen to work. I have 3 examples of different difficulty/approach, but you should have your own ideas.
Repeating code We could repeat code we need more than once: i = 1 print (i) i += 1 print (i) #… stop when i == 9 But each line means an extra line we might.
Intro to PHP & Variables
Exceptions and files Taken from notes by Dr. Neil Moore
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Lecture 4A Repetition Richard Gesick.
CSE341: Programming Languages Section 1
Selection CIS 40 – Introduction to Programming in Python
Topics Introduction to File Input and Output
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
CSE341: Programming Languages Section 1
Using files Taken from notes by Dr. Neil Moore
Building Web Applications
Exceptions and files Taken from notes by Dr. Neil Moore
Loops CIS 40 – Introduction to Programming in Python
Coding Concepts (Basics)
Introduction to TouchDevelop
Coding Concepts (Standards and Testing)
ERRORS AND EXCEPTIONS Errors:
CMSC201 Computer Science I for Majors Lecture 09 – While Loops
Data Structures & Algorithms
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Exceptions 10-May-19.
Topics Introduction to File Input and Output
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Exceptions 5-Jul-19.
Class code for pythonroom.com cchsp2cs
Python Simple file reading
Lecture 27: Array Disjoint Sets
Switch Case Structures
Presentation transcript:

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).