In Part One, we mentioned that Python executes code line by line. However, the sequence of execution of the code can be altered by imposing some conditions in the code. One such condition is in the form of the if and else statements.
The if and else statements work in conjunction with the comparison operators [less than (<), greater than (>), equals to (==), not equals to (!=)] and logical operators (and, or, not). When the statement evaluates to a Boolean (True or False), the code is executed or not executed.
Let us look at some examples
x = 5
if x > 0:
print(‘x is positive’)
else:
print(‘x is negative’)
In the code above a particular variable, x, is provided. The first condition is if the variable is greater than 0 (Boolean evaluates to True), then Python should display ‘x is positive’. The second condition is else the variable is not greater than 0 (Boolean evaluates to False), then Python should display ‘x is negative’.
Notice the colon (:) after the lines for the if and the else statements. This is vital without which we would have an error message.
Notice also, the indentation below the if and else statements. This is how to tell Python that those lines are part of the if block and part of the else block respectively.
If we run the code now we get an output from the if part of the code and the else part is not executed. We get ‘x is positive’.
Next, when we change the value of x to a negative number, say -5, the if part of the code is not executed but the else part would be executed. We get ‘x is negative’.
We could also request user input for the variable or even use a list. Let us modify the code to accept user input as follows
x = int(input(‘Please enter a number: ‘)
if x > 0:
print(‘x is positive’)
else:
print(‘x is negative’)
Now, the user is prompted to provide a number which would be evaluated and the correct output would be displayed.
Let us introduce the elif statement (else if). This is used when evaluating more than 2 conditions. We can have as many elif statements as required. Let us modify our code to include a condition if our variable is 0.
x = int(input(‘Please enter a number: ‘)
if x > 0:
print(‘x is positive’)
elif x == 0:
print(‘x is zero’)
else:
print(‘x is negative’)
Now if our input is 0, the elif section of the code is executed and the if and else sections are not executed. We get ‘x is zero’.
We can use logical expressions to combine conditions as well. We can modify our code to combine positive and 0 in one condition for example.
x = int(input(‘Please enter a number: ‘)
if x > 0 or x == 0:
print(‘x is positive’)
else:
print(‘x is negative’)
The if statement would be executed if x is greater than 0 or if x is equal to 0.
We can try other combinations of comparison operators with logical operators with if, elif and else statements.
We would explore this flow of control in more detail in subsequent lessons and exercises.
No comments:
Post a Comment