Transcripted Summary

In this chapter, we'll focus on conditionals.

# Decision Structures: Conditionals

We'll start our investigation into conditionals by taking a look at this decision tree.



This program asks a user how much their luggage weighs.

  • Then it says if the luggage weight is less than 20, print “no fee”.

  • And if the luggage weight is greater than or equal to 20, print “please pay fee”.


In order to make a program that can make decisions we need to learn about 2 things: comparison operators and conditional statements.

# Comparison Operators

Comparison operators are ways for us to make comparisons between one or more items in any of our programs.

If you recall some of your early math classes, then you'll have familiarity with some of these operators.



If you don't remember them, you can use this slide as a reference to help you construct your programs with the operators that you'd like to use.

We'll go ahead and try these out in the IDE so we can see how Python handles these operators, and what kind of feedback we get.


We're going to try testing the less than (<) comparison operator and see if it evaluates to the Boolean True or the Boolean False.

Boolean's True and False are keywords in Python. If you want to use those statements then you need to use a capital T, for True or a capital F, for False.



You'll notice that the output is also capital F, False.

We can continue testing each of the other comparison operators and watching to see that they evaluate in the way that we expect.

Go ahead and type in each of the other comparison evaluators, and make sure that they evaluate properly to True or False, with the outcome that you expect.



# Control Structures: if, elif, else

If, else/if and else — if, elif and else — are control structures in Python.

The if statement, used by itself, shows code that should run only if certain conditions are present.



The elif statement shows code that should run when conditions before are not met, and many conditions could possibly be met.

The elif code is run in the order that it appears.



The else statement is used close out the if, elif, else code block and can comprise anything that you can think of that the user might not do.



We are going to go ahead and try out the if, elif, else code block to see how each of the elements works.

I'll start with my name variable and my input prompt, and we'll ask the user, “What's your name?”. And then I'll leave my space at the end so that way that it prints nicely.

If a name is double equals, remember, to “Jessica”, then you'll notice how it automatically indents 1, 2, 3, 4 spaces.

We will print me a special message of, "Hello, nice to see you.".

I'm going to use my String formatting so I can easily put the variable into the sentence,

And no matter whose name is entered I'm going to print, "Have a nice day!".


name = input("What's your name? ")

if name == "Jessica":
    print("Hello, nice to see you {}".format(name))

print("Have a nice day!")

So that's my program.

I’ll go ahead and navigate up to Run, select the file I'm working in which is comp_op.py.

What's your name? First, we'll test a non-matching name — “Karen”

And the "Have a nice day!" message is printed. My exit code is zero. So that's great.

Go ahead and Run it again. This time I'll run with a match — “Jessica”.



Then we have our "Have a nice day!" message, but we also have, "Hello, nice to see you Jessica”.

So good, this is working exactly as I hoped.


Now I'll add some else/if statements to my code.

I'll unindent so that my elif statements will align with the if.

So, I've added 2 new elif statements. And each of the elif statements looks for a match and then prints some different code based on the match.


name = input("What's your name? ")

if name == "Jessica":
    print("Hello, nice to see you {}".format(name))

elif name == "Danielle":
    print("Hello, you are a great person!")

elif name == "Kingston":
    print("Hi, {}, let's have lunch soon!".format(name))

print("Have a nice day!")

So, we'll go ahead and test out this code. I'm going to clear terminal, going to Run this.

What's your name? Good. So, I typed “Danielle” that works, we got the "Hello, you are a great person!" and "Have a nice day!"

Now when I run the code, even if I type “danielle”, but I do so with all lowercase, I'm going to have the elif statement skipped because it is not an exact String match.



We only get the "Have a nice day!" message because “danielle” is not an exact match to “Danielle”.


We'll talk later about how to do exact matching, but right now as you're testing your code, keep in mind that it does need to be an exact match for you to get the results.

We'll try this again. Try running a name that will not match — “Greta”

Okay, so nothing happens (other than getting the default "Have a nice day!" message). So this is good.

This is pretty much how I expect it to behave.


Now I'd like to add an else statement.

Instead of having it print, "Have a nice day!", every time, I'm going to actually move this message into an else statement.

Something about else statements — else statements don't have any condition attached to them.


name = input("What's your name? ")

if name == "Jessica":
    print("Hello, nice to see you {}".format(name))

elif name == "Danielle":
    print("Hello, you are a great person!")

elif name == "Kingston":
    print("Hi, {}, let's have lunch soon!".format(name))

else:
    print("Have a nice day!")

If you for example went, else name == “Rob”:



If you just added that, you'll actually get an error because your else statement should not have anything after it.

So, you really need to decide that that is going to be the end of your block and the catchall.

Go ahead and clear this, then you see what that looks like using “Kristof” as the name.

Okay, so since we didn't have any matches to our names, you can see that we have the else statement which printed out "Have a nice day!".


Something I'd like to show you, is what happens when you have an elif statement that agrees with a condition, but there's another condition that also agrees at the same time.


name = input("What's your name? ")

if name == "Jessica":
    print("Hello, nice to see you {}".format(name))

elif name == "Danielle":
    print("Hello, you are a great person!")

elif name != "Mariah":
    print("You're not Mariah!")

elif name == "Kingston":
    print("Hi, {}, let's have lunch soon!".format(name))

else:
    print("Have a nice day!")

So, it's going to happen when we Run this.

