When writing a programme, there is almost always a need to create a branched algorithm with several variants of condition. For example, to use different language packages or software configuration mode for users with different language preferences. In this article, let's look at one of the most commonly used and simple Python3 constructs - if!
What is a conditional if construct in Python?
As mentioned above, algorithms are often branched and special language constructs are used to implement different scenarios:
The logic is, if [condition-1] is true, then execute [instruction-1]. Otherwise (first false) if [condition-2] is true, then execute [instruction-2], otherwise (all of the above are false) execute [instruction-3]. Note that the indentation or tab determines whether the next instruction line will refer to the construct or be separate from it. Let's consider the simplest example of usage:
min=1
if max>5 and min<2:
print(max+min)
The variables min, max are defined in advance and the condition that if max is greater than 5 and min is less than 2, then print (max+min) instruction should be executed. The instruction to be executed, if the condition is true, is separated by indents, like print(max+min) in this example. The result of the programme will look like this:
end
And if variables that do not satisfy the condition were specified, the conditional if construct would not execute the instructions included in it. And the output would look like this:
The following syntax is used to compose the condition:
- [value-1] == [value-2] equality check;
- [value-1] != [value-2] check for inequality;
- [value-1] >= or <= or > or < [value-2] check for magnitude.
Each of the presented expressions contains operands [value-1] and [value-2], as well as an operator between them, the boundness can be provided by additional values or and. And what if you need to perform an action when the condition is wrong? There is a block else for that!
Else block
The logic of the previous syntax was to check the data and perform the appropriate action if the value was True. But if it is necessary to introduce branching with an action when the condition is not fulfilled, we use else:
min=1
if max>5 and min<2:
print(max+min)
else:
print(‘Values din\’t calculate')
print (‘end’)
In this example, the instruction also checks the condition, but in case it is not fulfilled, the control will pass to the else block and the text will be displayed on the user's screen:
end
If the design command is a single line, the following syntax is acceptable if max>5 and min<2: print(max+min):
min=1
if max>5 and min<2: print(max+min)
else: print('Values din\'t calculate')
print ("end")
Usually such constructs are used to notify users about actions or changes in the algorithm's logic. But if it is necessary to check another condition, there is elif for such a condition.
As you can see this solution is much longer than the numerical rights designation, however, it is just as functional and fulfils the tasks. All steps in the tutorial can be performed on powerful cloud servers. Serverspace provides isolated VPS / VDS servers for common and virtualize usage.
It will take some time to deploy server capacity. After that you can connect in any of the convenient ways.
Elif block
The point of this block is to check for a new logical condition if the if [condition] is False. For example, this block can be useful when choosing between two paths:
if language == ‘en’:
print (‘Good evening!’)
elif language == ‘fr’:
print (‘Bonsoir!’)
else: print (‘Language udefined’)
If the user selects en, the standard condition will be fulfilled. If fr is selected, the elif block will take over and the command below will be executed. However, if none of the conditions is fulfilled, the else block will take over. The result of the above instruction will be the output:
Note that up to 2 branches of the algorithm are acceptable for this type of construction. For example, if the languages are more or equal to three, it is better to use the switch case construction, which is optimal for the work. But, what if you need to use conditions that depend on each other in the logic of the algorithm? It is possible to make them nested!
Nested if constructions
For more complex scenarios you can use nested constructs, they work the same way as normal ones by executing a block of nested instructions in them. Let's look at an example:
mode = "child"
if language == 'en':
if mode == "child":
print ("Hi, welcome to child mode!")
else: print ("Hi, welcome to adult mode!")
elif language == 'fr':
if mode == "child":
print ("Bonjour, bienvenue en mode enfant!")
else: print ("Bonjour, bienvenue en mode adulte!")
This instruction, depending on the language selected by the user and the mode the user is in, displays the appropriate greeting. Note that the indentation of nested conditions is also preserved! The output of this instruction will be:
Since the conditions for this path coincide, however, it is desirable to use nesting for two or three branches. In other cases, a switch case will do!
Knowing and knowing how to use conditional statements correctly is a fundamental part of programming skills. They provide an opportunity to create more interactive and adaptive applications that can respond to different input data and working conditions. Regardless of the complexity of the task, conditional constructs will help you implement the right logic and make your code more readable and maintainable.