Welcome to the fifteenth chapter of this python course. Python lists and tuples were studied extensively in the last session, and we learned how to manipulate the data contained in these types of structures. You've only experienced sequential execution up to this point, where each statement is performed sequentially in the order they appear in the code.
However, the real world is frequently more nuanced. Sometimes, a program must skip over certain statements, run a set of statements repetitively, or pick between other sets of statements to execute. This is called "conditional branching."
That's when control structures come into play, which controls the sequence in which statements in a program are executed.
What will you learn?
The if statement is the first control structure you'll encounter in Python.
Real-world situations frequently need us to examine the information around us and then make a decision based on what we've observed. As an illustration;
Unless it's raining, I'll be mowing the yard. It's correct to say that if it's pouring or snowing, I won't be mowing the lawn.
This type of decision-making is performed in Python programs using the if statement. If an expression has a certain value, and that value is known, a statement or set of statements can be executed.
Outline
- To begin, you'll learn the basics of the if statement in its most basic form.
- Next, you will understand why control structures require a way for grouping statements together into compound statements or blocks using the if statement as a model.
- Finally, you'll learn how to write code that makes difficult decisions.
Let`s get started.
The if statement in Python
We'll begin with the simplest form of an if statement. This is how it appears in its most basic form:
As you can see:
- This "expr" is an expression that is evaluated within the context of logic.
- Python statements, like ‘statement’, must have an indentation of at least one space. (You'll understand why in a moment.)
Execution of the statement occurs when the expression evaluates to a "truthy" value. No action takes place if expr is false. You must include a colon (:) after expr. Python does not require the parentheses around expr, as some other programming languages do.
This type of if statement is used in a variety of ways:
There is no effect on pressing Enter key after you have typed the print('yes') expression when using these examples interactively in a REPL session. There are multiple lines in this command. You must press Enter a second time to complete it. Executing a script file doesn't necessitate the use of an extra newline.
Using Blocks and Indentation to Group Statements
Suppose, on the other hand, that you wish to assess a condition and then take many actions if it is true:
There is only one 'statement' in each of the cases above, as demonstrated. It's necessary to be able to express "Do this if [expr] is true."
Syntactic devices, which bring together several statements into a single compound statement or block, are the most common technique employed by most programming languages. Syntactically, a block is considered to be a single entity. Explanation: All statements in the block are performed when it is an "if" target and "expr" is true. None of them are true if expr is false.
It is possible to define blocks in virtually all programming languages, however, this is not always possible. Let's have a look at Python's approach.
Python indentation
You may have heard the offside rule in football, right? Well, in programming, the off-side rule is a tenet of the Python programming language. Indentation is used by rule-abiding languages to define blocks. Off-side rule adherent Python is one of few languages.
Indentation has a specific meaning in a Python program, as you learned in the last tutorial on the structure of Python programs. The reason for this is that indentation is used to denote blocks of related statements. A block in a Python program consists of a series of statements that are all indented the same way. Thus, a Python compound if statement looks like this:
Lines 2 to 5 are considered to be part of the same block because they all have the same indentation level. If expr is true, the entire block executes, while if expr is false, the block is skipped. Following the following statement> (line 6) execution continues.
Tokens are not used to indicate the end of a block. There are two ways to tell when a block has come to a close.
Take foo.py as an example:
This is what happens when you run foo.py:
Lines 2-5 have the same indentation and print () commands. As a result, they form the code that would be executed if the underlying assumption was correct. Because it is untrue, the entire block is ignored. It doesn't matter whether or not lines 2 to 5 are executed, the first statement with a lower indentation level, the print () statement on line 6, is executed.
Is there a limit for nested blocks?
There is no limit on how deep blocks can be nested. Each new block is defined by a new indent, and each previous block is ended by an outdent. In the end, the structure is simple to follow, consistent, and easy to understand.
This script, called blocks.py, is a bit more complicated.
The following is an example of what you'll see after running this script:
When entering multiline expressions into a REPL session, you must include an extra newline because of the off-side constraint. Otherwise, the translator would have no means of knowing the if block's final statement had been entered.
What Do Other Languages Do?
Perhaps you'd like to know what other options are out there. It's unclear how blocks are declared in languages that don't follow the off-side rule
To denote the beginning and end of a block in most programming languages, special tokens are used as a strategy. Curly braces () are used to define blocks in Perl, for example:
Other programming languages, such as C/C++ and Java, also make use of curly brackets in this fashion.
Algol and Pascal, on the other hand, employ the keywords begin and end to denote the beginning and finish of a block.
Which Is Better?
It's all about how you look at it. They tend to have a strong opinion about how they do things in general. The off-side rule can generate a lot of controversies when it comes up for discussion.
Advantages:
- Clean, concise, and consistent: Python's usage of indentation is excellent.
- Writing code in languages that do not employ the off-side rule, the indentation of code is fully independent of the block definition and code function. While it's possible to create incorrect impressions by simply looking at code, it's also possible to create incorrect impressions by only looking at code.
- Code formatting guidelines should be followed anyway, thus using indentation assures that you are adhering to them. This sort of mistake is practically difficult to make in Python.
Disadvantages:
- The majority of programmers dislike being compelled to accomplish things in a specific way. Generally, they have firm beliefs about what they think is attractive and what they think is not. Because they don't want to be confined to a single choice.
- This can make it difficult for the Python interpreter to detect the level of indentation when indented lines are accompanied by a combination of space and tab characters. Then again, it is possible to configure editors in a way that prevents them from doing this. No matter what programming language you use, it is generally discouraged to use tab and space together in source code.
The off-side rule is an issue you'll have to deal with if you are writing Python code. Python's control structures all rely on it, and you'll see this in several upcoming lectures. Many programmers initially resisted Python's approach to defining blocks, but they've since learned to enjoy it and even prefer it over more traditional methods.
The else and Elif Clauses
If a certain condition is met, you may wish to conduct a certain course of action, but if it isn't, you may want to specify another course of action. The else clause is used to accomplish this:
If expr> is true, the first suite is run and the second is skipped. Second Suite Execution Is Skipped If 'Expr' Is False Execution resumes after the second suite is completed. Indentation is used to distinguish between the two suites, as indicated in the preceding paragraph. For example, lines 4 to 5 are run, and lines 7 to 8 are omitted because x is less than 50:
Because x exceeds 50 in this case, the first suite is omitted in favor of the second, which is run.
It's also possible to branch execution based on a variety of possible outcomes. One or more elif clauses can be used to do this. Each expr is evaluated in turn by Python, which then executes the set of instructions associated with the first one that is found to be true.
How many elif clauses can be specified?
You can provide as many elif clauses as you like. The else clause is not required. One must be provided at the end if it is present:
Short-circuit evaluation of elif clauses
An if statement with elif clauses, like the ‘and’ and ‘or’ operators, uses short-circuit evaluation. The remaining expressions are not tested when one of the tests returns true and its block is run. This can be seen in the following example:
There is a zero division in the second equation, and an undefined variable var is referred to in the third. As long as the first criterion is met, neither option will be assessed.
One-Line if Statements
The following is a standard way to write if (expr) indented on a separate line from the statement (statement):
However, an entire if statement can be written on a single line. The following is essentially the same as the previous example. Semicolons are used to separate multiple statements on the same line.
The Ternary Operator in Python
One exception to this rule is when an entire if statement is written in one line. Functionally, this is just like the example above. Separated by semicolons, you can have multiple statements on a single line.
Unlike the other if statement forms, this one does not control the flow of program execution, unlike the ones listed above. It's more like an expression-defining operator. Conditional expr> is first evaluated in the above example. The expression evaluates to expr1 if it is true. It returns a value of expr2 if it is false.
It's important to note that the evaluation of the middle expression comes before the evaluation of the two ends, and as a result, only one of the two ends is returned. Here are a few real-world examples to illustrate my point:
Selective assignment of variables is a popular application of the conditional statement. Let's say you're trying to figure out which of two numbers is greater. You could, of course, use the built-in method max() to accomplish the same thing. But what if you want to start from scratch and develop your code?
Statement "pass" in Python
The term "code stub" refers to a placeholder for a section of code that hasn't yet been implemented, such as when writing a test case.
Token delimiters, such as the curly brackets in C or Perl, can be used to define a code stub in these languages. Perl or C code like the following is acceptable:
The curly braces here denote an empty area. Even if the expression x is true, Perl or C will do nothing after evaluating it.
Specifying an empty block is impossible because Python utilizes indentation rather than delimiters. A follow-up statement, either indented or on the same line, is required after an if statement that begins with if expr. Consider foo.py as an example:
Foo.py doesn't work if it is attempted to be run.
This issue can be solved with the Python pass command. It does not affect the program's behavior. With this placeholder, the interpreter is kept happy in situations where a statement is required syntactically but no action is desired:
Foo.py is now error-free:
Conclusion
Congratulations! You have completed this tutorial on conditional statements in Python. We've explored the if-else statement in Python code and learned how to organize statements into blocks and understand the control structure concept in Python. Developing more complicated Python programs relies heavily on understanding these ideas. The while statement and the for statement are two new control structures that will be introduced in the next tutorial.