Basically, what this statement says is that any name that is not “Mariah” should print out, "You're not Mariah!".

Just by looking at those 2 lines of code and that statement, it would stand to reason that if I typed “Jessica”, that the "You're not Mariah!" statement should print.


What actually happens is that once the condition is met, none of the other conditions matter.



It's important to keep in mind that you want to design your program with order in mind.


# Conditional in Calculator

To see how to apply the if statement to a project in a way that's a little more practical, I'd like to actually create a small 4 function calculator, using the addition function that we created as the basis for this calculator.

I'm going to go ahead and make myself a new file, and I'll call this file calc.py,

For this calculator, I'm actually going to use the float function instead of the int function.

So float will allow us instead of converting our String input into an integer, float allows us to convert the String input into a decimal.

So, I'll go ahead, use that, and then our same input, which is that prompt.

Okay, I'd like to make a subtraction function, a multiplication function, and a division function. And for the purposes of this exercise, I'm just going to go ahead and make each of those functions.

If you are feeling confused or stuck, feel free to pause the video at any point so you can make sure that your work is matching the functions that I'm making (and you can also refer to the Git repo listed in the resources).

I will note that the functions that I'm making are actually all structured in basically the same way.

TIP FOR BEGINNERS

It's pretty tempting to actually use “copy and paste”, and I'm not going to say that people don't do it. They definitely do. What I will say is that the more you practice typing, the better you get at syntax and learning the rules. It's important to take as many opportunities as you can to practice your typing, your syntax, and review those rules in your head. So, exercises like this are actually a pretty nice way to go about doing that.

You'll notice if you only leave 1 line between each function, you are going to have an error because it expects to have 2 blank lines. Again, it's really good in practice.



Since I'm recording the video with the font a little bit larger so that way that you can all see it, I am probably going to have some more of these PEP 8 errors that you notice as I maintain single lines between each function, so that way that more of them fit on the screen.

I'm going to go ahead; I have these 4 functions and now I'm going to make a place to call the functions.

And you'll notice they're each coming up, which is pretty awesome because I can do a cleat or a tab complete.


def add():
    a = float(input("Enter a number. "))
    b = float(input("Enter another number. "))
    print(a + b)

def subtraction():
    a = float(input("Enter a number. "))
    b = float(input("Enter another number. "))
    print(a - b)

def multiply():
    a = float(input("Enter a number. "))
    b = float(input("Enter another number. "))
    print(a * b)

def divide():
    a = float(input("Enter a number. "))
    b = float(input("Enter another number. "))
    print(a / b)

add()
subtraction()
multiply()
divide()

And I'll go ahead Run all 4 of my operations, but it ran them in order.

Another way to give users choice, is to employ our conditional statements to allow the user to choose which operation they'd like to run.

This is actually a pretty easy thing for us to do. To get started, I'd like to make a variable called operation and I'm going to set that equal to a prompt from the user.

Now there are a couple of ways that you could structure this prompt. Since we're using really exact matches, I'm actually going to use symbols as the way to structure the problem.

So, I'm going to ask the user to choose one of these symbols — "Please type +, -, *, or / " — and also, I actually think I would like to ask the user to type that.


Here's the part where we can use our if statement.

So, if operation matches our String “+” then we will call the addition function. Since I'm calling it the addition function in this if statement, I don't want to call it at the end anymore.



Now have the opportunity (using the elif) to add my subtraction statement. I'll go ahead, call my subtraction function and remove it.


And remember we can use these statements, in order, to make sure that once the condition is met, none of the other statements will run.

So, if I hit enter it automatically indents, but if I don't hit enter then I can always indent the 4 spaces myself by using core spaces.

Okay, looks good so far.


def add():
    a = float(input("Enter a number. "))
    b = float(input("Enter another number. "))
    print(a + b)

def subtraction():
    a = float(input("Enter a number. "))
    b = float(input("Enter another number. "))
    print(a - b)

def multiply():
    a = float(input("Enter a number. "))
    b = float(input("Enter another number. "))
    print(a * b)

def divide():
    a = float(input("Enter a number. "))
    b = float(input("Enter another number. "))
    print(a / b)

operation = input("Please type +, -, *,  or / ")

if operation == '+':
    add()

elif operation == '-':
    subtraction()

elif operation == '*':
    multiply()

elif operation == '/':
    divide()

Something about Python, is that Python reads files from top to bottom — if you were to change the order of this file, the whole program would fail.

Right now, what I'd like to do is test out our operation statements.

I'd like to do that by clearing it out my terminal, clicking Run, and I am going to try multiplication.

I'll enter 3, I'll enter another 3 and I'll expect the output to be 9, if I have created my if and elif statements correctly. Because I have floats, everything is converted into a decimal number.

Let's try this again; try a different operation just to make sure that my code is indeed selecting. I always encourage my students to try each operation.

Good. Now I'm going to clear the console.


I'd like to add a statement that will catch user input, that does not match any of these statements.

Right now, the computer doesn't do anything if those statements aren't matched. So, I'm going to use the else statement, and I'm going to print, "That operation is not available. ".


else:
    print("That operation is not available.  ")

And then I'll go ahead and Run this code and purposefully type something else.



And I've executed my else statement.

So hopefully this helps you to see how using, if, elif and else can help you to make decisions in a practical program.



Resources



© 2024 Applitools. All rights reserved. Terms and Conditions Privacy Policy GDPR