If statement is in any programming language, it is used in Java, C and procedural Assembler. The if syntax is different in Python. In many ways, it is much simpler and more compact, but has its own specific elements.
If / else syntax rules in Python
Python is a scripting language, so its main task is to simplify the code and make life easier for the developer. The rule applies to all objects in the language, including the if statement . Unlike C-like languages, Python lacks curly braces, the need for a semicolon at the end of expressions. But there is one new element. This is a colon sign.
The simplest if / else example in Python:
- >>> c = 10
- >>> if c> 2:
- print (c)
- 10
The first line is assigned the value of the variable c . The second is the main instruction with the condition. After the colon, a nested block begins with the built-in print () function.
Despite the simplicity of the design, novice programmers make the same mistakes. They forget to put a colon and indent after it.
Why padding is important
For developers who are used to putting a semicolon at the end of each expression, indentation may seem unusual. But in Python, the end of a line automatically means the end of a statement. All code is written vertically with logical indentation alignment. Thanks to this, it is much easier to read.
The code execution order determines the execution order of multi-line and compound if / else statements in Python:
- if a:
- if b:
- First expression
- else:
- Second expression
If you work in the IDLE shell, the interpreter will put all indentation automatically. But when using text editors, you will have to monitor this yourself.
Why do we need optional instructions?
In Python, if / else are also called conditional statements. It is a selection tool that reflects the core logic of program code. Inside an if may be several instructions, including other ifs . An if statement is followed by an optional else statement . If, as a result of fulfilling the conditions described in if , the interpreter does not return True, it proceeds to else.
For more complex code branches, in some cases an optional elif statement is introduced. It specifies additional conditions. The if / elif / else constructs in Python look like this:
- if <condition1>: # if statement with conditional expression
- <expression1> # Associated block
- elif <condition2>: # Optional elif parts
- <expression2>
- else: # Optional else block
- <expression3>
After optional instructions, a colon and a mandatory indent are put. The else part is designed to handle situations in which no matches were found in if / elif . According to the rules, each part of the code is processed sequentially. But conditional expressions force the interpreter to perform transitions. Therefore, in Python, they are also called flow control instructions.