Section06: Sequences Chapter 4 and 5.

Slides:



Advertisements
Similar presentations
Games in Python – the easy way
Advertisements

ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Container Types in Python
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
Dictionaries Last half of Chapter 5. Dictionary A sequence of key-value pairs – Key is usually a string or integer – Value can be any python object There.
Lists Introduction to Computing Science and Programming I.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Computer Science 111 Fundamentals of Programming I Sequences: Strings.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Guide to Programming with Python
2 What is pyGame? A set of Python modules to make it easier to write games. –home page: –documentation:
January 24, 2006And Now For Something Completely Different 1 “And Now For Something Completely Different” A Quick Tutorial of the Python Programming Language.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Built-in Data Structures in Python An Introduction.
Functions Chapter 6. Function Overview We’ve used built-in functions: – Examples: print(“ABC”, x+10, sep=“:”) round(x * 5, 2) pygame.draw.circle(screen,
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
10. Python - Lists The list is a most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between.
Reference: The Game Loop Animation / Game loop 1. Update variables 2. [Get input from the user] (GameLoop only) 3. Draw (using variables)
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
Review: A Structural View program modules -> main program -> functions -> libraries statements -> simple statements -> compound statements expressions.
(More) Event handling. Input and Windowed-OS’s Windowed OS’s (Windows, OSX, GUI-linux’s) send messages (events) when the user does something “on” the.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
Section06: Sequences Chapter 4 and 5. General Description "Normal" variables x = 19 – The name "x" is associated with a single value Sequence variables:
String and Lists Dr. José M. Reyes Álamo.
Sprites (Images) and Sounds
Sound and more Animations
MOM! Phineas and Ferb are … Aims:
Part II Reference:
PYGAME.
Let’s Learn 2. Installing Pygame
8. Installing Pygame
Keyboard Input.
Module 4 String and list – String traversal and comparison with examples, List operation with example, Tuples and Dictionaries-Operations and examples.
Tuples and Lists.
Game Loops + Part II Reference:
Containers and Lists CIS 40 – Introduction to Programming in Python
CS 115 Lecture 8 Structured Programming; for loops
Section 6: Sequences Chapter 4 and 5.
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
CISC101 Reminders Quiz 2 this week.
Bryan Burlingame 03 October 2018
CHAPTER THREE Sequences.
Guide to Programming with Python
8. Starting Pygame Let's Learn Python and Pygame
CS190/295 Programming in Python for Life Sciences: Lecture 6
8 – Lists and tuples John R. Woodward.
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
4. sequence data type Rocky K. C. Chang 16 September 2018
I210 review.
Lists A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. Lists are.
String and Lists Dr. José M. Reyes Álamo.
(more) Python.
For loops Taken from notes by Dr. Neil Moore
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
And now for something completely different . . .
Python Review
Sequences Sequences are collections of data values that are ordered by position A string is a sequence of characters A list is a sequence of any Python.
CoE Software Lab II 1. Pygame Intro , Semester 2,
Enclosing delimiters Python uses three style of special enclosing delimiters. These are what the Python documentation calls them: {} braces # Sometimes.
Tuple.
Introduction to Computer Science
Presentation transcript:

Section06: Sequences Chapter 4 and 5

General Description "Normal" variables Sequence variables: x = 19 The name "x" is associated with a single value Sequence variables: L = (5, 17, 19, -1) A name which is associated with a group of values.

Python sequences Immutable types (Ch. 4) Mutables types (Ch. 5) Strings: a group of characters Tuples: a group of other python objects Mutables types (Ch. 5) Lists: a group of other python objects Dictionaries: a group of key-value pairs (the value is a python object), indentified by key.

Length of sequences Returns the number of "things" in the sequence. S = "ABCDEF" T = (1, 2, 3) U = (4, 5, (6, 7, 8), 9) len(S) # 6 len(T) # 3 len(U) # 4

Indexing Sequences (except Dictionaries) Index number identifies a position. s = "Oranges" Examples: >>> s[0] # 'O' >>> s[2] # 'a' >>> s[-1] # 's' >>> s[-2] # 'e' The indexed value can be used anywhere a "normal" variable / constant would -7 -6 -5 -4 -3 -2 -1 1 2 3 4 5 6 O r a n g e s

Slicing Sequences Returns a section of a sequence Doesn't work for Dictionaries. >>> s = "Apples-Oranges" >>> s[1:4] # "ppl" >>> s[5:9] # "s-Or" >>> s[-6:-1] # "range" >>> s[-5:-7] # "" >>> s[10:] # "nges" >>> s[:6] # "Apples" >>> s[1:10:2] # "plsOa" >>> s[12:8:-1] # "egna" >>> s[-1::-1] # "segnarO-selppA" (backward) -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 1 2 3 4 5 6 7 8 9 10 11 12 13 A p l e s - O r a n g

for loops A type of repetition, but tied to a sequence. Syntax: for var in seq: # for-loop block The number of items in seq controls the number of iterations. var: A variable, created / updated by python A reference to the "current" item in the sequence.

for loop example s = "ABCDE" for c in s: print(c) Outputs: A B C D E # Doing the same thing with a while loop i = 0 while i < len(s): c = s[i] print(c) i += 1 s = "ABCDE" for c in s: print(c) Outputs: A B C D E

range objects range([start,] end [, step]) Treated as a sequence Useful when used with for loops Example: for i in range(1, 6,2): # range is (1,3,5) print(i) s = "ABCDE" for i in range(len(s)): # range is (0,1,2,3,4) print(i, s[i])

a new random function random.choice(sequence) Returns a random element of sequence. s = "ABCDEFG" print(random.choice(s)) Here's how we could do this ourself: Indx = random.randint(0,len(s)-1) X = s[Indx] # Same as x = random.choice(s)

Concatenation Combining two sequences into a new one. s1 = "ABCDEF" s2 = "GHI" s3 = s1 + s2

count method All sequences have this method. Returns the # of times that value appears S = "ABCDEFGBH" S.count("B") # returns 2 S.count("AB") # returns 1 S.count("I") # returns 0

in operator val in seq Returns True or False if the given value appears in the sequence. Examples: S = "ABCD" "B" in S # True "X" in S # False "AB" in S # True

Tuples A (possibly) heterogenous group of python objects. Deliminted by parentheses (when creating) Examples: T1 = (1, 2, 3, 4, 5) T2 = ("ABC", "DEF", "GHI") T2[1] # "DEF" T2[1][0] # "D" T3 = (1.7, "XYZ", 19) T4 = () # Empty tuple T5 = (5,) # Tuple with only 1 elem. T6 = (10, 11, (12, 13), 14) # Nested T7 = (screen, marioSurf, luigiSurf)

Tuples, cont. All the previous operations, work with tuples [Try it!] Where have we seen tuples already? Colors (pygame.draw.xxx, screen.fill) Positions (pygame.draw.xxx) Window Dimensions (pygame.display.set_mode) Point-lists (pygame.draw.polygon) Rectangles (pygame.draw.rect)

2D Tuples A common name for a tuple with tuple (sub-)elements Example: T[1] + T[2] # (3,2,9,1,-2,10) T[1] + T[1] # (3,2,9,3,2,9) T[1][1] + T[2][-1] # 12

Tuple un-packing Another way to extract values from a sequence. x,y,z = T # x is 1, y is 2, z is 3 One catch: #variables on left must be == len(T)

Lists Like a tuple, but they are mutable. You can add elements You can remove elements You can change elements You can share references to the same thing. Delimited by square brackets. Note: All sequences use square brackets for slicing / indexing. The delimiters are only relevant when creating.

Lists Adding an element: H = L + G # H is now [4, 5, 1.0, 2.0, 3.0] G.append(9.0) # G is now [1.0, 2.0, 3.0, 9.0] G.insert(0, 11.0) # G is [11.0,1.0,2.0,3.0,9.0] G.insert(2, 0.0) # G is [11.0,1.0,0.0,2.0,3.0,9.0] Note: these are both methods of all list objects.

Lists, cont. Removing an element L = [1.3, 9.2, 5.8, 1.7, 1.3, 2.1] Using the remove method L.remove(9.2) # L is [1.3,5.8,1.7,1.3,2.1] L.remove(1.3) # L is [5.8, 1.7, 1.3, 2.1] L.remove(L[0]) # L is [1.7, 1.3, 2.1] L.remove(2.2) # ERROR! Using the del operator del L[0] Note: del can be used to "un-define" any variable, not just mutable seq. variables.

Lists, cont. Changing elements L = [1.1, 2.2, 3.3, 4.4, 5.5] L[0] = 9.9 # L is [9.9, 2.2, 3.3, 4.4, 5.5] L[1:3] = [10.1, 11.11, 12.12] print(L) # [9.9, 10.1, 11.1, 12.12, 4.4, 5.5]

Lists & Mutability Mutability means we can change values of a mutable object after it’s created. L = [1.2, 3.7, 5.0, 9.9, 10.3] This is changing the list: L[2] = 4.2 This is re-creating the list (we can do this with immutable types): L = L[:2] + [4.2,] + L[3:]

Lists & Mutability, cont. Mutability also means a variable of a mutable type is a reference (or pointer) to the memory location. L = [1.2, 3.7, 5.0, 9.9, 10.3] Address Value This is L 1024 8000 … This is the actual 1.2 list data. 8004 3.7 (4 bytes per float) 8008 5.0 8012 9.9 8016 10.3

Lists & Mutability, cont. This is important because assigning a new variable = to the mutable object simply copies the reference. L = [1.2, 3.7, 5.0, 9.9, 10.3] Address Value This is L 1024 8000 … This is the actual 1.2 list data. 8004 3.7 (4 bytes per float) 8008 99 8012 9.9 8016 10.3 Address Value This is L 1024 8000 … This is the actual 1.2 list data. 8004 3.7 (4 bytes per float) 8008 5.0 8012 9.9 8016 10.3 K = L K[2] = 1000 print(K) [1.2, 3.7, 1000, 9.9, 10.3] print(L) [1.2, 3.7, 1000, 9.9, 10.3] This is K 12100 8000 …

Lists & Mutability We’ll see other mutable objects in python: Dictionaries Objects (from Object-Oriented Programming)

Event (input) handling Part III Event (input) handling

Input and Windowed-OS’s Windowed OS’s (Windows, OSX, GUI-linux’s) send messages (events) when the user does something “on” the window: Move mouse Press a key Close the window Resize the window Minimize / maximize The window notifies the program when these first happen. The application can respond to these (event handling)

Input and Windowed OS’s An application can also use device-polling to get the current state of an input device. “Is the ‘a’ key currently pressed? Where is the mouse cursor?

Event handling in pygame The pygame.event.get() function returns a list of new event objects. Each object has a .type attribute (a variable) You can compare it to pygame.XYZ variables to determine its type. Depending on the type, the event object may have other Calling pygame.event.get() empties the event queue for your window.

Examples Write a program which: Can be closed by clicking the ‘X’ or by pressing escape. Can be resized / fullscreen-ed Draws a square at a random location when a key is pressed. Moves a circle when the arrow keys are pressed.

Device Polling in pygame Emptying the event queue saves input device state to various module variables pygame.mouse.xyz pygame.keyboard.xyz pygame.joystick.xyz You can call functions in these modules to determine the current state of the device. If you’re not doing event handling, you must call pygame.event.pump() to process events.

Device polling important func’s Mouse pygame.mouse.get_pos() pygame.mouse.get_pressed() Keyboard pygame.key.get_pressed() Joysticks: …

Example Write a program which: Draws a circle at the mouse cursor’s location That can’t go off-screen Draws a square controllable by the arrow keys. Quits by pressing escape.

A few pygame tidbits Clock objects Sounds / Music Font objects tick get_fps Sounds / Music loading and playing Font objects rendering blitting Images (sprites) loading and blitting Off-screen Surfaces

Back to sequences…

Examples Example1. Star-field Example2. Space-invaders start Moving Changing colors Example2. Space-invaders start Moving spaceship Fire key Moving (& Fading) bullets Power-up: stream of bullets Example3. Space-invaders, pt II Line of aliens Hit-detection Sounds

Dictionary A sequence of key-value pairs Key is usually a string or integer Value can be any python object There is no order to the elements So, there isn't a first or a last element Python uses its own algorithm to order elements (for efficient access) You access values by using the key.

Dictionary operations Creating an empty dictionary: D = {} Creating a dictionary with string-float pairs D2 = {"ABC":42.9, "DEF":13.8, "GHI":-19.1} Getting a list of keys or values D2.keys() # Returns ["ABC", "GHI", "DEF"] or something like this. Getting a list of values D2.values() # Returns [42.9, -19.1, 13.8]

Dictionary Index'ing Using an existing element print(D2["ABC"]) Changing a value for an existing key D2["ABC"] = 100.3 Adding a new value D2["XYZ"] = 0.0 Note how this looks the same as modifying.

Dictionary examples [Using integers as a key] [Load a sequence of sounds]