# Chapter 5: Conditional Execution


## `if` Statement in Python

The `if` statement is used for **decision making** in Python.  
It allows a program to execute certain statements **only when a condition is True**.

Basic Syntax

```plaintext
if condition:
    statement1
    statement2
```

*   `condition` → Boolean expression (`True` or `False`)
    
*   The indented statements form the **if block**
    
*   The block executes only if the condition is `True`
    

### Flow of Execution

```plaintext
Condition True  -> Execute if block
Condition False -> Skip if block
```

**Example 1:** Division Check

```python
n1 = int(input('Enter a number : '))
n2 = int(input('Enter a number : '))

print(n1 + n2)
print(n1 - n2)
print(n1 * n2)

if n2 != 0:
    print(n1 / n2)
    print(n1 // n2)
    print(n1 % n2)

print(n1 ** n2)
```

**Why use** `if` **here?**

Division by zero causes an error.

```plaintext
if n2 != 0:
```

means:

> Execute division operations only when `n2` is not zero.

**Important Concept: Indentation**

Python uses **indentation** to define blocks.

```python
if condition:
    print("Inside if")
    print("Also inside if")

print("Outside if")
```

*   Recommended indentation → **4 spaces**
    
*   All statements in the block must have the same indentation
    

**Example 2:** Check Divisibility

```python
n1 = int(input('Enter a number : '))
n2 = int(input('Enter a number : '))

if n1 % n2 == 0:
    print('n1 is divisible by n2')
```

Explanation

```plaintext
n1 % n2
```

gives the remainder.

If remainder is `0`, the number is divisible.

**Example 3:** Check Even Number

```python
n1 = int(input('Enter a number : '))

if n1 % 2 == 0:
    print('n1 is even')
```

### Using Logical Operators

### `and`

Both conditions must be `True`.

```plaintext
if n1 % 2 == 0 and n2 % 2 == 0:
    print('Both are even')
```

### `or`

At least one condition must be `True`.

```python
age = int(input('Enter age : '))

if age < 5 or age > 80:
    print('Entry prohibited')
```

### `not`

Reverses the condition.

```python
if not n1 > 10:
    print('n1 is not greater than 10')
```

### Using `in` and `not in`

Example

```python
athletes = ['Ram', 'Sam', 'Shyam']

student = input('Enter student name : ')

if student in athletes:
    print('Scholarship awarded')
```

### Using `not in`

```python
failed_students = ['Pam', 'Sam', 'Ron']

student = input('Enter student name : ')

if student not in failed_students:
    print('You are promoted')
```

### Better Alternative to Multiple `or`

Instead of:

```python
if error_code == 400 or error_code == 404 or error_code == 301:
    print('Bad error')
```

Use:

```python
if error_code in {400, 404, 301}:
    print('Bad error')
```

A set is faster for searching.

**Example:** Palindrome Check

A palindrome reads the same forward and backward.

Examples:

*   madam
    
*   refer
    
*   level
    

```python
s = input('Enter a string : ')

if s == s[::-1]:
    print(f'{s} is a palindrome')
```

### Reverse of String

```plaintext
s[::-1]
```

This creates the reversed string.

For example:

```plaintext
"madam"[::-1]
```

gives:

```plaintext
"madam"
```

### Interactive Prompt Note

When writing compound statements in the Python shell:

```plaintext
>>> if True:
...     print("Hello")
...
Hello
```

You must press **Enter twice** to execute the block.

### Key Points Summary

*   `if` is used for conditional execution
    
*   Indentation defines blocks
    
*   Condition must evaluate to `True` or `False`
    
*   Logical operators:
    
    *   `and`
        
    *   `or`
        
    *   `not`
        
*   Membership operators:
    
    *   `in`
        
    *   `not in`
        
*   Python blocks begin after `:`
    

* * *

## `else` Clause in Python `if` Statement

The `else` clause is used with an `if` statement when you want to execute one block of code if the condition is `True` and another block if the condition is `False`.

Basic Syntax

```python
if condition:
    statements_if_true
else:
    statements_if_false
```

*   If the condition is `True` → `if` block executes
    
*   If the condition is `False` → `else` block executes
    

**Example 1:** Even or Odd

```python
n = int(input('Enter a number : '))

if n % 2 == 0:
    print('n is even')
else:
    print('n is odd')
```

Sample Run 1

```plaintext
Enter a number : 3
n is odd
```

Sample Run 2

```plaintext
Enter a number : 8
n is even
```

