If statement in Python
Published: 2024-03-12 00:45:55

<p>In Python, the if statement is the basic tool used to&nbsp;make decisions when two or more alternative actions are to&nbsp;be&nbsp;taken. It is used to evaluate a condition and take an action based on the results of the evaluation.</p>

<p>The following example shows a simple <code>if </code>statements.</p>

<div class="autorun example">
<pre>
<code class="language-python">x = 10

if x == 10:
    print('x is equal to 10')</code></pre>
</div>

<p>Typically, the if statement consists of&nbsp; a condition, followed by one or more actions to take if the condition is met. The following shows the general syntax of the if statement.</p>

<div class="syntax">
<pre>
<code class="language-python">if &lt;condition&gt;:
    &lt;statements&gt;
elif &lt;condition&gt;:
    &lt;statements&gt;
else:
    &lt;statements&gt;</code></pre>
</div>

<p>As shown above, an <code>if </code>statement has three primary blocks, <code>if </code>, <code>elif </code>and <code>else</code>, together they may be referred to as<strong> conditional expression blocks.</strong></p>

<p>The&nbsp;<code>if </code>block signals the start of an if statement. It contains a condition that must be met in order for the code within the block to be executed.&nbsp; This block can stand alone in an if statement without <code>elif </code>or <code>else </code>blocks.&nbsp;</p>

<p>The&nbsp;<code>elif </code>block, also popularly known as the<strong>&nbsp;&ldquo;else-if&rdquo;&nbsp;</strong>block&nbsp; is used to check for additional conditions if the condition of the initial&nbsp;<code>if&nbsp;</code>block fails. We can have as much <code>elif </code>blocks as necessary but an <code>elif </code>block cannot stand alone ,&nbsp;there needs to be a&nbsp;&nbsp;preceding <code>if </code>block.</p>

<p>The <code>else</code> block gets&nbsp;executed when all the preceding <code>if </code>and <code>elif </code>blocks fails. Similarly an else block cannot stand alone, there must be a preceding <code>if </code>block.&nbsp; We can only&nbsp;have a single <code>else&nbsp;</code>block&nbsp;in one <code>if </code>statement.&nbsp;</p>

<div class="autorun example">
<pre>
<code class="language-python">
def check(x):
    if x &gt; 0: 
        print(f"{x} is positive") 
    elif x &lt; 0: 
        print(f"{x} is negative") 
    else: 
        print(f"{x} is zero") 

check(10)
check(-5)
check(0)
check(2)</code></pre>
</div>

<p>In the above example, <code>if </code>the value of <code>x </code>is greater than 0, the first if block gets executed. If the value of x is less than 0, the&nbsp;<code>elif </code>block gets executed, and if neither of the <code>if </code>and <code>elif</code> blocks are satisfied, the <code>else </code>block gets&nbsp;executed.&nbsp;</p>

<h2>Multiple elif blocks</h2>

<p>As we earlier&nbsp;said, we can have as much <code>elif </code>blocks as necessary, this allows us to chain multiple conditions together so that the block whose condition gets satisfied first is executed and the check terminates.</p>

<div class="autorun example">
<pre>
<code class="language-python">def check(age):
    if age &lt; 0: 
        print("Age entered is not valid") 
    elif age &lt;= 3: 
        print("You are a baby!") 
    elif age &lt;= 12: 
        print("You are a child!") 
    elif age &lt;= 18: 
        print("You are a teenager!") 
    else: 
        print("You are an adult!")

check(14)
check(25)
check(-4)</code></pre>
</div>

<h2>The if-else syntax</h2>

<p>The <code>elif</code> blocks are optional, they are only included when&nbsp;multiple conditions need to be tested and evaluated.&nbsp;If we have a binary situation with&nbsp;only two possibilities, then the&nbsp;<code>elif </code>block is not needed. In this case We would only need to use an <code>if </code>statement and an <code>else </code>statement. If the condition of the if block evaluates to&nbsp; <code>True</code>, its statements gets executed. Otherwise, the code within the else block gets executed.</p>

<div class="autorun example">
<pre>
<code class="language-python">def even_or_odd(x):
    if x % 2:
        print(f"{x} is odd.")
    else:
        print(f"{x} is even.")

even_or_odd(10)
even_or_odd(7)
even_or_odd(5)
even_or_odd(2)</code></pre>
</div>

<h2>Nested if statements</h2>

<p>Nesting is when an if statement appears inside the body of another if statement in any of its 3 primary blocks i.e <code>if</code>, <code>elif</code>, <code>else</code>.&nbsp;</p>

<p>There is really no limit on how nesting can occur or how deep it can get. The following demonstrates a possible structure of nested if statements:</p>

<div class="syntax">
<pre>
<code class="language-python">if &lt;condition&gt;:
    &lt;statements&gt;
elif &lt;condition&gt;:

    if &lt;condition&gt;
        &lt;statements&gt;
    elif &lt;condition&gt;:
        &lt;statements&gt;
    else:
        &lt;statements&gt;
elif &lt;condition&gt;:
      &lt;statements&gt;
else:
     if &lt;condition&gt;:
         &lt;statements&gt;
     else:
         &lt;statements&gt;</code></pre>
</div>

<div class="autorun example">
<pre>
<code class="language-python">def greater(a, b):
    if a &gt; b: 
        print(f"{a} is greater than {b}.") 
    else: 
        if a == b: 
            print(f"{a} is equal to {b}.") 
        else: 
            print(f"{a} is less than {b}.")

greater(10, 20)
greater(10, 5)
greater(10, 10)</code></pre>
</div>

<h2>Short Hand syntax</h2>

<p>If we only have a single <code>if </code>block in an if statement and its body is made of a single statement, we can put the single statement in the same line as shown below.</p>

<div class="syntax">
<pre>
<code class="language-python">if &lt;condition&gt;: &lt;statement&gt;</code></pre>
</div>

<div class="autorun example">
<pre>
<code class="language-python">x = 10

if x == 10: print('x is equal to ten')</code></pre>
</div>

<p>Python also supports a short hand syntax where simple if-else blocks are&nbsp;condensed into a single line. The short hand syntax is suitable in cases where the body of the <code>if</code> and <code>else</code> statements consists of only one statement each.</p>

<div class="syntax">
<pre>
<code class="language-python">&lt;statement&gt; if &lt;condition&gt; else &lt;statement&gt;</code></pre>
</div>

<p>The first statement is returned if the condition evaluates to <code>True</code>, otherwise the statement at the end is returned.&nbsp;</p>

<div class="autorun example">
<pre>
<code class="language-python">def check(x):
    return f'{x} is Odd' if x % 2 else f'{x} is Even'

print(check(10))
print(check(1))
print(check(7))
print(check(2))</code></pre>
</div>
<div class="related"><h3>Related articles</h3><ul><li><p><a class="text-success" href="https://www.pynerds.com/pythons-implementation-of-switch-caseexploring-match-case/">Python's Implementation of Switch-Case:Exploring match-case</a><li><p><a class="text-success" href="https://www.pynerds.com/python-for-loops/">Python for loops</a><li><p><a class="text-success" href="https://www.pynerds.com/python-while-loop/">Python while loop</a><li><p><a class="text-success" href="https://www.pynerds.com/with-statement-in-python/">with statement in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/pass-statement-in-python/">pass statement in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/uses-of-the-else-statement-in-python/">Uses of the else statement in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/name-variable-in-python/">__name__ variable in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/asyncawait-in-python/">async/await in Python</a></ul></div>