Python if else Conditional Statement

By YBI Foundation

CONTENT

  • Introduction
  • Solved Problems
  • Unsolved Problems
  • Check Your Understanding

​Introduction

Imagine you’re playing a game where you need to decide what to do based on a rule—like going outside if it’s sunny or staying in if it’s raining.

The if-else statement works the same way: it helps a computer make choices!

In Python, you start with if, add a question (like “Is the score more than 50?”), and write what happens if the answer is yes. Then, you use else to say what happens if the answer is no. It’s like giving the computer a simple plan: “If this, do that; if not, do this instead.” 
The if-else statement is easy to learn and super important for making games, apps, or even homework helpers.
​Basic Syntax:
if condition:
    execute this code block if condition is True
else:
    execute this code block if condition is False
SOLVED PROBLEMS

Solved Problems

​1. Even or Odd:

Determine whether a given number is even or odd

​Code </>:
​# if else statement
number = 7
if number % 2 == 0:
  print(number, "is an even number")
else:
  print(number, "is an odd number")

Output:

7 is an odd number

Explanation:

We have a number, let's say 7.
We use the % operator (called the modulo operator) to find the remainder when the number is divided by 2.
If the remainder is 0, the number is even, and the code prints "7 is an even number".
If the remainder is not 0, the number is odd, and the code prints "7 is an odd number".
In this case, the remainder when 7 is divided by 2 is 1, so the else part is executed.

​2. Pass or Fail:

Determine if a student has passed or failed an exam, given their grade (A, B, C, D, E, or F). Student passes with grades A, B, or C.

​Code </>:
​# if else statement
grade = "B"
if grade == "A" or grade == "B" or grade == "C":
  print("Congratulations! You passed the exam.")
else:
  print("Sorry, you did not pass the exam.")

Output:

Congratulations! You passed the exam.

Explanation:

We have a student's grade, for example, "B".
The if condition checks if the grade is "A", "B", or "C". We use or to check multiple possibilities.
If the grade is one of those, the computer prints "Congratulations! You passed the exam."
If the grade is anything else (like "D", "E", or "F"), the computer prints "Sorry, you did not pass the exam."
Here, the grade is "B", so the if part is executed

​3. Voting Eligibility:

Check if a person is eligible to vote, given their age (the voting age is 18).

​Code </>:
​# if else statement
age = 19
if age >= 18:
  print("You are eligible to vote.")
else:
  print("You are not eligible to vote.")

Output:

You are not eligible to vote.

Explanation:

We have a person's age, let's say 19.
The if condition checks if the age is greater than or equal to 18.
If it is, the code prints "You are eligible to vote."
If it's not, the code prints "You are not eligible to vote."
Since 19 is greater than 18, the if part runs.

​4. First Letter:

Check if a given word starts with the letter "A".

​Code </>:
​# if else statement
word = "Apple"
if word[0] == "A":
  print("The word starts with the letter A.")
else:
  print("The word does not start with the letter A.")

Output:

The word starts with the letter A.

Explanation:

We have a word, "Apple".
In Python, word[0] gives you the first letter of the word.
The if condition checks if the first letter is "A".
If it is, the code prints "The word starts with the letter A."
If it isn't, the code prints "The word does not start with the letter A."
"Apple" starts with "A", so the if part is executed.

​5. Sign of a Number:

Determine if a given number is positive or not (i.e., it's either zero or negative).

​Code </>:
​# if else statement
number = -5
if number > 0:
  print("The number is positive.")
else:
  print("The number is negative.")

Output:

The number is negative.

Explanation:

We have a number, -5.
The if condition checks if the number is greater than 0.
If it is, the number is positive
If it is not, the number is either negative or zero.

UNSOVED PROBLEMS

Unsolved Problem

1. Library Book Reminder

Imagine you have a variable days_late that shows how many days a library book is overdue. Write a Python program using an if-else statement to check if this number is greater than 0. If it is, print a reminder to return the book. If it’s not, print a message saying the book is still on time.

2. School Bus Alert

Suppose you have a variable time_now set to the current hour (like 7 or 8). Create a Python program with an if-else statement to see if the time is 8 or later. If it is, print a warning that the school bus is leaving soon. If it’s earlier, print a message saying there’s still time.

3. Water Bottle Refill

You have a variable water_level showing the percentage of water left in your bottle. Write a Python program using an if-else statement to check if this level is less than 20. If it is, print a message to refill the bottle. If it’s not, print that the bottle is still full enough.

4. Room Light Control

Think of a variable is_dark set to True or False to show if a room is dark. Write a Python program with an if-else statement to check if it’s dark. If it is, print that the lights are turning on. If it’s not, print that the lights will stay off.

5. Shopping Budget Monitor

Create a Python program with a variable cart_total representing the total cost of items in a shopping cart in rupees. Using an if-else statement, determine if the total exceeds 3000. If it does, print a warning about going over budget; otherwise, print a confirmation that the purchase is within budget.

CHECK YOUR UNDERSTANDING

Concept Problems

1. Explain the basic syntax and functionality of an 'if-else' statement?

An 'if-else' statement provides a way to execute one block of code if a condition is true, and a different block of code if the condition is false.
The basic syntax involves the keyword 'if', followed by a condition.  If the condition evaluates to 'true', the code within the 'if' block is executed.
If the condition evaluates to 'false', the code within the 'else' block is executed.
This structure ensures that one, and only one, of the two code blocks will be executed.

For example, in Python:
if condition:
    # Code for true condition
else:
    # Code for false condition

2. Describe a scenario where using an 'if-else' statement is more appropriate than using a simple 'if' statement?

An 'if-else' statement is more appropriate when you have a condition and you want to perform one action if the condition is true, and a different, specific action if the condition is false.
A simple 'if' statement only executes code when the condition is true and does nothing when the condition is false.

For example:
1. If you're checking if a user is logged in, you might use 'if-else' to either:
    Redirect them to their profile page (if logged in - true).
    Redirect them to the login page (if not logged in - false).
2. If you're checking if a number is positive, you might:
    Print "Positive" (if true).
    Print "Not Positive" (if false).  This covers both zero and negative numbers.
3. The 'if-else' statement provides a clear, binary choice in your code.
3. Can the 'else' block of an 'if-else' statement be empty?  Why or why not?

In most programming languages, the 'else' block of an 'if-else' statement cannot be completely empty.
The purpose of the 'else' block is to provide an alternative action when the 'if' condition is false.
If the 'else' block is empty, it creates a logical inconsistency because the program is designed to do something in either case (true or false).
Some languages might allow an empty 'else' block syntactically, but it's generally bad practice because it makes the code less readable and can hide potential errors.
If you truly want nothing to happen when the condition is false, you should use a simple 'if' statement without an 'else' block.
In Python, an empty else block will cause a syntax error.
4. Can we use multiple conditions in an if statement?

Yes, multiple conditions can be combined using logical operators such as and, or, and not.
Example:
score = 85
if score > 80 and score <= 100:
    print("Excellent")
else:
    print("Good or Average")
5. What is the importance of indentation in Python's if-else statements?

Python uses indentation (usually 4 spaces) to define blocks of code. Incorrect indentation can lead to syntax errors or incorrect execution.
Previous
Next