**How It Works?**

Condition:

```python
n % 2 == 0
```

*   If remainder is `0` → number is even
    
*   Otherwise → number is odd
    

**Example 2:** Palindrome Check

```python
s = input('Enter a string : ')

if s == s[::-1]:
    print(f'{s} is a palindrome')
else:
    print(f'{s} is not a palindrome')
```

Sample Run 1

```plaintext
Enter a string : refer
refer is a palindrome
```

Sample Run 2

```plaintext
Enter a string : learn
learn is not a palindrome
```

* * *

## Nested `if` Statements

An `if` statement can be written inside another `if` statement.

This is called **nested if**.

### General Structure

```python
if condition1:
    if condition2:
        statements
    else:
        statements
else:
    statements
```

**Example:** Small or Big Palindrome

```python
s = input('Enter a string : ')

if s == s[::-1]:

    if len(s) < 5:
        print(f'{s} is a small palindrome')
    else:
        print(f'{s} is a big palindrome')

else:
    print(f'{s} is not a palindrome')
```

### Explanation

***Outer*** `if`

```plaintext
if s == s[::-1]:
```

Checks whether the string is a palindrome.

***Inner*** `if`

```python
if len(s) < 5:
```

Checks the length of the palindrome.

*   Length less than 5 → small palindrome
    
*   Otherwise → big palindrome
    

### Sample Runs

Sample Run 1

```plaintext
Enter a string : malayalam
malayalam is a big palindrome
```

Sample Run 2

```plaintext
Enter a string : maths
maths is not a palindrome
```

Sample Run 3

```plaintext
Enter a string : noon
noon is a small palindrome
```

**Example:** Marks and Scholarship

```python
marks = int(input('Enter marks : '))

if marks >= 70:

    print('Well done, you have got A grade')

    if marks >= 90:
        print('You are awarded a scholarship')

else:

    print('Try to get A grade next time')

    if marks < 40:
        print('You really need to work hard')
```

### Logic of the Program

***Case 1: Marks ≥ 70***

Student gets:

*   A grade
    

If marks are also ≥ 90:

*   Scholarship
    

***Case 2: Marks < 70***

Student gets:

*   Improvement message
    

If marks are below 40:

*   xtra warning message
    

### Sample Runs

Sample Run 1

```plaintext
Enter marks : 95
Well done, you have got A grade
You are awarded a scholarship
```

Sample Run 2

```plaintext
Enter marks : 80
Well done, you have got A grade
```

Sample Run 3

```plaintext
Enter marks : 35
Try to get A grade next time
You really need to work hard
```

Sample Run 4

```plaintext
Enter marks : 45
Try to get A grade next time
```

### Quick Practice Programs

**1\. Check Positive or Negative**

```python
n = int(input("Enter number: "))

if n >= 0:
    print("Positive")
else:
    print("Negative")
```

**2\. Check Voting Eligibility**

```python
age = int(input("Enter age: "))

if age >= 18:
    print("Eligible to vote")
else:
    print("Not eligible")
```

**3\. Check Largest of Two Numbers**

```python
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

if a > b:
    print("a is larger")
else:
    print("b is larger or equal")
```

* * *

## `if`, `else`, and `elif`

### 1\. `if` Statement

The `if` statement is used for **decision making** in Python.

Syntax:

```python
if condition:
    statement
```

*   If the condition is `True`, the block executes.
    
*   If the condition is `False`, the block is skipped.
    

Example:

```python
n = 10

if n > 5:
    print("Number is greater than 5")
```

Output:

```python
Number is greater than 5
```

### 2\. Indentation in Python

Python uses **indentation (spaces)** to define blocks.

```python
if True:
    print("Hello")
    print("World")
```

Both statements belong to the `if` block.

Recommended indentation: **4 spaces**

### 3\. Example: Avoid Division by Zero

```python
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))

if n2 != 0:
    print(n1 / n2)
```

Condition:

```python
n2 != 0
```

*   If true → division happens
    
*   If false → division skipped
    

### 4\. Using Logical Operators in `if`

`and`

Both conditions must be true.

```python
if n1 % 2 == 0 and n2 % 2 == 0:
    print("Both numbers are even")
```

`or`

At least one condition must be true.

```python
age = 85

if age < 5 or age > 80:
    print("Entry prohibited")
```

`not`

Reverses the condition.

```python
if not False:
    print("Executed")
```

### 5\. Membership Operators with `if`

`in`

