crow walking along a clay-covered driveway

True or False

Ahoy, mate.

If you’ve been following along, you already know about my secret plot to create an AI that can replace me at work. I’m inching closer to my goal, but one of the first hurdles I’ve run into is that so far, all my programs are super plain.

Here’s an example:

print("Hello, world.")

Now, this code is awesome, it’s true.

But it doesn’t do a great job of replacing me. There aren’t a lot of situations where I’m going to need the AI-version of myself to say hello to the entire world. (Maybe if one of them gets a job as a TV presenter or something.)

Luckily, Python has some more tricks up its sleeve.

Specifically, I’m talking about conditionals.

Yes, conditionals. Those famous “if” statements that allow you to run a block of code if, and only if, a certain condition is true. Here’s an example:

“Let me know whether x is greater than, less than, or equal to 10.”

In code, you might specify that like this:

# Define a variable
x = 10

# If-elif-else statement
if x > 10:
    print("x is greater than 10")
elif x < 10:
    print("x is less than 10")
else:
    print("x is equal to 10")

In this example, we’re using a conditional “if-elif-else” statement that allows us to specify code to run depending on various situations.

The code block under the first condition to evaluate to True will be run. Unless, of course, no condition evaluates to True. If that’s the case, we handle it with a catch-all called an else statement.

The else statement only runs if none of the if or elif statements evaluate to True.

Pretty handy, right? Here’s a more realistic example of when you might want to use conditionals.

Let’s say you’re a teacher and you want to give all of your students a letter grade based on a numerical score. You could program that like this:

# Function to calculate letter grade
def calculate_grade(score):
    if score >= 90:
        return 'A'
    elif score >= 80:
        return 'B'
    elif score >= 70:
        return 'C'
    elif score >= 60:
        return 'D'
    else:
        return 'F'

# Main program
def main():
    # Get input from the user
    score = float(input("Enter the student's score: "))
    
    # Calculate the grade
    grade = calculate_grade(score)
    
    # Output the result
    print("The student's grade is:", grade)

# Execute the main program
if __name__ == "__main__":
    main()

Boom! Conditionals unlock a lot of functionality for us as developers.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *