Syntax and Arithmetics
Python Syntax
Syntax in programming, including Python, refers to the programming language rules. The syntax determines the structure and interpretation of the code when it runs. It may be easier to learn Python and its syntax by trying and breaking it instead of purely reading the documentation. Let’s try running (and breaking) some code.
Commenting Your Code
Python uses #
for single-line, and '''...'''
or """ ... """
for multi-line
comments. The latter are technically just unused text objects, As for #
, any part
of a line after #
is completely ignored by the Python interpreter.
Arithmetic Operators
For example, let’s start with the basic arithmetics. Python uses the following operators to do basic arithmetics,
+
: addition,-
: subtraction,*
: multiplication,/
: division.
Feel free to edit the code cells. If you need to reset code to the default state, just reload the page.
When you run your code, Python interprets the code sequentially line-by-line. Try switching the sequence, deleting, and adding print statements to the above to see the effect.
Floor Division and Modulo Operators
In addition to these, Python also has integer division and modulo operators.
//
: floor or integer division.a // b
dividesa
byb
then returns an integer part of the quotient. This operation rounds down the result to the nearest whole number.
Note the absence of decimal point
.
that you get when using/
, e.g.,3.14..
.
%
: modulo,a % b
returns the remainder of the division.
Operator Precedence
The order of the arithmetic operations follows the usual operator precedence:
- parantheses
(...)
- multiplication and division (
/
or//
) - addition and subtraction.
Exercises
E1: Python Shell
Run some of the commands above in the Python shell.
- The shell displays a default representation of the commands’ outputs if you
don’t use
print
. The representation of an object (e.g., text), is more informative. That’s what you get when you enter commands into the shell. - The output of
print
is meant to be human-readable and formatted. This may hide some of the information about the object.
Keep the terminal open when reading through the pages of this site to quickly try out different variations of the commands in the shell.
E2: Fix a Syntax Error
Note that, compared to other programming languages, indentation is important in Python.
- Fix the error in the code so that it is able to run by correcting the indentation.
In your browser the above won’t run and might not display any errors. In Python, indentation defines a code block. We will revisit indentation in the coming sections.
E3: Floor Division with Negative Numbers
Apply //
to negative numbers. How does floor division behave in this case?
Tip: compare the results of floor division with the ones you get from the regular division operations
/
.