Comments, Expressions, Operators

Comments, Expressions, Operators#

Comments#

Comments are lines or parts of lines in the source code that are not interpreted by the Python interpreter. Their purpose is solely to make the source code more readable and understandable for other programmers, but also for yourself. Typically, after a week or two, a programmer is not able to remember the details of an implementation they have coded themselves. So comments help you to remember why you have chosen a particular solution to a problem. However, too many comments make the code less readable. So a good balance is needed. A general rule is to add comments where you made a non-trivial decision on a particular choice of implementation.

In Python a comment starts with #:

# This is a comment
spam = 1  # second comment...
          # ... and the third!
text = "# this is NOT a comment!"

Note that the last line does not contain a comment. Double or single quotes (", ') enclose a text sequence, typically called string, which we will learn more about in the next section.

Expressions#

Expressions are instructions that take data and perform an operation with it which and possibly result in some new data. Arithmetic expressions are an example of an expression. But also comparisons or the call of a function also are expressions.

In Python, expressions can be grouped using brackets and arithmetic expressions follow the same rules as one would expect such as the associative law and commutative law.

Here are some examples:

(50 - 5 * 6) / 7
17 // 3
17 % 3.0
16. ** 0.5
(5+1j) * 1j
5. == 5
(5 > 3) and (8 < 10)

Logical expressions, that are expressions which are either True or False, can be combined using logical operators such as and or or.

Operators#

Here is a list of common operators acting on numeric data, for a complete list of operator symbols have a look at the Python documentation.

Operator

Description

+

Summation

-

Subtraction

*

Multiplication

/

Division

//

Explicit floor division

%

Modulo for division of integer operands

**

Exponentiation

==

Equal

!=

Unequal

+=, -=, *=, /=, //=, …

Summation, subtraction etc. with simultaneous assignment

Some of the operators such as + and * are also available for sequence data, but we will cover this later. As we will see in the section on object-oriented programming, it is also possible to define a custom meaning of an operator symbol when defining your own data types by implementing special methods.