Skip to main content

Section 3.7 Python recap

Conditionals. The instruction if ... else ... allows programmers to tell Python to execute different segments of code depending on some the trutth value of a given logical condition. Common logical conditions consist in comparisons of two mathematical expressions through the operators
  • < (smaller than);
  • <= (smaller than or equal to);
  • > (greater than);
  • >= (greater than or equal to);
  • == (equal to);
Recall that = is an assignment, the logical operator testing the equality of two expressions is ==.

Comparing floating-point numbers. Due to the ever-present round-off errors, it is never a good idea comparing with == two floating point numbers, as the following code shows:
A better solution is to fix some tolerance eps and asking that the distance between the two numbers is smaller than that:
Of course in this case by "equal" we really mean "close enough to each other for our purposes".

Defining functions. What if we need to define, within Python, a function, say \(f(x)=\sin x-3x^4\text{?}\) the simplest solution is using the syntax as in the example below:
In Python's jargon, these are called Anonymous functions.