Teaching London Computing

Similar documents
Python Intro GIS Week 1. Jake K. Carr

Working with Lists 4

Teaching London Computing

Data Structures. Lists, Tuples, Sets, Dictionaries

Sequences and iteration in Python

Introduction to Functional Programming

Teaching London Computing

Overview of List Syntax

Collections. Lists, Tuples, Sets, Dictionaries

Lists How lists are like strings

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

The Dynamic Typing Interlude

Lists, loops and decisions

Review 4. Lists and Sequences

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

Python I. Some material adapted from Upenn cmpe391 slides and other sources

LECTURE 2. Python Basics

Lessons on Python Functions

Announcements for this Lecture

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Introduction to Computer Science with Python Course Syllabus

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

Try and Error. Python debugging and beautification

Python for Finance. Control Flow, data structures and first application (part 2) Andras Niedermayer

The Big Python Guide

At full speed with Python

CSc Introduction to Computing

CPD for GCSE Computing: Practical Sheet 6 February 14

Python in 10 (50) minutes

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

CPSC 217 Midterm (Python 3 version)

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

Topic 7: Lists, Dictionaries and Strings

Compound Data Types 1

Data structure and algorithm in Python

OOP and Scripting in Python Advanced Features

Semester 2. Structured Programming. Modular Programming Top-down design. Essentials covered. More complex programming topics.

Fundamentals of Programming (Python) Getting Started with Programming

Python Unit

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Programming to Python

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Part III Appendices 165

Getting Started with Python

Announcements. Project 2 due next Monday. Next Tuesday is review session; Midterm 1 on Wed., EE 129, 8:00 9:30pm

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

Teaching London Computing

Impera've Programming

Lecture 7: Python s Built-in. in Types and Basic Statements

Lecture 2 Tao Wang 1

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala

Brush up Python. December 20, 2018

Statements 2. a operator= b a = a operator b

Arrays (& strings) Ch 7

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

Topic 1: Introduction

Python Tutorial. Day 1

Python debugging and beautification

CSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray

Introduction to Python

Introduction to: Computers & Programming: Strings and Other Sequences

Slide Set 15 (Complete)

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Chapter 6 Sub Procedures

Introduction to Programming in Python (2)

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Teaching London Computing

Turn in a printout of your code exercises stapled to your answers to the written exercises at 2:10 PM on Thursday, January 13th.

More Loop Examples Functions and Parameters

Ceng 111 Fall 2015 Week 8a

Exceptions CS GMU

ENGR 102 Engineering Lab I - Computation

Introduction to Programming Using Java (98-388)

Python Lists and for Loops. Learning Outcomes. What s a List 9/19/2012

Exercise: The basics - variables and types

Variable and Data Type I

CIS192 Python Programming

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

CIS192 Python Programming

Introduction to Python

Python and Bioinformatics. Pierre Parutto

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han

The Practice of Computing Using PYTHON

Problem Solving for Intro to Computer Science

Recall that strings and tuples are immutable datatypes, while lists are mutable datatypes. What does this mean?

Java+- Language Reference Manual


Fundamentals of Programming. Week 5 - Lecture 2: Efficiency continued. Merge sort. Sets. Dictionaries.

Teaching London Computing

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

NOTES: Procedures (module 15)

Introduction to Python

Variable and Data Type I

Transcription:

Teaching London Computing A Level Computer Science Topic 3: Advanced Programming in Python William Marsh School of Electronic Engineering and Computer Science Queen Mary University of London

Aims Further topics in programming Some Python-specific Representing information Arrays of multiple dimensions Python built-in types: tuples, dictionaries; sequences Exceptions: dealing with errors

Two Representation Problems Minesweeper squares Flagged / tested / hidden Mine / no mine Number of neighbouring mines Hangman words Letter at each position Letters used Letters uncovered

Hangman Example Representation changes program Letter Positions A 5 L 6 N 1 S 3 U 0, 2, 4 Complete word [ 'U', 'N', 'U', 'S', 'U', 'A', 'L']! Letters guessed [ 'A', 'E', 'T', 'S', 'R']! Current display [ '_', '_', '_', 'S', '_', 'A', '_']!

Arrays of Multiple Dimensions Standard part of A Level

Multidimensional Arrays Recall that Arrays are Lists in Python So far: arrays represent What about: X==0, Y==1 X==2, Y==3

Why Arrays? An array is a sequence of memory locations Simple and fundamental idea Really, lists are represented using arrays Arrays Fixed number of entries All entries the same size Continuous in memory Regular shape Lists Can be extended Can have different entries more complex Can be irregular We use lists to learn about arrays

Table of Data Sum the columns in a table of data 10 27 23 32 31 44 12 65 15 17 18 23???????? Issues Representation Algorithm

Table Representation Table represented by list of lists Quiz table = [ \! [10, 27, 23, 32], \! [31, 44, 12, 65], \! [15, 17, 18, 23] \! [ 0, 0, 0, 0] \! ]! table[0][1] ==?! table[1][2] ==?!

