Extra Topic: If/Else

Preview

Learn how to use if/else statements in Python to enhance your Discord bot. This will not go into how to implement it into a Discord bot as you will try to implement it on your own.

Topic

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 conditions.

You can use multiple if statements in a row or you can also use them inside each other. These are called nested if statements.

if BLANK: if BLANK: print(1) else BLANK: print(2)

This topic can be hard to grasp over text, so if you need help please ask your mentor as this will be critical knowledge to create customized Discord bots.

Last updated