Printing Conditional Outputs
Once you have understood the basics of if-else
statements in Python, you can use them to print different outputs based on the evaluated conditions. This allows you to provide customized responses or feedback to the user or other parts of your program.
Simple If-Else Printing
The simplest way to print different outputs based on an if-else
condition is to use the print()
function within the corresponding code blocks.
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
In this example, if the age
variable is greater than or equal to 18, the program will print "You are an adult." Otherwise, it will print "You are a minor."
Printing with Variables
You can also incorporate variables into the printed outputs to make the messages more dynamic and informative.
name = "LabEx"
score = 85
if score >= 90:
print(f"{name} scored an excellent grade of {score}.")
else:
print(f"{name} scored a grade of {score}.")
By using f-strings (formatted string literals), you can seamlessly integrate variables into the printed output.
Printing with Nested Conditions
When working with nested if-else
statements, you can print different outputs based on the evaluation of multiple conditions.
temperature = 25
humidity = 80
if temperature > 30:
if humidity > 70:
print("It's hot and humid outside.")
else:
print("It's hot and dry outside.")
else:
if humidity > 70:
print("It's cool and humid outside.")
else:
print("It's cool and dry outside.")
In this example, the program will print different messages depending on the combination of temperature and humidity levels.
By understanding how to print conditional outputs, you can create more informative and interactive programs that provide tailored responses to the user or other parts of your application.