Module: (Python) Conditional statement


Problem

12/17

Incomplete conditional statement

Theory Click to read/hide

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

Problem

You can formalize the solution of the problem of finding the maximum of two numbers using the incomplete form of the conditional operator.
Using the additional variable \(M\), the initial value of which is set equal to the value of the variable \(a\)< br /> Next, we check if the value of the variable \(b\) is greater than the value of the variable \(M\) , then we replace the value of the variable \(M\) with the value of the variable \(b\).

Using this scheme, it is easy to find the maximum value of three or more of their numbers.