```python
athletes = ['Ram', 'Sam', 'Shyam']

if 'Sam' in athletes:
    print("Scholarship awarded")
```

`not in`

```python
failed_students = ['Pam', 'Ron']

if 'Sam' not in failed_students:
    print("Promoted")
```

### 6\. Using Sets in Conditions

Instead of:

```python
if error_code == 400 or error_code == 404 or error_code == 301:
    print("Bad error")
```

Use:

```python
if error_code in {400, 404, 301}:
    print("Bad error")
```

This is:

*   shorter
    
*   cleaner
    
*   faster
    

### `if-else` Statement

Used when we want one action for `True` and another for `False`.

Syntax:

```python
if condition:
    statements
else:
    statements
```

**Example:** Even or Odd

```python
n = int(input("Enter a number: "))

if n % 2 == 0:
    print("Even")
else:
    print("Odd")
```

**Example:** Palindrome Check

```python
s = input("Enter string: ")

if s == s[::-1]:
    print("Palindrome")
else:
    print("Not palindrome")
```

### Nested `if`

An `if` inside another `if`.

Example:

```python
s = input("Enter a string: ")

if s == s[::-1]:

    if len(s) < 5:
        print("Small palindrome")
    else:
        print("Big palindrome")

else:
    print("Not palindrome")
```

Nested `if` Example with Marks

```python
marks = int(input("Enter marks: "))

if marks >= 70:
    print("A grade")

    if marks >= 90:
        print("Scholarship awarded")

else:
    print("Try again")

    if marks < 40:
        print("Work harder")
```

### `elif` Statement

`elif` means:

```plaintext
else if
```

Used for checking multiple conditions.

Syntax:

```plaintext
if condition1:
    block1

elif condition2:
    block2

elif condition3:
    block3

else:
    block4
```

Only **one block** executes.

### Grade Program Using `elif`

```plaintext
marks = int(input("Enter marks: "))

if marks >= 70:
    grade = 'A'

elif marks >= 60:
    grade = 'B'

elif marks >= 50:
    grade = 'C'

elif marks >= 40:
    grade = 'D'

else:
    grade = 'E'

print("Grade:", grade)
```

***Why*** `elif` ***is Better***

Without `elif`, all conditions are checked.

With `elif`:

*   checking stops after first true condition
    
*   program becomes faster
    
*   code becomes cleaner
    

### Menu-Driven Program Using `elif`

```python
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))

print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

choice = input("Enter choice: ")

if choice == '1':
    print(x + y)

elif choice == '2':
    print(x - y)

elif choice == '3':
    print(x * y)

elif choice == '4':
    print(x / y)

else:
    print("Wrong choice")
```

### Quick Summary Table

| Statement | Purpose |
| --- | --- |
| `if` | Execute block if condition is true |
| `else` | Execute block if condition is false |
| `elif` | Check multiple conditions |
| Nested `if` | `if` inside another `if` |
| `and` | Both conditions true |
| `or` | Any one condition true |
| `not` | Reverse condition |

* * *

## Short-Circuit Behavior of `and` and `or`

Python uses **short-circuit evaluation** with logical operators `and` and `or`.

This means:

*   Python sometimes skips evaluating the second operand.
    
*   This improves efficiency.
    
*   It also helps avoid errors.
    

### Short-Circuit with `and`

**Rule**

For:

```python
A and B
```

*   If `A` is `False`, Python does NOT evaluate `B`.
    
*   Because the final result will already be `False`.  
    

**Truth Table of** `and`

| A | B | A and B |
| --- | --- | --- |
| False | False | False |
| False | True | False |
| True | False | False |
| True | True | True |

Example

```python
x = 0

if x != 0 and 10/x > 2:
    print("Hello")
```

***What happens?***

*   `x != 0` → False
    
*   Python stops immediately
    
*   `10/x` is never evaluated
    

So:

*   No divide-by-zero error occurs  
    

### 2\. Short-Circuit with `or`

**Rule**

For:

```plaintext
A or B
```

*   If `A` is `True`, Python does NOT evaluate `B`.
    
*   Because the final result will already be `True`.  
    

### Truth Table of `or`e

| A | B | A or B |
| --- | --- | --- |
| False | False | False |
| False | True | True |
| True | False | True |
| True | True | True |

Example

```plaintext
x = 10

if x > 5 or 10/x > 2:
    print("Hello")
```

***What happens?***

*   `x > 5` → True
    
*   Python skips `10/x > 2`
