Serverspace Black Friday
JT
July 23, 2024
Updated July 23, 2024

How expression if work in Python?

Python

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:

Language syntax
Screenshot №1 — Language syntax

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:

max=12
min=1
if max>5 and min<2:
print(max+min)
Simple construction of if expression
Screenshot №2 — Simple construction of if expression

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:

13
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:

end

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:

max=12
min=1
if max>5 and min<2:
print(max+min)
else:
print(‘Values din\’t calculate')
print (‘end’)
Block else
Screenshot №3 — Block else

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:

Values didn't calculate
end

If the design command is a single line, the following syntax is acceptable if max>5 and min<2: print(max+min):

max=12
min=1
if max>5 and min<2: print(max+min)
else: print('Values din\'t calculate')
print ("end")
Else in another syntax
Screenshot №4 — Else in another syntax

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.

Create Server
Screenshot №5 — Create Server

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:

language = ‘fr’
if language == ‘en’:
print (‘Good evening!’)
elif language == ‘fr’:
print (‘Bonsoir!’)
else: print (‘Language udefined’)
Elif construction
Screenshot №6 — Elif construction

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:

Bonsoir!

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:

language = "en"
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!")

Encapsulated constructions
Screenshot №7 — Encapsulated constructions

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:

Hi, welcome to child mode!

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.

Vote:
5 out of 5
Аverage rating : 5
Rated by: 1
33145 North Miami, FL 2520 Coral Way apt 2-135
+1 302 425-97-76
700 300
ITGLOBAL.COM CORP
700 300

You might also like...

We use cookies to make your experience on the Serverspace better. By continuing to browse our website, you agree to our
Use of Cookies and Privacy Policy.