Let's learn some more Python syntax, using what we know in Snap!.
x = 0
x = 5
x = 5 + 3
x = 5 * 3
x = 5 % 3
x = 5 + 4 * 3
Python automatically uses order of operations to evaluate expressions with multiple operators. In the example above, Python will first evaluate 4 * 3, which equals 12, and then evaluate 5 + 12. In the example above, x equals 17. If you want to change the order in Python, use parentheses:
is the same as x = (5 + 4) * 3
Another important block we used with variables was the block. In Python, it is done a little differently.
Notice that and are equivalent. Python follows the structure of this second block to change the value of a variable.
and are the same as x = x + 8
(Quick Tip: x = x + 8
is the same as x += 8)
Here's a quick summary of many of the useful operators in Python shown side by side with their Snap! equivalent. We can see that Python operators like greater than or equal to >=
can save us a lot of time when writing our code, since in Snap! we would have needed to drag out multiple blocks.
Function | Snap! | Python |
---|---|---|
Addition | x + y |
|
Subtraction | x - y |
|
Multiplication | x * y |
|
Division | x / y |
|
Modulo | x % y |
|
Less Than | x < y |
|
Greater Than | x > y |
|
Equals | x == y |
|
Not Equal | x != y |
|
Not | not x |
|
Greater Than or Equal To | x >= y |
|
Less Than or Equal To | x <= y |
Be careful! Notice that in Python, =
is used to assign variables, and ==
is used to check the equality of values. Make sure you remember the differences between Snap! and Python syntax.