Printing a Column Two methods Use two indices def printcol1(table, coln):! string = ""! for rown in range(0, len(table)):! string += str(table[rown][coln]) + " "! print(string)! def printcol2(table, coln):! string = ""! for row in table:! string += str(row[coln]) + " "! print(string)! Select List from Table

Exercise: Sum Columns Adapt the code on the previous slide to print the sum of: A given column Of all columns

Built in Types in Python Important in Python programming Very useful Details specific to Python; related concepts elsewhere

Overview Lists [1,2,3,4] Ordered collection of items; often of the same type. Can be changed (mutable) Tuples (1,2,3,4) Immutable ordered collection; often different types Ranges range(1,5) Number sequence; used in for loops Sets {1,2,3,4} Unordered non-repeating collection Dictionaries {1:'one', 2:'two', 3:'three'} Mappings

Tuples Examples Convenient for returning multiple values from a function Unpack def gettwo():!!ms = input("a string> ")!!nm = input("a number> ")!!return((ms, int(nm)))!! >>> gettwo()! A string> Hello! A number> 99! ('Hello', 99)! >>> t = ("a", 1, [1])! >>> x,y,z = t! >>> z! [1]! Assign to multiple variables

Ranges Examples In a for loop: for x in range(1,10,2):!!print("x =", x)!! x = 1! x = 3! x = 5! x = 7! x = 9! Convert to a list >> list(range(0,-10,-1))!! [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]!

Sequences Strings, lists, tuples and ranges are all sequences

Mutable and Immutable Mutable == can change e.g. append an item to a list Immutable == cannot change Concatenating two lists does not change them Copied when necessary Lists, sets and dictionaries are mutable Strings, tuples and ranges are immutable

Sequences Mutable Only

Understanding Assignment Variables (and parameters) refer (or point) to objects Assignment (and function parameters) copy references x! [1,2,3,4,5]! y = x # assignment! x! y! [1,2,3,4,5]!

Other Languages Issue: copying large objects (long arrays) In Visual Basic, you can pass an argument to a procedure by value or by reference. This is known as the passing mechanism, and it determines whether the procedure can modify the programming element underlying the argument in the calling code. The procedure declaration determines the passing mechanism for each parameter by specifying the ByVal or ByRef keyword. Quoted from http://msdn.microsoft.com/en-gb/library/ddck1z30.aspx If an object is immutable, you cannot tell whether it is copied or referenced

Sets and Dictionaries Set: a collection of unique objects Not ordered Mutable (but elements must be immutable) Dictionary: a map from a key to a value Unique key Mutable (key must be immutable)

Set Examples >>> s = {1,2,3}! >>> t = set(range(2,11,2))! >>> t! {8, 2, 10, 4, 6}! >>> u = s.union([1,1,1])! >>> u! {1, 2, 3}! >>> u = s.intersection(t)! >>> u! {2}! >>> len(s)! 3! >>> {2,4}.issubset(t)! True! >>> s.issubset(t)! False! >>>! Making sets Set operations

Dictionary Examples >>> d1 = {'milk':2,'eggs':6,'tea':1}! >>> d1! {'eggs': 6, 'tea': 1, 'milk': 2}! >>> len(d1)! 3! >>> 'books' in d1.keys()! False! >>> 'records' in d1.keys()! False! >>> d2 = dict([((0,0),'b'),((0,1),'g'),((1,0),'b'), ((1,1),'G')])! >>> d2! {(0, 1): 'G', (1, 0): 'B', (0, 0): 'B', (1, 1): 'G'}! >>> d2[(1,1)]! 'G'! >>> d1['milk']! 2! Check keys Making a dictionary Tuple as a key Dictionary look up

Dictionaries versus Arrays Standard Array Index by number Indices continuous e.g 0 à 10 Fixed length Simple values: number, character Python Dictionary Key can be a string, pair, Gaps ok Can add and delete entries Any value even a dictionary In other languages, library has dictionary data structure

Exercise Suggest two representations each for minesweeper and / or hangman Write Python to create examples Write Python to update the state New location in the mine field tested New letter guessed in hangman

Exceptions What Happens When a Problem Occurs

Exception Example int("xyz") leads to an error Not a programming error: user input Program stops: Traceback (most recent call last):! File "<pyshell#32>", line 1, in <module>! int("xyz")! ValueError: invalid literal for int() with base 10: 'xyz'! Error or exception name

Exceptions Trying it out Try out the code Certain errors possible Catch the error (i.e. exception) if it occurs and run code to handle the error. Words Exception a type of error, with a name Handle respond to the error nicely Catch jump to error-handling statement

Exception Syntax Example try:! in_str = input("enter a number> ")! in_num = int(in_str)! except ValueError:! print("sorry", in_str, "is not an integer")! Two new keywords Statements where exceptions may occur Only if exception occurs

When to Use Exceptions Robust code: check for errors Why? Either: Check error cannot occur Or: Catch exceptions Exceptions used: User input OS operation (opening a file) When using library code

Summary Representing data Aspect of problem solving Easier in Python: build in data structures Handle exceptions for robust code