Conditionals allow programs to make decisions based on certain conditions. This enables the program to take different actions based on different inputs.
The if statement is used to test a condition. If the condition is true, then the code inside the if block will be executed.
# If statement example
declare number as int;
let number = 5;
if (number > 0) {
print "Number is positive";
}
The if-else statement is used to test a condition. If the condition is true, then the code inside the if block will be executed. If the condition is false, then the code inside the else block will be executed.
# If-else statement example
declare number as int;
let number = -3;
if (number > 0) {
print "Number is positive";
} else {
print "Number is negative";
}
The if-elif-else statement is used to test multiple conditions. If the first condition is true, then the code inside the if block will be executed. If the first condition is false, then the next condition will be tested. If that condition is true, then the code inside the elif block will be executed. If all conditions are false, then the code inside the else block will be executed.
# If-elif-else statement example
declare number as int;
let number = 0;
if (number > 0) {
print "Number is positive";
} elif (number == 0) {
print "Number is zero";
} else {
print "Number is negative";
}
Logical operators are used to combine conditions. There are three logical operators: and, or, and not.
# Logical operators example
declare number as int;
let number = 5;
if (number > 0 and number < 10) {
print "Number is between 0 and 10";
} elif (number > 10 or number < 0) {
print "Number is outside the range of 0 to 10";
} else {
print "Number is 0 or 10";
}
Nested if statements are if statements inside if statements. They are used to test more complex conditions.
# Nested if statements example
declare number as int;
let number = 15;
if (number > 0) {
if (number < 10) {
print "Number is between 0 and 10";
} else {
print "Number is greater than 10";
}
} else {
print "Number is negative";
}
[](data:image/svg+xml,%3csvg%20xmlns=%27http://www.w3.org/2000/svg%27%20version=%271.1%27%20width=%2730%27%20height=%2730%27/%3e)
In conclusion, conditionals in programming are essential for creating decision-making capabilities in our code. Through the use of logical operators and conditional statements, we can create programs that respond to specific conditions and produce different outputs depending on the inputs provided. By understanding how conditionals work, we can write more robust and versatile programs that can handle a variety of scenarios and edge cases.