Conditional Statements: Learn how to use if, if-else, and nested if-else statements to control the flow of a program.

What is if,if-else and nested statement?

In computing and in programming, these are decision-making structures that allow a program to perform different actions based on specific conditions precisely.

  1. if statement: This statement or command is used to test a condition. If the condition is true, the program will execute or run the code block that follows the statement.

  2. if-else statement: This statement or syntax is an extension of the if statement. It is used to test a condition and, if the condition is true, the program will execute or operate the code block that follows the if statement. However, and in addition, if the condition is false, the program will execute the code block that follows the else statement.

  3. nested if-else statement: This is a statement where a combination of the if and if-else statements. It is noted to be used to test multiple conditions and perform different actions based on these conditions.

Below is a typical example of using if, if-else, and nested if-else statements in a Python program. This program takes the temperature in Fahrenheit and the humidity percentage as input, and determines if there is a need for fans.

def should_use_fans(temperature, humidity):
# Base decision on temperature
if temperature <= 78:
# No fans needed if the temperature is below or equal to 78
return False
elif temperature > 85:
# Fans needed if the temperature is above 85
return True
else:
# Check humidity if temperature is between 78 and 85
if humidity > 70:
# Fans needed if the humidity is above 70
return True
else:
# No fans needed if the humidity is below or equal to 70
return False

# Example usage
temp = 86 # Temperature in Fahrenheit
humidity = 75 # Humidity percentage
print(should_use_fans(temp, humidity)) # Output: True

 

In the program above,  we first check the temperature. If it is below or equal to 78, we return False, indicating that fans are not needed. If the temperature is above 85, we return True, indicating that fans are needed.

Meanwhile, If the temperature is between 78 and 85, we then check the humidity. If it is above 70, we return True, indicating that fans are needed. If the humidity is below or equal to 70, we return False, indicating that fans are not needed.

In this case, you have the liberty to or you can adjust the temperature and humidity values in the example usage to test the function with different conditions.

About Author


Discover more from SURFCLOUD TECHNOLOGY

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from SURFCLOUD TECHNOLOGY

Subscribe now to keep reading and get access to the full archive.

Continue reading