Control Flow
Master the art of controlling program execution flow with conditionals, loops, and exception handling in SAPL.
Conditional Statements
Conditional statements enable your program to execute different code paths based on specific conditions. SAPL provides several conditional constructs to handle various decision-making scenarios.
If Statement
The እንደሆነ (if) statement is the most basic conditional statement. It executes a block of code only when a specified condition evaluates to true.
Basic Syntax
እንደሆነ condition:
# Code to execute if condition is true
statement1
statement2Example
# Check if a number is positive
number = 10
እንደሆነ number > 0:
አሳይ("The number is positive")
አሳይ("Number value:", number)
# Check user age for voting eligibility
age = ያስገባ("Enter your age: ")
age = ቁጥር(age)
እንደሆነ age >= 18:
አሳይ("You are eligible to vote!")
አሳይ("Welcome to the voting system")If-Else Statement
The እንደሆነ-ካልሆነ(if-else) statement provides an alternative execution path when the condition is false.
Basic Syntax
እንደሆነ condition:
# Code to execute if condition is true
statement1
ካልሆነ:
# Code to execute if condition is false
statement2Examples
# Check if number is even or odd
number = ቁጥር(ያስገባ("Enter a number: "))
እንደሆነ number % 2 == 0:
አሳይ(number, "is an even number")
ካልሆነ:
አሳይ(number, "is an odd number")
# Temperature check
temperature = ነጥብ(ያስገባ("Enter temperature in Celsius: "))
እንደሆነ temperature > 30:
አሳይ("It's hot outside! Stay hydrated.")
ካልሆነ:
አሳይ("The weather is pleasant.")
# Login validation
username = ያስገባ("Username: ")
password = ያስገባ("Password: ")
እንደሆነ username == "admin" እና password == "secret123":
አሳይ("Login successful! Welcome, admin.")
ካልሆነ:
አሳይ("Invalid credentials. Please try again.")If-Elif-Else Statement
The እንደሆነ-ወይም_እንደሆነ-ካልሆነstatement allows you to check multiple conditions in sequence, executing the first matching condition.
Basic Syntax
እንደሆነ condition1:
# Code for condition1
ወይም_እንደሆነ condition2:
# Code for condition2
ወይም_እንደሆነ condition3:
# Code for condition3
ካልሆነ:
# Code when no conditions matchExamples
# Grade calculator
score = ነጥብ(ያስገባ("Enter your score (0-100): "))
እንደሆነ score >= 90:
grade = "A"
አሳይ("Excellent work!")
ወይም_እንደሆነ score >= 80:
grade = "B"
አሳይ("Good job!")
ወይም_እንደሆነ score >= 70:
grade = "C"
አሳይ("Satisfactory performance")
ወይም_እንደሆነ score >= 60:
grade = "D"
አሳይ("Needs improvement")
ካልሆነ:
grade = "F"
አሳይ("Please study harder")
አሳይ("Your grade is:", grade)
# Traffic light system
light_color = ያስገባ("Enter traffic light color: ").lower()
እንደሆነ light_color == "green":
አሳይ("GO - Proceed with caution")
ወይም_እንደሆነ light_color == "yellow":
አሳይ("CAUTION - Prepare to stop")
ወይም_እንደሆነ light_color == "red":
አሳይ("STOP - Do not proceed")
ካልሆነ:
አሳይ("Invalid color - Check the traffic light")Nested Conditional Statements
You can nest conditional statements inside other conditional statements to create more complex decision trees.
# Complex eligibility checker
age = ቁጥር(ያስገባ("Enter your age: "))
has_license = ያስገባ("Do you have a driver's license? (yes/no): ")
has_car = ያስገባ("Do you have access to a car? (yes/no): ")
እንደሆነ age >= 18:
አሳይ("You are an adult")
እንደሆነ has_license.lower() == "yes":
አሳይ("You have a valid license")
እንደሆነ has_car.lower() == "yes":
አሳይ("You can drive! Have a safe trip.")
ካልሆነ:
አሳይ("You need access to a vehicle to drive")
ካልሆነ:
አሳይ("You need a driver's license to drive legally")
ካልሆነ:
አሳይ("You must be 18 or older to drive")
# Number classification
number = ቁጥር(ያስገባ("Enter a number: "))
እንደሆነ number > 0:
አሳይ("Positive number")
እንደሆነ number % 2 == 0:
አሳይ("Even positive number")
ካልሆነ:
አሳይ("Odd positive number")
ወይም_እንደሆነ number < 0:
አሳይ("Negative number")
እንደሆነ number % 2 == 0:
አሳይ("Even negative number")
ካልሆነ:
አሳይ("Odd negative number")
ካልሆነ:
አሳይ("The number is zero")Ternary Operator
The ternary operator provides a concise way to write simple conditional expressions in a single line.
Basic Syntax
result = value_if_true እንደሆነ condition ካልሆነ value_if_falseExamples
# Simple pass/fail check
score = 75
result = "Pass" እንደሆነ score >= 60 ካልሆነ "Fail"
አሳይ("Result:", result)
# Age category
age = 25
category = "Adult" እንደሆነ age >= 18 ካልሆነ "Minor"
አሳይ("Age category:", category)
# Maximum of two numbers
a = 10
b = 20
maximum = a እንደሆነ a > b ካልሆነ b
አሳይ("Maximum:", maximum)
# Absolute value
number = -15
absolute = number እንደሆነ number >= 0 ካልሆነ -number
አሳይ("Absolute value:", absolute)Loops
Loops enable you to execute a block of code repeatedly, making your programs more efficient and reducing code duplication. SAPL provides several types of loops for different iteration scenarios.
For Loop
The ለእያንዳንዱ (for) loop iterates over sequences like lists, strings, or ranges. It's ideal when you know the number of iterations in advance.
Basic Syntax
ለእያንዳንዱ variable በ sequence:
# Code to execute for each item
statement1
statement2Examples
# Iterate over a list
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
አሳይ("Available fruits:")
ለእያንዳንዱ fruit በ fruits:
አሳይ("- " + fruit)
# Iterate over a string
word = "SAPL"
አሳይ("Letters in", word + ":")
ለእያንዳንዱ letter በ word:
አሳይ(letter)
# Iterate over a range
አሳይ("Counting from 1 to 5:")
ለእያንዳንዱ i በ ከ(1, 6):
አሳይ("Count:", i)
# Multiplication table
number = 7
አሳይ("Multiplication table for", number)
ለእያንዳንዱ i በ ከ(1, 11):
result = number * i
አሳይ(number, "x", i, "=", result)
# Calculate sum of numbers
numbers = [10, 20, 30, 40, 50]
total = 0
ለእያንዳንዱ num በ numbers:
total = total + num
አሳይ("Sum of numbers:", total)Advanced For Loop Features
# Using enumerate to get index and value
students = ["Alice", "Bob", "Charlie", "Diana"]
አሳይ("Student roster:")
ለእያንዳንዱ index, student በ enumerate(students):
አሳይ(index + 1, ".", student)
# Iterating over dictionary
grades = {"Alice": 95, "Bob": 87, "Charlie": 92}
አሳይ("Student grades:")
ለእያንዳንዱ student, grade በ grades.items():
አሳይ(student + ":", grade)
# List comprehension (advanced)
squares = [x * x ለእያንዳንዱ x በ ከ(1, 6)]
አሳይ("Squares:", squares)While Loop
The እስከ (while) loop continues executing as long as a specified condition remains true. It's useful when the number of iterations is unknown.
Basic Syntax
እስከ condition:
# Code to execute while condition is true
statement1
statement2
# Don't forget to update the condition variable!Examples
# Simple countdown
count = 5
አሳይ("Countdown:")
እስከ count > 0:
አሳይ(count)
count = count - 1
አሳይ("Blast off!")
# User input validation
እስከ እውነት:
age = ያስገባ("Enter your age (0-120): ")
age = ቁጥር(age)
እንደሆነ 0 <= age <= 120:
አሳይ("Valid age entered:", age)
አቋርጥ
ካልሆነ:
አሳይ("Invalid age. Please try again.")
# Number guessing game
import ዘፈቀዳዊ
secret_number = ዘፈቀዳዊ.ከ(1, 100)
attempts = 0
አሳይ("Guess the number between 1 and 100!")
እስከ እውነት:
guess = ቁጥር(ያስገባ("Enter your guess: "))
attempts = attempts + 1
እንደሆነ guess == secret_number:
አሳይ("Congratulations! You guessed it in", attempts, "attempts.")
አቋርጥ
ወይም_እንደሆነ guess < secret_number:
አሳይ("Too low! Try again.")
ካልሆነ:
አሳይ("Too high! Try again.")Loop Control Statements
Loop control statements allow you to change the normal flow of loop execution.
Break Statement
The አቋርጥ (break) statement immediately terminates the loop and transfers control to the statement following the loop.
# Find first even number in a list
numbers = [1, 3, 7, 8, 9, 12, 15]
አሳይ("Looking for the first even number...")
ለእያንዳንዱ num በ numbers:
እንደሆነ num % 2 == 0:
አሳይ("Found first even number:", num)
አቋርጥ
አሳይ("Checking:", num)
# Exit loop on user command
እስከ እውነት:
command = ያስገባ("Enter command (type 'quit' to exit): ")
እንደሆነ command.lower() == "quit":
አሳይ("Goodbye!")
አቋርጥ
አሳይ("You entered:", command)Continue Statement
The ቀጥል (continue) statement skips the rest of the current iteration and moves to the next iteration of the loop.
# Print only odd numbers
አሳይ("Odd numbers from 1 to 10:")
ለእያንዳንዱ i በ ከ(1, 11):
እንደሆነ i % 2 == 0:
ቀጥል # Skip even numbers
አሳይ(i)
# Process valid inputs only
inputs = ["hello", "", "world", " ", "SAPL", ""]
አሳይ("Valid inputs:")
ለእያንዳንዱ text በ inputs:
እንደሆነ text.strip() == "":
ቀጥል # Skip empty or whitespace-only strings
አሳይ("Processing:", text)
# Skip negative numbers in calculation
numbers = [5, -2, 8, -1, 3, -7, 10]
positive_sum = 0
ለእያንዳንዱ num በ numbers:
እንደሆነ num < 0:
ቀጥል # Skip negative numbers
positive_sum = positive_sum + num
አሳይ("Sum of positive numbers:", positive_sum)Nested Loops
You can place loops inside other loops to handle multi-dimensional data or create complex patterns.
# Multiplication table
አሳይ("Multiplication Table (1-5):")
ለእያንዳንዱ i በ ከ(1, 6):
ለእያንዳንዱ j በ ከ(1, 6):
product = i * j
አሳይ(product, end=" ") # Tab-separated
አሳይ() # New line after each row
# Pattern printing
አሳይ("Star pattern:")
ለእያንዳንዱ i በ ከ(1, 6):
ለእያንዳንዱ j በ ከ(1, i + 1):
አሳይ("*", end="")
አሳይ() # New line
# 2D list processing
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
አሳይ("Matrix elements:")
ለእያንዳንዱ row በ matrix:
ለእያንዳንዱ element በ row:
አሳይ(element, end=" ")
አሳይ() # New line after each rowException Handling
Exception handling allows your programs to gracefully handle errors and unexpected situations, preventing crashes and providing meaningful feedback to users.
Try-Except Blocks
The ሞክር-ያዝ(try-except) block allows you to catch and handle exceptions that might occur during program execution.
Basic Syntax
ሞክር:
# Code that might raise an exception
risky_operation()
ያዝ ExceptionType:
# Code to handle the specific exception
handle_error()
ያዝ:
# Code to handle any other exception
handle_general_error()Examples
# Basic exception handling
ሞክር:
number = ቁጥር(ያስገባ("Enter a number: "))
result = 100 / number
አሳይ("Result:", result)
ያዝ ZeroDivisionError:
አሳይ("Error: Cannot divide by zero!")
ያዝ ValueError:
አሳይ("Error: Please enter a valid number!")
ያዝ:
አሳይ("An unexpected error occurred!")
# File handling with exception handling
ሞክር:
file = ክፈት("data.txt", "r")
content = file.አንብብ()
አሳይ("File content:", content)
file.ዝጋ()
ያዝ FileNotFoundError:
አሳይ("Error: File 'data.txt' not found!")
ያዝ PermissionError:
አሳይ("Error: Permission denied to read the file!")
ያዝ:
አሳይ("Error: Could not read the file!")
# List access with exception handling
my_list = [1, 2, 3, 4, 5]
ሞክር:
index = ቁጥር(ያስገባ("Enter list index: "))
value = my_list[index]
አሳይ("Value at index", index, "is:", value)
ያዝ IndexError:
አሳይ("Error: Index out of range!")
ያዝ ValueError:
አሳይ("Error: Please enter a valid integer!")Try-Except-Finally
The በመጨረሻ (finally) block contains code that will always execute, regardless of whether an exception occurred or not.
# File handling with cleanup
file = None
ሞክር:
file = ክፈት("important_data.txt", "r")
data = file.አንብብ()
# Process the data
processed_data = data.upper()
አሳይ("Processed data:", processed_data)
ያዝ FileNotFoundError:
አሳይ("Error: File not found!")
ያዝ:
አሳይ("An error occurred while processing the file!")
በመጨረሻ:
እንደሆነ file:
file.ዝጋ()
አሳይ("File closed successfully")
# Database connection example
connection = None
ሞክር:
connection = connect_to_database()
data = connection.fetch_data()
አሳይ("Data retrieved:", data)
ያዝ ConnectionError:
አሳይ("Error: Could not connect to database!")
ያዝ:
አሳይ("Database operation failed!")
በመጨረሻ:
እንደሆነ connection:
connection.close()
አሳይ("Database connection closed")Raising Exceptions
You can manually raise exceptions using the ስህተት(raise) keyword to signal error conditions in your code.
# Custom validation function
ተግባር validate_age(age):
እንደሆነ age < 0:
ስህተት ValueError("Age cannot be negative")
ወይም_እንደሆነ age > 150:
ስህተት ValueError("Age seems unrealistic")
ካልሆነ:
አሳይ("Valid age:", age)
# Using the validation function
ሞክር:
user_age = ቁጥር(ያስገባ("Enter your age: "))
validate_age(user_age)
ያዝ ValueError as error:
አሳይ("Validation error:", error)
# Custom exception for specific business logic
ተግባር divide_numbers(a, b):
እንደሆነ b == 0:
ስህተት ZeroDivisionError("Division by zero is not allowed")
return a / b
# Account balance example
ተግባር withdraw_money(balance, amount):
እንደሆነ amount <= 0:
ስህተት ValueError("Withdrawal amount must be positive")
እንደሆነ amount > balance:
ስህተት ValueError("Insufficient funds")
return balance - amount
# Using the withdrawal function
account_balance = 1000
ሞክር:
withdrawal_amount = ነጥብ(ያስገባ("Enter withdrawal amount: "))
new_balance = withdraw_money(account_balance, withdrawal_amount)
አሳይ("Withdrawal successful. New balance:", new_balance)
ያዝ ValueError as error:
አሳይ("Transaction failed:", error)Best Practices
Conditional Statements
- ✓Use meaningful variable names and clear conditions
- ✓Avoid deeply nested if statements (max 3 levels)
- ✓Use logical operators to combine simple conditions
- ✓Consider using functions for complex conditional logic
Loops
- ✓Choose the right loop type for your use case
- ✓Always ensure while loops will eventually terminate
- ✓Use descriptive variable names in loop constructs
- ✓Minimize work inside loops for better performance
Exception Handling
- ✓Handle specific exceptions rather than using generic catch-all
- ✓Always clean up resources in finally blocks
- ✓Provide meaningful error messages to users
- ✓Log errors for debugging purposes
General Guidelines
- ✓Keep your code readable with proper indentation
- ✓Add comments to explain complex control flow logic
- ✓Test edge cases and error conditions
- ✓Use consistent coding style throughout your project
