Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Shaun Barbour
PLUS
Shaun Barbour
Courses Plus Student 1,907 Points

why use an else statement?

why use an else statement if they are not required? doesn't the code just skip over the if and elif statements if they are not true, and move on to the next line anyway? if so, why use an else statement? what is the value in it?

3 Answers

Nader Alharbi
Nader Alharbi
2,253 Points

Allow me to join the discussion. Lets say that you are preparing your lunchbox and you want to pack a one of two sandwiches and water but you love one sandwich over the other one.

If first_sandwich available > pack first sandwich
else if second_sandwich available > pack second sandwich
else > pack any food

pack water

You see, you are packing the water regardless of which sandwich you choose. And you are getting your most favorite sandwich. Hope i didn't confuse you with my silly example :)

Shaun Barbour
Shaun Barbour
Courses Plus Student 1,907 Points

i think you answered it for me. i responded to the previous two answers with the question you just answered. the question was... if the code is written outside of the else statement, it will always run regardless of the if and elif statements. so you have to put the default/go-to option inside an else statement or it will always run. is that correct?

my original reasoning was... if the if statement is false, the program just moves along. so it would still hit the next command, so why put it in an else statement if it was going to hit it anyways. but i think you cleared that up for me.

thanks for your thoughtful response. very helpful. really appreciate it.

Nader Alharbi
Nader Alharbi
2,253 Points

Glad it helped, you can close your question by selecting best answer to any of the answer you received. Good Luck :)

Steven Parker
Steven Parker
229,732 Points

Many times, you will still want something to happen even when the "if" and "elif" conditions are all false. That's when a final "else" comes in handy. The associated code runs only when the other blocks don't, so it's great for things like setting default values. For example:

if seat_type == "vip":
    price = 90
elif seat_type == "premium":
    price = 60
else:
    price = 40  # all other types are $40
Shaun Barbour
Shaun Barbour
Courses Plus Student 1,907 Points

thanks for the thoughtful reply. i really appreciate it. let me know if the following is wrong logic... if the seat type is not vip or premium, it will set the price to 40 as contained in the else statement. i get that much. but why is the else needed at all in this case? doesn't the program skip over the if and elif statements if they're not true and move on to the next line of code? so couldn't you just put price = 40 after the if and elif statements as a standalone, and not in an else statement?

or is the following logic accurate?... if the else price of 40 is not contained in an else statement, and if the seat type is vip, it will assign the price as 90 for vip, then skip the elif price, and move on to price = 40 and reassign it as 40 overriding the vip price of 90. is that correct? is that why it must be contained in an else statement?

or... am i way off? lol.

Steven Parker
Steven Parker
229,732 Points

It sounds like you have it correctly. Any assignment made after the conditionals (and outside of an "else") will override any previous assignments. That's why the "else" is useful. And of course, this is a simplified example and in actual practice there may be much more than just an assignment involved with each condition.

Kevin Gates
Kevin Gates
15,052 Points

To add to Steven's reply, think of real-life examples.

Goal: you want to talk to your friend.

So you decide to run a function contactFriend(friendPhoneNumber);

As this runs, you know there are 2 options: (1) the friend answers or (2) he does not answer. You then could have:

pseudo code below in JS

contactFriend(friendPhoneNumber) {

var isFriendAvailable = callFriend(friendPhoneNumber); // returns true or false. True is "answers", false is "he does not answer"

// In IF statements, if the variable is a boolean, then it will be true or false. Hence, I'm not doing something like "If( var == true)"
  if(isFriendAvailable) {
    // Your friend answers, so you talk with him.
    talkWithFriend();
  } else {
  // here you do not NEED an "IF ELSE". Why? Well, there is no such thing as a partial answer. He answers or not. Therefore, if he does not answer, I want to do something else.
    leaveVoiceMail();
  }
}
Shaun Barbour
Shaun Barbour
Courses Plus Student 1,907 Points

after a bit more research, i think i'm starting to grasp it a little more. however, in your example... if the friend is not available (if the if statement is false), won't the program simply move on the next line of code anyway? if so, why put the friend not available option in an else statement? wouldn't it suffice on its own outside the else statement?

or... will it always run the friend not available scenario even if the friend is available? so... friend is available, you talk with friend, then it moves to the next line of code which executes the leave voicemail. so it's always leaving voicemail regardless if the friend is available or not. is that accurate?

thanks for your thoughtful response! really appreciate it.

Kevin Gates
Kevin Gates
15,052 Points

Hi Shaun Barbour ,

That's a great follow-up question. So, the elements within an if / if else / else are all conditionally run.

However, your question is insightful because it does depend on when and where the if / if else / else statement is used.

For instance, on the condition that your if statement is utilized in a function, you could do something like this:

contactFriend(friendPhoneNumber) {

var isFriendAvailable = callFriend(friendPhoneNumber); // returns true or false. True is "answers", false is "he does not answer"

// In IF statements, if the variable is a boolean, then it will be true or false. Hence, I'm not doing something like "If( var == true)"
  if(isFriendAvailable) {
    // Your friend answers, so you talk with him.
    talkWithFriend();
    return true;
  } 
  // here you do not NEED an "IF ELSE". Why? Well, there is no such thing as a partial answer. He answers or not. Therefore, if he does not answer, I want to do something else.
  leaveVoiceMail();
  return false;
}

The above would work because of the use of a return statement: What is a return?

Therefore after the talkWithFriend(); code is run, it would then return true; and therefore not get to the code to leaveVoiceMail();.


However, the else statement is very use if you're wanting to use code after the conditional statement.

contactFriend(friendPhoneNumber) {

var isFriendAvailable = callFriend(friendPhoneNumber); // returns true or false. True is "answers", false is "he does not answer"

// In IF statements, if the variable is a boolean, then it will be true or false. Hence, I'm not doing something like "If( var == true)"
  if(isFriendAvailable) {
    // Your friend answers, so you talk with him.
    talkWithFriend();
  } else {
  // here you do not NEED an "IF ELSE". Why? Well, there is no such thing as a partial answer. He answers or not. Therefore, if he does not answer, I want to do something else.
    leaveVoiceMail();
  }

  callWifeAndUpdateHer();
}

Now, in the code above, I want to call my wife and update her, whether the friend answers or not. (Let's pretend I'm having a party and I'm trying to get RSVPs. So she needs to know if I got in contact or not.).

In this instance, I don't want to return true; after I talk to my friend because there is more code that I want to run, namely calling my wife.

Finally, Else statements can be helpful to the human eye / understanding. It allows us to see code as we would speak it (or approximately how we would speak it).

"I am going to call my friend, else I'm going to leave a voicemail."

I hope I clarified the above. :)