Decision-making is a crucial aspect of programming, allowing a program to make choices based on certain conditions or inputs. In Python, decision-making is achieved through the use of control structures such as if-else
statements and loops.
If-Else Statements
The most basic form of decision-making in Python is the if-else
statement.
The syntax for an if-else statement is as follows:
if condition:
# code to be executed if condition is true
else:
# code to be executed if condition is false
The condition in an if-else statement is a Boolean expression that evaluates to either True or False.
Here is an example of if-else
statement:
x = 5
if x > 0:
print("x is positive")
else:
print("x is negative or zero")
# Output : x is positive
If-Elif-Else Statements
- In some cases, you may want to check multiple conditions and execute different codes for each condition.
- This can be done using the
if-elif-else
statement, which allows for multiple conditions to be checked.
if condition1:
# code to be executed if condition1 is true
elif condition2:
# code to be executed if condition1 is false and condition2 is true
else:
# code to be executed if condition1 and condition2 are both false
An example of if-elif-else
statement:
x = 5
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
Nested If-Else Statements
- It is also possible to have
if-else
statements inside otherif-else
statements. These are called nestedif-else
statements. - The inner
if-else
statements will only be executed if the outerif-else
statement's condition is true.
The syntax for a nested if-else statement is as follows:
if condition1:
if condition2:
# code to be executed if condition1 and condition2 are true
else:
# code to be executed if condition1 is true and condition2 is false
else:
# code to be executed if condition1 is false
An example of nested if-else statement:
x = 5
y = 10
if x > 0:
if y > 0:
print("x and y are both positive")
else:
print("x is positive and y is non-positive")
else:
print("x is non-positive")
Conditional Expressions
Python has a shorthand notation for simple if-else
statements, called a conditional expression.
The syntax for a conditional expression is as follows:
value_if_true if condition else value_if_false
An example of if-else shorthand:
x = 5
result = "positive" if x > 0 else "non-positive"
print(result)
Conclusion
- Decision-making in Python is achieved through the use of control structures such as
if-else
statements andloops
. - The
if-else
statement is used to check a single condition and execute different codes based on whether the condition is true or false. - The
if-elif-else
statement allows for multiple conditions to be checked. - Nested
if-else
statements can be used to check multiple conditions in a more complex manner. - Conditional expressions provide a shorthand notation for simple
if-else
statements.