Ict 4
Ict 4
ENDIF
statements, which are fundamental to
programming logic. They allow your code to
make decisions based on conditions.
Basic Structure
The basic structure looks like this:
IF (condition) THEN
// Code to execute if the condition is TRUE
ELSE
// Code to execute if the condition is FALSE
ENDIF
How it Works
* Condition: The condition is an expression
that can be evaluated as either TRUE or
FALSE. This is often a comparison (e.g., x >
10, name == "Alice", age >= 18).
* IF: The IF statement checks the condition.
* THEN: If the condition is TRUE, the code
within the THEN block is executed.
* ELSE: If the condition is FALSE, the code
within the ELSE block is executed.
* ENDIF: Marks the end of the IF statement.
It's essential to properly close your IF blocks.
Examples
Let's illustrate with some examples, first in
pseudocode (which is language-agnostic) and
then in Python.
Example 1: Checking Age
* Pseudocode:
IF (age >= 18) THEN
OUTPUT "You are an adult."
ELSE
OUTPUT "You are a minor."
ENDIF
* Python:
age = 16 # Example age
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
* Python:
number = -5 # Example number
if number > 0:
print("The number is positive.")
elif number < 0: # Python's way of ELSE IF
print("The number is negative.")
else:
print("The number is zero.")
* Python:
name = "Bob" # Example name
if name == "Alice":
print("Hello, Alice!")
else:
print("You are not Alice.")
Key Points
* Indentation: In Python (and many other
languages), indentation is crucial. It's how the
code knows which statements belong to the IF
block, the ELSE block, etc. Consistent
indentation is vital for correct execution.
* Comparison Operators: You'll use
comparison operators within the condition:
* == (equals)
* != (not equals)
* > (greater than)
* < (less than)
* >= (greater than or equals)
* <= (less than or equals)
* Logical Operators (AND, OR, NOT): You
can combine conditions using logical
operators:
* AND: Both conditions must be true.
* OR: At least one condition must be true.
* NOT: Reverses the truth value of a
condition.
* ELSIF (or elif in Python): Use ELSIF (or
elif) when you need to check multiple
conditions in sequence.
Example with Logical Operators (Python)
age = 20
has_license = True