🧙‍♂️ Python Wizard!

Selection

🔍 Quick Lesson

Selection in Python allows your programs to make decisions and execute certain code only when specific conditions are met. This is achieved using conditional statements like if, elif, and else.


What is Selection?

Selection, also known as conditional execution, enables a program to choose different paths based on certain conditions. This is fundamental in programming, allowing your software to respond intelligently to inputs and situations.


The if Statement

The simplest form of selection is the if statement. It executes a block of code only if a specified condition is True.


                age = 18
                if age >= 18:
                    print("You are an adult.")
            

Here, the message will be printed only if age is 18 or more.


The else Clause

An else clause can be added to handle what happens when the condition is not met.


                age = 16
                if age >= 18:
                    print("You are an adult.")
                else:
                    print("You are a minor.")
            

The elif Clause

The elif (short for "else if") clause allows checking multiple conditions sequentially.


                grade = 85
                if grade >= 90:
                    print("Grade: A")
                elif grade >= 80:
                    print("Grade: B")
                elif grade >= 70:
                    print("Grade: C")
                else:
                    print("Grade: F")
            

This evaluates from top to bottom and stops at the first true condition.


Comparison Operators

Comparison operators are used to form conditions. Common operators include:


Logical Operators

Combine multiple conditions using logical operators:


                age = 25
                if age > 18 and age < 65:
                    print("You are of working age.")
            

Nested Conditions

You can nest if statements inside each other for more complex logic.


                score = 95
                if score >= 60:
                    if score >= 90:
                        print("Excellent!")
                    else:
                        print("Passed.")
                else:
                    print("Failed.")
            

Best Practices


🧠 Mini Quiz: Test Your Knowledge on Selection

1. What keyword is used to check an alternative condition after an if block?



2. What will the following code output?
if 3 > 2: print("Yes")



3. Which of these is a valid condition for an if statement?