The if statement exists in any programming language, it is used in Java, C and Procedural Assembler. The syntax model for if in Python is different. In many ways, it is much simpler and more compact, but it has its own specific elements.
Python if/else syntax rules
Python is a scripting language, so its main purpose is to simplify the code and make life easier for the developer. The rule applies to all language objects, including the if statement. Unlike C-like languages, Python lacks curly braces, requiring a semicolon at the end of expressions. But there is one new element. This is a colon sign.
Easiest Python if/else example:
- >>>if c > 2:
The first line assigns a value to c. The second contains the main statement with a 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 do after itindent.
Why padding matters
For developers who are used to putting semicolons at the end of each expression, indentation may seem unusual. But in Python, the end of a line automatically means the end of the statement. All code is written vertically with logical indentation alignment. This makes it much easier to read.
Coding order determines the order in which multi-line and compound if/else statements are executed in Python:
- if a:
- if b:
- First expression
- Second expression
If you are working in the IDLE shell, the interpreter will automatically indent all the indents. But when using text editors, you will have to follow this yourself.
Why do we need optional instructions
In Python, if/else are also called conditional statements. This is a selection tool that reflects the main logic of the program code. An if can contain multiple statements, including other if statements. The if is followed by an optional else statement. If as a result of the conditions described in if, the interpreter does not return True, it goes to else.
For more complex code branches, an optional elif statement is introduced in some cases. It contains additional terms and conditions. If/elif/else constructs in Python look like this:
- if: If statement with conditional expression
- Associated block
- elif: Optional parts elif
- else:Optional block else
Optional instructions are followed by a colon and mandatory indentation. The else part is for handling situations in which no match is found in if/elif. According to the rules, each part of the code is processed sequentially. But conditional expressions cause the interpreter to jump. Therefore, they are also called flow control instructions in Python.