If-else statements in python
Introduction to if
Statements in Python
Conditional statements are fundamental in programming, allowing code execution to depend on whether specific conditions are met. In Python, the primary keywords for this are if, elif, and else.
These statements evaluate conditions that resolve to either True or False, directing the program's flow down different paths based on the outcome. We will introduce these concepts one by one, building from the simplest decision-making structure to more complex scenarios
General syntax of the if
Statements
The general syntax consists of the if keyword, followed by a condition that evaluates to True or False, and a colon (:). This is followed by an indented block of code that executes only if the condition is True. Optionally, elif
and else clauses can be used to handle additional conditions or provide a fallback action, offering a clear and efficient way to control program flow based on specific criteria.
Using If Statements with Logical and Arithmetic Operators
The if statements are often used in conjunction with logical and arithmetic operators to evaluate complex conditions. Logical operators like and
, or
, and not
combine or modify conditions, while arithmetic operators such as +
, -
, *
, /
, and %
perform calculations within the condition. This allows for precise control over the program flow by enabling the execution of specific code blocks based on the results of these combined evaluations.
Example 1: Using Arithmetic and Logical and Operator
The if statement checks two conditions: age >= 18 (arithmetic comparison) and income > 30000 (arithmetic comparison), combined with the and logical operator. Both must be True for the premium account message to print. Here, since age is 25 and income is 50000, the condition is True, so the output is "You are eligible for a premium account"
Example 2: Using Arithmetic and Logical or Operator
The if statement uses the or
logical operator to check if temperature < 20 (arithmetic comparison) or is_raining
is True
. If either condition is True, the jacket message prints. Here, temperature is 15, making the condition True, so the output is "Bring a jacket."
Example 3: Nested If with Arithmetic and Logical Operators
The outer if checks score >= 80 (arithmetic comparison). If True, a nested if uses and to evaluate attendance >= 85 and score + attendance > 160 (arithmetic addition). Here, score is 85 and attendance is 90, so score + attendance is 175. Both conditions are True, so the output is "You qualify for the honor roll."