Python if Conditional Statement

By YBI Foundation

CONTENT

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

​Introduction

If conditional statements, enable python program to execute specific code blocks based on whether defined conditions are met. The basic "if" statement evaluates a condition and executes a block of code if the condition is true.
Practical applications span from validating user input and controlling program flow to making data-driven decisions.
​Basic Syntax:
if condition:
    execute this code block if condition is True
SOLVED PROBLEMS

Coding Solved Problems

​1. Coffee Crisis Detector:

Write a Python program that defines a variable coffee_cups to represent the number of coffee cups available. Using a single if statement, check if the number of coffee cups is less than 1. If this condition is true, print a message warning that productivity levels are dropping and a coffee refill is urgently needed.

​Code </>:
​# if statement
coffee_cups = 0
if coffee_cups < 1:
    print("Alert: Productivity levels dropping—refill coffee immediately!")

Output:

Alert: Productivity levels dropping—refill coffee immediately!

​2. Code Comment Confession:

Create a Python program with a variable lines_of_comments indicating the number of comment lines in a script. Using only one if statement, determine if the number of comments is fewer than 10. If so, print a message cautioning that insufficient documentation may cause future regret.

​Code </>:
​# if statement
lines_of_comments = 5
if lines_of_comments < 10:
    print("Warning: Future you will regret this lack of documentation!")

Output:

Warning: Future you will regret this lack of documentation!

​3. Pizza Motivation Check:

Develop a Python program that includes a variable hours_worked to track the number of hours worked. With a single if statement, evaluate whether the hours worked are greater than or equal to 8. If this condition holds, print a congratulatory message announcing that a pizza break has been earned.

​Code </>:
​# if statement
hours_worked = 8
if hours_worked >= 8:
    print("Congratulations! You’ve earned a pizza break!")

Output:

Congratulations! You’ve earned a pizza break!

​4. Procrastination Detector:

Construct a Python program with a variable tasks_due representing the number of pending tasks. Using a single if statement, check if the number of tasks due exceeds 0. If true, print a robotic-sounding message urging the user to stop procrastinating and begin working.

​Code </>:
​# if statement
tasks_due = 3
if tasks_due > 0:
    print("Stop scrolling and start working!")

Output:

Stop scrolling and start working!

​5. Procrastination Detector:

Write a Python program that defines a variable temperature to store the current temperature in degrees. Using only one if statement, assess whether the temperature exceeds 25 degrees. If it does, print a instruction stating that shorts and t-shirts are now required.

​Code </>:
​# if statement
temperature = 35
if temperature > 25:
    print("Caution: Shorts and t-shirts are required!")

Output:

Caution: Shorts and t-shirts are required!

UNSOVED PROBLEMS

Coding Unsolved Problem

Minimum Balance Checker

Create a Python program with a variable account_balance representing a bank account’s current balance in rupees. Using only one if statement, determine if the balance is below 100. If so, print a notification advising the account holder to deposit funds.

Speed Limit Warning

Develop a Python program that includes a variable speed representing a vehicle’s current speed in kilometers per hour. Using a single if statement, evaluate whether the speed exceeds 120 km/h. If this condition is true, print a warning about exceeding the speed limit.

Login Attempt Monitor

Write a Python program that defines a variable login_attempts to track the number of failed login attempts. Using a single if statement, determine if the number of attempts exceeds 3. If this condition holds, print a security alert indicating a potential unauthorized access attempt.

CHECK YOUR UNDERSTANDING

Concept Problems

1. Explain the basic syntax and functionality of a simple 'if' statement?

The 'if' statement evaluates a condition. If that condition evaluates to 'true', the code block within the 'if' statement is executed. If the condition is 'False', the code block is skipped. 
Python uses indentation to define code blocks, rather than curly braces.
The basic syntax typically involves the keyword 'if', followed by a condition, and then a code block by indentation. For example,
if (condition):
    code to execute.

2. What types of data can be used in the condition part of an 'if' statement?

The condition within an 'if' statement must evaluate to a boolean value, either True or False. This can be achieved through various means:
  1. Boolean variables or literals directly (e.g., if True:).
  2. Comparison operators (e.g., if x > 5:, if y == 10:).
  3. Functions or expressions that return a boolean value.
  4. Falsy values: False, None, 0, 0.0, 0j, '', (), [], {}. Any object whose __bool__() method returns False or whose __len__() method returns zero.
  5. Truthy values: Any value that is not falsy.
  6. Python evaluates the condition to a boolean internally.
3. Provide an example of a situation where you would use a simple 'if' statement without an 'else' or 'elif' clause in Python?

The condition within an 'if' statement must evaluate to a boolean value, either True or False. This can be achieved through various means:
  1. Boolean variables or literals directly (e.g., if True:).
  2. Comparison operators (e.g., if x > 5:, if y == 10:).
  3. Functions or expressions that return a boolean value.
  4. Falsy values: False, None, 0, 0.0, 0j, '', (), [], {}. Any object whose __bool__() method returns False or whose __len__() method returns zero.
  5. Truthy values: Any value that is not falsy.
  6. Python evaluates the condition to a boolean internally.
4. What happens if the condition in an 'if' statement in Python is always 'True'?

If the condition is always 'True', the indented code block within the 'if' statement will execute every time the 'if' statement is encountered. This can be useful for creating loops (though generally you'd use a while loop), or for debugging purposes, but it can also lead to unintended behavior if not used carefully. It's important to ensure the condition accurately reflects the desired logic.
5. What happens if the condition in an 'if' statement in Python is always 'False'?

If the condition is always 'False', the indented code block within the 'if' statement will never execute. This means that the code inside the block will be completely skipped, and the program will continue with the next statement after the 'if' block. 
This can be useful for temporarily disabling code or handling edge cases, but it can also indicate a logical error in the program. Python's interpreter will not throw an error, it will simply move on.
Previous
Next