Week 4a - Basics of Lists
List
Create
none, string, lists
Access
len
slice
Update
# List reference problem
###################################################
# Student should enter code below
a = [5, 3, 1, -1, -3, 5]
b = a
c = list(a)
c[1] = 0
b[0] = 0
print a
print b
print c
###################################################
# Explanation
# The assignment b = a created a second reference to a.
# Setting b[0] = 0 also mutated the list that both
# a and b reference. As a result, a[0] == 0.
# See the Programming Tips videos for a more detail
# explanation and examples
Keyboard Input
# control the position of a ball using the arrow keys
import simplegui
# Initialize globals
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
ball_pos = [WIDTH / 2, HEIGHT / 2]
# define event handlers
def draw(canvas):
canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")
def keydown(key):
vel = 4
if key == simplegui.KEY_MAP["left"]:
ball_pos[0] -= vel
elif key == simplegui.KEY_MAP["right"]:
ball_pos[0] += vel
elif key == simplegui.KEY_MAP["down"]:
ball_pos[1] += vel
elif key == simplegui.KEY_MAP["up"]:
ball_pos[1] -= vel
# create frame
frame = simplegui.create_frame("Positional ball control", WIDTH, HEIGHT)
# register event handlers
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
# start frame
frame.start()
Tips
- some key like shift in simplegui KEY_MAP will become a number
- pressing a key for a long time will just call the keyboard handler once
Week 4b - Keyboard Control
Velocity Control
using draw handler to control the velocity can keep the ball moving
Global & Local for lists
a = [4, 5, 6]
def mutate_part(x):
a[1] = x #Global, don't need to declare glabal
def assign_whole(x):
a = x #local
def assign_whole_global(x):
global a
a = x #a become an int
mutate_part(100)
assign_whole(200)
assign_whole_global(300)
Tuple
- cannot change element in it
- string is a type of tuple