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.
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.
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.
!=
.
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".