Introduction to Computer Science Through Programming
Smith Computer Science
An If block is a piece of code that will be executed only when a condition (a boolean expression) is evaluated as True.
This is what it looks like:
if <condition> : <Block To Execute>
1 2 3 4 5 6 7 8 9 | # before the if x = 2 # if statement if x > 0: print ('positive') # if body # after the if print ('done') |
# before the if x = 2 # if statement if x == 2: print ('it is a two') # if body # after the if print ('done')
# before the if x = 2 # if statement if x != 0: print ('x is not zero') # after the if print ('done')
# before the if x = 6 # complex condition if x%2 == 0: print ('x is divisible by 2') # after the if print ('done')
In the example above, we have three options that can be executed.
The nature of the problem makes it so that one of them always is (a number has to be <0, 0, or >= than 0).
However, there are problems where a sequence of if statements might not be ideal, because there is always
a default option: none of them get executed!
For example:
# before the if x = 2 y = 2 # if statement if x < y: print ('x is smallest') # another (independent) if statement if x > y: print ('y is smallest') # after the if print ('done')
if <condition> : <Block To Execute> else: <Alternative Block To Execute>
# before the if x = 2 y = 2 # if-else statement if x < y: print ('x is smallest') else: print ('y is smaller or equal than x') # after the if print ('done')
What happens when we want alternative paths, each with its own condition?
It turns out that you can combine IF and IF-ELSE statements to do anything, but to make things easier,
Python provides the if-elif-else block:
if <condition> : <Block To Execute> elif <condition>: <Another Block To Execute> else: <Default Block To Execute>
# before the if x = 2 y = 2 # if-elif-else statement if x < y: print ('x is smallest') elif x > y: print ('y is smallest') else: print ('x and y are equal') # after the if print ('done')
A variable's scope is that of the innermost function, class or module in which they're assigned.
The IF/ELIF/ELSE block does not establish its own scope (This is different than in Java or C!).
Example:
x = -2 if x<0: y = x+1 print('y is the next number:',y) print(x) print(y)
Sometimes, we want sub-conditions to be true before we perform an action.
Think of the following situation:
A professor issues two assignments X and Y.
And the rules for grading are:
# before the if x = 6 # a "nested" conditional if x%2 == 0: print ('x is divisible by 2') if x%3 == 0: print ('x is divisible by 6') # after the if print ('done')
I forgot to show you some "shorthand" for some arithmetic operations: