User:Milanandreew/Python 3 Programming/Conditional Statements
Decisions
[edit | edit source]A Decision is when a program has more than one choice of actions depending on a variable's value. Think of a traffic light. When it is green, we continue our drive. When we see the light turn yellow, we reduce our speed, and when it is red, we stop. These are logical decisions that depend on the value of the traffic light. Luckily, Python has a decision statement to help us when our application needs to make such decision for the user.
If Statements
[edit | edit source]Here is a warm-up exercise - a short program to compute the absolute value of a number:
n = input('Integer? ') # Pick an integer.
n = int(n) # Defines n as the integer the user chose. (Alternatively, you can define n yourself)
if n < 0:
print('The absolute value of',n,'is',-n)
else:
print('The absolute value of',n,'is',n)
What does the computer do when it sees this piece of code? First it prompts the user for a number with the statement n = input('Integer? ')
. Next it reads the line if n < 0:
. If n
is less than zero Python runs the line print('The absolute value of',n,'is',-n)
. Otherwise Python runs the line print('The absolute value of',n,'is',n)
.
More formally, Python looks at whether the expression n < 0
is true or false. An if
statement is followed by an indented block of statements that are run when the expression is true. After the if
statement is an optional else
statement and another indented block of statements. This 2nd block of statements is run if the expression is false.
Expressions can be tested several different ways. Here is a table of all of them:
operator | function |
---|---|
<
|
less than |
<=
|
less than or equal to |
>
|
greater than |
>=
|
greater than or equal to |
==
|
equal |
!=
|
not equal |
Another feature of the if
command is the elif
statement. It stands for "else if," which means that if the original if
statement is false and the elif
statement is true, execute the block of code following the elif
statement. Here's an example:
a = 0
while a < 10:
a = a + 1
if a > 5:
print(a,'>',5)
elif a <= 7:
print(a,'<=',7)
else:
print('Neither test was true')
Notice how the elif a <= 7
is only tested when the if
statement fails to be true. elif
allows multiple tests to be done in a single if statement.