This example shows you how an if-else
statement works.
if
is executed and then control passes to the next line of code that isn't part of the if-else
.elif
, then that condition is evaluated and the code under it executed if the condition is true. Again, control passes out of the if-else
block once that code is executed.if
and all elif
conditions are false, then the code under else
is executed.elif
blocks as you need, but only one if
and else
are allowed. The if
part of the whole thing is required, but elif
and else
are optional.Use the Set button to set an initial value for n
, and notice how line 2 of the code changes to reflect the value you chose. If the box under the Next button is checked when n
is set on line 2, then all occurrences of n
in the code will also be replaced with the value of n
in order to make the comparisons more explicit.
Then use the Next button to step through the code one line at a time. The current line of code is highlighted so you can see where you are in the process, and the box to the right of the code shows you the current value of n
(it will briefly turn to red when the value changes). n
is set to None
when you start out, because its value doesn't get set until line 2.
The output from the print
statements will appear below the code.
|
n =
Replace the variable |
Hit the Set button at the top of the page to start over.