Incomplete conditional statement
If in the "otherwise" block you don’t have to do anything (for example: “if there is ice cream on sale, buy ice cream”, and if not ...), then the entire block “otherwise” you can omit and use an abbreviated (incomplete) form of the conditional operator:
if condition:
... # what to do if condition is true
The operation of choosing the maximum of two values is used very often, so Python has a built-in function
max
that can be called in this way
M = max(A, B)
There is also a similar function for finding the minimum value of two or more values -
min().
When choosing from two values in Python, you can use another form of the conditional operator, which works like the full form of the conditional operator.
M = a if a > b else b
If you need to do more than one if the condition is met, then all actions are written one under the other at the same shift level:
if a > b:
temp = a
a = b
b = temp
In this program, if
\(a>b\), then we swap the values of the variables. The
temp
variable is an auxiliary one.
Notice the same shifts from the left edge of all three operators. This tells the compiler that all three statements are executed provided that a>b.
Another subtlety of the Python language is the multiple assignment operator, which facilitates the exchange of two variables. It can be written like this:
a, b = b, a