Programming Python Handbook - Logiscool
Programming Python Handbook - Logiscool
MIX PROGRAMMING
PYTHON
STUDENT
COURSE NOTES
Mix Programming
With Python
First Edition
Logiscool Singapore
Published by
Logiscool Singapore
Printed in Singapore.
Mix Programming Pg 9
1 Introduction Pg 11
Python Pg 13
Real-world applications Pg 14
Motion Pg 15
2 Positioning Pg 17
Direction Pg 20
Movement Pg 22
Looks Pg 27
3 Display Pg 29
Size Pg 30
Opacity Pg 30
Colours Pg 31
Costume Pg 32
Scene Pg 34
Contents
Sensing Pg 43
4 Collision and Touch Pg 45
Inputs Pg 46
Time Pg 47
Data Pg 53
5 Variables Pg 55
List Pg 56
Functions Pg 60
Events Pg 69
6 Signals Pg 73
Clone Pg 75
Contents
Control Pg 79
7 Delay Pg 81
Loops Pg 81
If-Else Statements Pg 82
Cloning Pg 83
Operators Pg 89
8 Arithmetic Operators Pg 91
Boolean Values Pg 91
Comparison Operators Pg 92
Logical Operators Pg 92
String Pg 93
Assignment Statements Pg 94
Other Functions Pg 96
Contents
Physics Pg 105
9 Force and Gravity Pg 107
Friction Pg 109
Speed Pg 110
Collision Pg 111
Pen Pg 115
8 Drawing Pg 117
Pen Size Pg 118
Pen Colour Pg 118
Pen Shape Pg 119
9
Mix
Programming
Transitioning from block coding
to text-based coding is like
discovering that each blox is
actually made of text, and now
you write that text directly.
Introduction
Python
Real-world Applications
10
11
Introduction
Logiscool Coding Road Map:
Blox to Text
when started:
while True:
x += 10
This helps you see how the blocks you’ve been using are actually
made up of lines of code. Mix programming is like a bridge that
connects what you already know with what you’re going to learn next.
It’s a fun way to start exploring how text coding works while still using
the blocks that make things easy to understand.
12
Introduction
Text-based Programming
Text programming is like building your own LEGO set from scratch.
Instead of snapping together pre-made blocks, you create each
piece by writing out instructions.
write
when started:
yourself
while True:
x += 10
Python
Python is a programming language used by people
all over the world to create games, apps, websites,
and so much more.
Python was created in 1989 by a programmer
named Guido van Rossum. He wanted to design a
programming language that was both powerful
and easy to use, so that more people could learn
to code. Guido named it "Python" after a comedy
Guido van Rossum show he liked called "Monty Python's Flying Circus,"
(Creator of because he wanted the language to be fun and
Python)
accessible.
Since then, Python has become one of the most
popular programming languages in the world.
People use Python for all kinds of things, from
building websites and creating games to controlling
robots and exploring space! It’s used by big
Top companies
companies like Google and NASA, and even by that uses
scientists. Python
Real-world Applications
Let’s explore some of the amazing things you can do with Python in the
real world!
this is a cat this is a dog
Artificial ???
Intelligence (AI) :
and Machine
Learning (ML)
Data
Analytics :
(Weather
forecast)
In this example, we use Python to analyze weather data, such as
temperature and humidity. By examining these data points, Python
helps us forecast whether it will remain sunny, become cloudy, or if rain
is expected. This demonstrates how data analytics can be used to
effectively understand and predict weather patterns.
Robotics and
Automation :
Motion
noun [motion]
Positioning
Direction
Movement
16
17
Positioning
Positioning: Tell your actors where to go
Horizontal Position runs from the left to the right side
Vertical Position runs from the top to the bottom
Positioning
Increment: Increase (+)
Decrement:Decrease (-)
Make your actor go
towards the right
Increment
Y Position
Decrement
Y Position
19
Positioning
Positioning: Telling where your actors to go
*Mouse
Pointer =
Example:
Y
Center Position
Random
Position
Bottom
Bottom left go to
right
corner Pencil
Corner
X Position
20
Direction
A Direction refers to the path which someone or something moves
Rotate: Turning your actor to a certain direction
A degree is a unit used to represent the measurement of an angle on
how much to rotate. A full circle has 360 degrees.
0/360
315 45
270
90
225 135
180
Examples
1.
2.
21
Direction
Point: face towards the direction of something
This is a variable
Example:
r
Point towards ne
To
pl cor
eft the cupcake ht
co p rig
rn
er To
Bo
t tto
lef m
rig
m
otto r Random c or ht
B ne ne
r position r
co
22
Movement
Movement is an act of moving
10 steps
Positioning
x=0
y=0
setPosition(0, 0)
x += 10
x -= 10
y += 10
y -= 10
coordinateSystem = "center"
goTo(UFO)
goTo(Pointer.position)
goTo(Position.random())
goTo(Position.center)
goTo(Position.topLeft)
goTo(Position.bottomLeft)
goTo(Position.topRight)
goTo(Position.bottomRight)
24
Direction
This is a variable
called “heading”
heading = 135
turnRight(30)
turnLeft(20)
pointTowards(UFO)
rotationStyle = "leftRight"
rotationStyle = "allAround"
rotationStyle = "none"
variable value
(expression)
Assignment
heading = 135
Movement
move(10)
bounceOffEdge()
Sample Program
when started:
show()
heading = 90
setPosition(50, 7)
while True:
move(10)
wait(1)
turnRight(15)
When Started,
set the direction to 90 degrees angle, then
make the actor go to position: x = 50, y = 7.
Forever, make the actor move by 10 steps every second then
turn 15 degrees to the right
27
Looks
noun [looks]
Display
Size
Opacity
Colours
Costume
Scene
28
29
Display
Display: How do you want your actors to be shown on the screen?
Size
Size: How big or small something is
Opacity
Opacity describes how faded an object is
Colours
Each colour has a tint hue and tint shade. Tint adds an extra layer of
colour.
Tint hue: The colour spectre (rainbow)
Tint shade: The lightness and darkness of the colour.
Tint Hue
Tint
Shade
RGB colors, which stand for Red, Green, and Blue, are the primary
colors of light. This concept provides a more accurate representation of
how colors are displayed in the digital world.
Red
R: 0, G: 255, B: 255
Yellow Magenta
White
Green Blue R: 40, G: 62, B: 55
Cyan
32
Costume
Costumes are skins of an actor. An actor can have more than 1
costume.
*Costumes of an actor can be found in the design tab
Choose the
costume
that you
want your
actors to Costume name: Axolotl Pink Idle
wear
on Land
Costume
Switch to the Switch to the
previous next costume
costume of the of the actor
actor
Example
1.
10 11 12
2.
10 9 8
Scene
Scenes are background of the stage. A stage can have more than 1
scene.
*Scenes of the stage can be found in the design tab.
Choose a
background for
your stage
Stage name: Planets
Scene
Switch to the Switch to the
previous scene next scene of
of the stage the stage
Examples
1.
1 2 3
2.
1 3 2
Scene
In logiscool, "Move parallax" refers to the background/scene moving.
*Will dive deeper into this topic in class, trainer to demonstrate in
class
Same concept
Coding Example:
Display
show()
hide()
goBefore(UFO)
goAfter(UFO)
goToFront()
goForwardBy(1)
goToBack()
goBackwardBy(1)
say("Hello World!")
38
Size
This is a variable
called “size”
size = 30
size += 10
size -= 10
Opacity
This is a variable
called “opacity”
opacity = 60
opacity += 10
opacity -= 10
39
Colours
variable: tint
tint = 100
tint += 10
variable: tintHue
tintHue = 50
tintHue += 10
variable: tintShade
tintShade = 50
tintShade+= 10
setRgbTint(0, 0, 255)
resetTint()
variable += value
drop down menu for
some blox only variable -= value
variable /= value
variable *= value
40
Costume
variable: costumeName
variable: costumeId
setCostume(UFO_2)
nextCostume()
previousCostume()
To be used in a
condition
Example:
if isCostumeSelected(UFO_2): if costumeId == 1:
show() show()
41
Scene
variable: sceneName
variable: sceneId
setScene(Planets)
nextScene()
previousScene()
isSceneSelected(Planets)
To be used in a
condition
Spring_Forest_Starry_Night.move(-10)
Street_Light_Evening.moveLayer("Evening", -10)
42
Sample Program
when started:
while True:
setCostume(randrange(1, 30, 1))
if isCostumeSelected(Axolotl_Pink_Walk_1):
say(costumeName)
else:
say(costumeId) when started:
show()
wait(1) size = 50
setScene(Planets)
while True:
goTo(Pointer.position)
Sensing
present participle [sensing]
be aware of (something)
Clone
Clone
Actor
Check if your actor is
touching other actors
and their clones.Returns
a true or false value. The orange is touching the Axolotl
and its clones, therefore, the
answer is True.
Input
An input is something you give to a computer, like pressing a key or
clicking a mouse, to make it do something.
Time
Timer is used to measure time.
A timer starts time from 0 seconds.
Continue
counting
Forever, set the value of the variable time
to the timer
This way, the timer will be updating and
counting
48
Time
A date is a specific day, month, and year used to mark a point in time.
This is a variable.
Date 1 Date 2
Example:
Output:
49
touching(Axolotl_Pink)
touching(Edge.top)
touching(Edge.bottom)
touching(Edge.left)
touching(Edge.right)
touching(Edge.vertical)
touching(Edge.horizontal)
touching(Edge.any)
touchingActorOrClone(Axolotl_Pink)
variable: Pointer.x
variable: Pointer.y
distanceTo(Pointer.position)
50
Input
variable: Pointer.isDown
isPointerOver()
isKeyPressed("space")
isKeyPressed("right arrow")
isKeyPressed("a")
Others
variable: username
ask("What's your
name?")
To be used in a
condition
51
Time
Timer.read()
Timer.reset()
Date.now()
Date.daysSince2000()
Date.getFullYear()
Date.getMonth()
Date.getDate()
Date.getDay()
Date.getHours()
Date.getMinutes()
Date.getSeconds()
Sample Program
Simple Actor Movement Code.
When:
“a” key is pressed - move left | “d” key is pressed - move right
“w” key is pressed - move up | “s” key is pressed - move down
when started:
setPosition(0, 0)
show()
while True:
if isKeyPressed("w"):
y += 10
if isKeyPressed("s"):
y -= 10
if isKeyPressed("a"):
x -= 10
if isKeyPressed("d"):
x += 10
if touching(Edge.any):
setPosition(0, 0)
53
Data
noun [data]
Variables
List
Functions
54
55
Variables
A variable is a value that can change, depending on conditions or on
information passed to the program. When defined in the stage, it is
called a global variable and when it is defined in the actor, it is a local
variable.
List
An array is a data structure that can store a list of elements.
This is an array
The elements in this examples are:
block
Apple, Orange and Banana
To create an array:
The array blox array have to be
defined within the “define
variable” blox to become a list/
array variable.
To add/remove elements:
Elements
During
: Add
Initialisation
During Program:
List
Elements and Indexing
Each item in an array is called an
element.
List: Apple, Grape, Orange
In this example: Apple, Grape and
Element Count: 3
Orange are elements. There are 3
elements in the list.
An index in an array is a
List: Apple, Grape, Orange numerical position used to access
a specific element within the
Index Index Index array. The Index of an array starts
0 1 2 from 0, referring to the first
element.
Element
This Blox will return the index of
the element of the array selected.
If the element does not exist, it
will return -1.
Index of “Apple” is 0
Index
This blox will return the element
corresponding to the selected
index number in the array.
Index 1 of List is “Grape”
List
Elements and Indexing
Element
Index
Add a new element at the
selected index of the array.
Index
Index value
Increase/Decrease the
value of the element
at the selected index
of an array. Can be
used for both strings
List (before): Apple, Grape, 100
and numbers. *Best to
List (after): Apple, GrapeS, 89
only use on numbers
Element Count: 3
to avoid errors.
59
List
Contain function in List:
Check if the list contains
whatever you have typed in.
It will return 1 if it is true
and 0 if it is false.
List: Apple, Grape, Orange
Item: Orange (1), Banana (0), Kiwi (0)
Example:
Before: After:
List_1: Grape, Kiwi List_1: Grape, Kiwi, Apple, Banana
Element Count: 2 Element Count: 4
List_2: Apple, Banana List_2: Apple, Banana
Element Count: 2 Element Count: 2
60
Functions
Functions are self-contained blocks of code that perform a specific task
or set of tasks and can be called or invoked whenever needed in a
program, keeping your code neat and tidy.
Do you know that most of the blox you have used before are functions?
= blox consisting of 2
smaller individual
bloxs.
= shorter? That’s
because functions
work like shortcuts!
Functions
Functions have two main steps:
1. You create or define the function by writing it.
2. You use the function by calling it whenever you need it.
Function Body
The block of code
that defines what
the function does.
Return statement
The output the function
produces. Not all
functions need to have a
return value.
62
Functions
Step 2: Calling the Function
Calling function
Calling function_1, with the value
of the counter as the parameter.
The return value is then stored in
the variable counter.
63
Functions
Parameters (or arguments):
Passing arguments:
parameters 1 parameters 2
example:
parameter 1 is set to 87
parameter 2 is set to -9
since,
value_1 is parameter 1
value_2 is parameter 2
value_1 = 87
value_2 = -9
64
Functions
Return value:
The return value of a function is the output or result that the function
produces after completing its task. When a function is called, it can
process the inputs (or parameters) given to it and then send back a
value to the part of the program that called it.
number_1 = 13
Variables
number_1 = -8
number_2 = 5
showVariable(ref number_1)
hideVariable(ref number_1)
variable: number_1
variable: number_2
variable: number_3
number_1 = 10
number_2 = 10
number_3 = 10
number_1 += 1
number_1 -= 1
number_1 /= 1
number_1 *= 1
66
List
[ "Orange", "Apple" ]
List.append("Grape")
List.remove("Grape")
List.clear()
List.insert(2, "Grape")
List.pop()
List.pop(1)
List.index(0)
List[1]
List[1] = 10
67
List
List_1.extend(List_2)
List_1[1] += 23
List_1[1] -= 23
List_1[1] /= 23
List_1[1] *= 23
List_1.count("Apple")
List.reverse()
Sample Program
List = [ "Apple", "Orange" ]
when started:
while True:
showVariable(ref List)
if isKeyPressed("a"):
List.append(ask("What do you want to add?"))
if isKeyPressed("d"):
List.remove(ask("What do you want to remove?"))
if isKeyPressed("space"):
List.clear()
68
Functions
The def keyword is used to define a new function in Python. When you
write def function_name(): you are creating a function and giving it a
name.
A function is identified by
its name followed by
parentheses (), which may
also contain parameters,
that the function uses to
def function_1(value_1, value_2):
perform its task.
To be used in a
return (value)
function only
2 ways to call a
function
function_name(value 1, value 2)
Events
noun [event]
Events
Signals
Clones
70
71
Events
Events block are used at the top of any codes. We use events blocks to
tell our actors what to do when something changed.
Events
Events block are used at the top of any codes. We use events blocks to
tell our actors what to do when something changed.
Examples
Signals
Signals allow actors to communicate with each other.
Examples
Signals
Signals allow actors to communicate with each other.
Examples
Clone
A clone is a duplicate or a copy of an actor.
This block of code tells your clones what actions to do. Without
this block, your clones would not be able to do perform
anything.
The block of code is used for clones only.
Examples
Sample Program
This simple program demonstrates how to use events bloxs for when
you are creating clones and sending signals, enabling your program to
perform specific actions. Give it a try!
Program Explanation
Left-clicking the mouse creates a clone
that spawns at a random position. The
clone is programmed to move forward
continuously.
Events
when started:
when touched:
when clicked:
when keyPressed("space"):
when pointerOver:
when pointerOut:
when pointerOut:
In Python, the colon (:) signals the start of a code block associated with
a condition or function.
In when started:, the colon
when started : signals that the indented
setPosition(0, 0) lines should run when the
Indented
show() lines program starts, grouping
related instructions under
specific conditions.
78
Signals
broadcast("signal1")
broadcastAndWait("signal1")
when signalReceived("signal1"):
variable: event.data
broadcastData("message1", 10)
broadcastDataAndWait("message1", 10)
when dataReceived("message1"):
Clone
when cloned:
79
Control
noun [control]
Delay
if-else Statements
Loops
Cloning
80
81
Delay
Delay: to make something happen at a later time.
if-else statement
A condition is a specific requirement or expression that evaluates to
either true or false, determining the flow of a program or decision-
making process.
Loops
In coding, a loop is a sequence of instructions that keeps repeating until
a certain condition is reached.
This is a for loop, which continuously repeat the same action for
a specific number of times.
Cloning
Cloning refers to duplicating or creating a copy of something
Actor
A variable that stores the
clone count
number of clones of the
=5
actor
5 clones
created:
A list of all the clones created from an
actor
84
Cloning
The index of a clone of an actor.
clone id
Examples
Infomation of the
clone
85
Delay
wait(1)
example:
while not (counter == 3):
pass
if-else statement
if (condition):
actions
if (condition):
actions
else:
actions
example:
if (counter == 3):
show()
else:
hide()
86
Loops
while True:
while (condition):
actions
Cloning
variable: isClone
variable: cloneCount
createClone(UFO)
createCloneAndWait(UFO)
deleteClone()
deleteAllClonesOf(UFO)
variable: cloneId
getClone(1)
getCloneOf(1, UFO)
88
Sample Program
when started:
show()
size = 30
setScene(White)
while True:
showVariable(ref chosen_clone)
createClone(self)
wait(2)
when cloned:
size = 15
goTo(Position.random())
while True:
if cloneId == chosen_clone:
say(concat("Chosen: ", cloneId))
wait(1)
broadcast("signal1")
deleteClone()
else:
say(cloneId)
when signalReceived("signal1"):
chosen_clone = randrange(chosen_clone + 3, chosen_clone + 10, 1)
89
Operators
noun [operator]
Arithmetic Operators
Boolean Values
Comparison Operators
Logical Operators
String
Assignment Statements
Other Functions
90
91
Arithmetic Operators
An arithmetic operation is a basic action like addition, subtraction,
multiplication, or division.
Addition Subtraction
Multiplication Division
Multiple one number with the Divide one number from the other
other
Modulus
The modulus is the remainder after dividing
one number by another. 10 3 = 3,
remainder 1. The answer is 1.
Boolean Values
A Boolean value represents a truth value: whether it is TRUE or FALSE.
Comparison Operators
Comparison operations compare two values and return a Boolean
result, either True or False.
Logical Operators
Logical operators are generally used for combining two or more
relational statements. They return Boolean values, either True or False
String
A string is a series of characters.
Example of strings: "Apple" "Orange" "Red" "Hello!" "Xyz123"
*Sometimes numbers itself can also be considered strings
Concatenation: to link
something together in a
series or chain. Link 2
strings or values together
94
Assignment Statements
An assignment in Python is when you store the result of an expression
in a variable using the equals sign (=)
Variable = Expression
assignment
Assignment Statements
An expression in Python is a combination of values, variables,
operators, and function calls that, when evaluated, produces a single
value.
Examples of Expressions:
variables: total_fruits = 0, apples = 10, oranges = 8, kiwi = 5
Statements Explanation
Other Functions
Range with step Function:
This function generates a
sequence of numbers starting
from 0 to 9, and increases by
1 with each step. It is used in
a for loop.
Pick Random with Step
Function: This function
randomly selects a number
between 0 and 10, increasing
by 1 with each step.
example:
Other Functions
Y X
Inverse Tangent Function:
This function finds the angle in
degrees between the positive x-
axis and a point.
y - axis
point(y,x) = point(5,3)
*good to know (not tested).
Formula:
Angle
x - axis
Other Functions
Trigonometry is the study of the relationships between the angles
and sides of right-angled triangles, Trigonometry uses functions like
sine (sin), cosine (cos), and tangent (tan) to give you a number that
tells you something about an angle. These numbers are usually between
-1 and 1.
=1 =0 =1
Arithmetic Operators
Boolean Values
Comparison Operators
Logical Operators
condition and condition
condition or condition
not condition
Sample Program
when started:
setPosition(0, 0)
while True:
show()
if isKeyPressed("space") and not touching(Edge.top):
y += 10
while not not isKeyPressed("space"):
pass
101
String
len("hello")
"HeLLo".lower()
"hello".upper()
Other Functions
range(0, 10, 1)
randrange(0, 10, 1)
min(1, 2)
max(1, 2)
sum(1, 2)
pow(1, 2)
zip(1, 2)
divmod(1, 2)
Math.atan2(5, 3)
Math.roundToDigits(5, 3)
print("Hello!")
#"This is a comment"
103
Other Functions
Math.abs(45)
Math.random(45)
Math.round(45)
Math.floor(45)
Math.ceil(45)
Math.sqrt(45)
Math.sin(45)
Math.cos(45)
Math.tan(45)
Math.asin(45)
Math.acos(45)
Math.atan(45)
Math.ln(45)
Math.log(45)
Math.exp(45)
Math.pow10(45)
str(1) bin(1)
repr(1) oct(1)
number(1) hex(1)
list(1) chr(1)
bool(1) ord(1)
abs(1) reversed(1)
all(1) sorted(1)
any(1)
104
Sample Program
Lucky_Number = 0
Your_Number = 0
Score = 0
when started:
show()
while True:
showVariable(ref Score)
Lucky_Number = randrange(1, 11, 1)
while not (Your_Number >= 1 and Your_Number <= 10):
Your_Number = ask("Pick a number from 1 to 10:")
say("Choose a number between 1-10")
#"Check if 'your number' is equals to the 'lucky number'"
if Your_Number == Lucky_Number:
say("You Win!")
Score += 1
else:
say("You Lose!")
#"reset 'my number'"
Your_Number = 0
105
Physics
noun [physics]
Amount
of force
This is a variable
*To explore the physics engine in your code, you must set static to off,
allowing the object to move and interact with forces.
108
Friction
Friction is the force that opposes the motion of an object when it
comes into contact with another surface.
This is a variable
Distance
110
Speed
Speed is the measure of how fast an object is moving, calculated as the
distance traveled divided by the time it takes.
This is a variable
Speed
Direction
(speed angle) How fast do you want your
object/actor to move and in
what direction do you want
your actor to move to?
Collision
Collision is an occurrence where two or more objects come into contact
with each other, often resulting in a change in their motion or shape.
Collision: ON
physics.isStatic = False
physics.isStatic = True
physics.applyForce(10, 0)
physics.horizontalGravity = 0
physics.verticalGravity = 0
113
Friction
variable: physics.damping
physics.damping = 0.1
physics.damping += 0.1
physics.damping -= 0.1
physics.damping /= 0.1
physics.damping *= 0.1
Speed
variable: physics.speed
variable: physics.speedAngle
variable: physics.velocityX
variable: physics.velocityY
physics.setVelocity(10, 0)
physics.setAngularVelocity(10)
114
Collision
variable: physics.isCollides
variable: physics.isSensor
physics.isCollides = True
physics.isCollides = False
physics.isSensor = True
physics.isSensor = False
physics.enableWall("top")
physics.disableWall("top")
Pe n
verb [pen]
write or compose.
Drawing
Pen Size
Pen Colour
Pen Shape
116
117
Drawing
The pen tool in logiscool replicates the action of a human when using a
pen
Start drawing
Stop drawing
Examples
118
Pen Size
Pen size refers to how thick or thin your pen ink is.
Pen Colour
Set a pen colour either from using a hue value
or choosing from the colour palette.
Pen Shape
Pen Shape refers to the shape of your pen tip.
These are
variables
Examples
120
Drawing
pen.down()
pen.up()
clearPenTrails()
stampCostume()
Pen Size
variable: pen.size
pen.size = 1
pen.size += 1
pen.size -= 1
pen.size /= 1
pen.size *= 1
122
Pen Colour
variable: pen.shade
variable: pen.hue
pen.setCssColor("#0000FF")
pen.hue = 50
pen.hue += 10
pen.shade = 50
pen.shade += 10
Pen Shape
variable: pen.shape
pen.shape = 0
pen.shape = 3
pen.shape = 4
My Notes
My Notes
My Notes
My Notes
My Notes
My Notes
My Notes
My Notes
My Notes
My Notes