Home

If and Else Statements

In this lesson, we will go over the functions of if and else statements. These statements help the computer make decisions within the program.

Using an if statement will create a condition where if the condition is met, the following indented code will run. When comparing two variables, such as variables, a double equals sign is used ==. This is important as using only one equal sign assigns the second value to the first variable, rather than comparing the two.

You can have as many if statements as you want, but nothing will happen if none of the conditions are met. That is where an else statement can be used. An else statement must come after at least one if statement and runs if none of the conditions directly above are met.

There are also a combination of the two - elif (else if) statements. This acts as a regular if statement, however, if any if or elif conditions are met, this code doesn't run even if its condition is met.

More Details

For each if or elif statement, there can be more than one condition set. This can be done using or or and inbetween conditions.

The or creates a situation where if either of the conditions are met, the code beneath runs. On the other hand, and requires all the conditions mentioned to be met to run.

Another way to compare two variables other than if one is equal to another, is to check if one does not equal to something. This is done using the exclamation mark and an equal sign !=.

A less (<) or greater (>) than sign is also often used when comparing numbers. Remember the alligator thing you were taught? The alligator always eats the bigger number.

Try It Out!

Go to Replit
  • Ask for the users age and if they are over 10 say that they can watch the movie, otherwise tell them they are not allowed to.
  • Input a number, print whether the number is "even" or "odd", but if the number is less than zero, only print out "negative".

Related Problems