More Conditionals, Key Events, and Methods in Python
This week we are covering More Conditionals, Key Events, and Methods in Python. Once again we will code using CMU Academy IDE (Integrated Development Environment). CMU CS Academy is an online, graphics-based computer science curriculum taught in Python provided by Carnegie Mellon University. They create novel, world-class Computer Science education forthe classroom —and it’s entirely free. You can sign up for it here: CMU CS Academy
Alternatively, To get started in Python, I also recommend getting PyCharm: https://www.jetbrains.com/pycharm/
In each blog post, I will go over some examples, creative tasks that I created, related code and summarize the key concepts and syntax we learned .
Now here’s how I created this animated vintage Space Invaders Python code :
Here’s the concept summary for this week:
More Conditionals(if-elif-else Statements)
if-elif-else Statements
After we use
if
, we can useelif
to add another test that will only be tested if the first test was FalseNote that
elif
is actually short for else if
There can be many
elif
's following anif
, but at most one of their bodies will runUse
elif
withoutelse
, but you cannot useelif
withoutif
Code in an
else
body runs if all the tests before it were Falseelse
can be thought of in English as "otherwise"
Key Events
onKeyPress and onKeyRelease
onKeyPress
is called when a key is pressedThe parameter to
onKeyPress
iskey
Use the
key
parameter to test which key was pressed usingif
andelif
statementsUse
onKeyRelease
to run code when the user releases a keyThe arrow keys are represented as: “left”, “right”, “up” and “down”
Methods
Custom Properties
Can add your own custom properties to any shape
Ex. For a circle c, can initialize c.count = 0, and then can use that count throughout
Must be named something not used by CMU Graphics already
Can also have custom app properties that do not belong to a shape
Shape Methods
toFront()
brings a shape to the front of other shapestoBack()
pushes a shape to the back of other shapesMethods are basically the same as functions, with these two differences:
Methods are called differently: We use
shape.toFront()
instead oftoFront(shape)
Methods are like properties in that they can differ across shapes
Every shape has the
toFront()
andtoBack()
addPoint(x, y)
is only available for polygonsTakes the (x, y) values of some point on the canvas, and adds that point to the polygon
contains(x, y)
takes two values, x and y, and simply tells us whether or not the shape contains the point (x,y)returns True or False
shape.hits(x, y)
If the fill=None for the shape, any point inside the shape will return False
shape1.hitsShape(shape2)
tests if a shape hits another shapeshape1.containsShape(shape2)
tests if the first shape fully contains the second shapeapp.stop()
is called when we want no more events happen
I hope this helps.
Till next post, happy coding,
Alara