If/Else Statements

What is an if/else statement? An if/else statement is a way of checking requirements and then executing code if it fulfills the specific requirement.

Think of it like in real life. If I am in either grade 9, 10, 11, or 12 then I am in high school. If I am in either grade 6, 7, or 8 then I am in middle school.

We can put that into code, like the following:

grade = 10

if grade == 9 or grade == 10 or grade == 11 or grade == 12:
  print("High School")
elif grade == 6 or grade == 7 or grade == 8:
  print("Middle School")
else:
  print("Neither")

Remember to use 2 equal signs for comparisons and 1 equal sign to assign values.

And instead of using or we can use things like and and not. Think of it like normal English. If I am in grade 9 or I am in grade 10 or I am in grade 11 or I am in grade 12 then I am in High School so it will print that. However, if I am grade 6 or grade 7 or grade 8 then I am in middle school. If I am not in any of those grades, then I am in neither high school or middle school.

The keyword if is used to start a series of if/else statements and must be the first thing you use to check conditions.

The keyword elif is used to indicate if that the previous conditions are not true then it will check this condition after. However, if the previous condition was true and it executed the code, it will skip over this.

The keyword else is used if the previous conditions are not true and the code was not executed but you do not need to check if it satisfies a condition.

I would like you to follow the sample code above and create if else statements but declare a number instead of a grade. Make it so that if the number is 1, 3, 5, 7, 9 it prints "odd", if it is 2, 4, 6, 8, 10 it prints even, and if it is not any of those numbers it prints "out of bounds."

Last updated