Understanding Python’s Conditional Statements
If you want to create code that is effective and efficient, you must be well-versed in conditional statements. The foundation of many programs, conditional statements are present in almost all programming languages. When writing conditional statements in Python, the keywords “if,” “elif,” and “else” are used. By using these statements, you may modify the way your code runs depending on particular circumstances.
Let’s examine conditional statements in Python in more detail.
The even integers between 0 and 9 will be printed in our first, straightforward example.
To show the strength and adaptability of conditional statements in Python, we will next move on to examples that are more complicated.
Even numbers between 0 and 9 should be printed.
Using a loop and the range function, we can display the even values between 0 and 9. Let’s examine how conditionals may be applied to get the same outcome, though. Take into account this code:
in range(10) for i
if I % 2 == 0:
print(i)
In this code, the “if” statement is used to determine whether the result of multiplying i by 2 equals 0.
If this criterion is satisfied, the code included in the “if” statement is run, and the character i is printed.
Understanding Conditional Statements using Modulo
Grasp Python’s conditional statements requires an understanding of the modulo notion. The modulo operator returns the remainder when two numbers are divided. In our example, the modulo operator was used to check whether i is even by seeing if the output of ‘i% 2’ equals 0.
The If Statement in Python
Let’s examine each part of the Python “if” statement in more detail. If is used as a conditional keyword at the start of the line, followed by a condition that is highlighted in green. It is determined whether or not this condition is true. The sentences that are indented below the “if” statement are carried out if the condition is satisfied.
if statements: condition
The criterion ‘i% 2 == 0’ in the above example determines if i is even. The “if” statement’s code is run and the character i is displayed if the condition is satisfied.
The Else and Elif Statements in Python
Python additionally has the “else” and “elif” statements in addition to the “if” statement. When you wish to describe an alternative set of steps to be done if the condition in the “if” statement is not fulfilled, you use the “else” statement. On the other hand, you may define extra conditions to be evaluated if the initial “if” statement fails by using the “elif” statement.
Here is an illustration of how to use the “otherwise” clause:
in range(10) for i
if i % 2 == 0:
print(i) otherwise
display(i + 10)
In this example, the code within the “else” line is performed, and the value ‘i + 10’ is displayed, if the condition in the “if” statement is not fulfilled (i.e., is odd).
Here is an illustration of how to use the “elif” statement:
in range(10) for i
If i% 3 equals 0, print (i)