To perform decision making in Python, we will use the conditional statement if/elif/else. Before we perform a decision, we need to understand the concept of a Boolean statement.
A Boolean statement is a result of any operation that results in a True or False value.
We use the relational operators in Python, to perform these actions. To perform a decision, we need at least two values to make a comparison or a current state of a control variable. To make this possible we can use the six relational operators
>
<
>=
<=
==
!=
For Example, if we run the following relational operations using the Python interpreter, we get the following:
Python 3.7.3 (default, Dec 20 2019, 18:57:59)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 5 > 2
True
>>> 5 < 2
False
>>> 5 >= 2
True
>>> 5 <= 2
False
>>> 5 == 2
False
>>> 5 != 2
True
Python uses the white space as a delimiter for the scope for any structure, also known as indentation. Be careful how you use those delimiters because Python may generate an error if one space is missing. You can also use the Tab as a delimiter, but we recommend to use spacing with the white space.
Structure of the if:
The if-statement structure requires a Boolean expression to make a decision. If the Boolean expression is True, then it will execute a set of statements. In case the Boolean expression is False, in the if-statement, then the execution process will “jump” into the else statement. This is the structure:
if():
statement
elif():
statement
else:
statement
Tasks
Task 1: Write a script called task01.py that requests the user to enter two numbers, print the largest number that was entered by the user. In case both numbers are the same, print: “duplication of values”. E.g., your program shall run with the following prompts:
servin@linux-csit-club:~/pythonscripts$ python3 task01.py
enter a value: [5]
enter a value: [5]
Duplication of number
servin@linux-csit-club:~/pythonscripts$ python3 task01.py
enter a value: [5]
enter a value: [7]
The largest value is: 7
servin@linux-csit-club:~/pythonscripts$ python3 task01.py
enter a value: [7]
enter a value: [5]
The largest value is: 7
Task 2: Modify Task 1. Instead of asking the user to use the arguments to perform the actions. E.g., your script shall be called through the terminal as follows:
servin@linux-csit-club:~/pythonscripts$ python3 task01.py 5 5
Duplication of number
servin@linux-csit-club:~/pythonscripts$ python3 task01.py 5 7
The largest value is: 7
servin@linux-csit-club:~/pythonscripts$ python3 task01.py 7 5
The largest value is: 7
Task 3: Modify Task 2 to check if there are enough arguments to perform the action. Your program shall provide an error message in case there are not enough arguments provided.
Task 4: Python owns Built-in functions that permit to simplify work done in programming. Use the function max() that extracts the largest value between two numbers.
Task 5: (optional) Modify Task 3, to extend the program to provide additional information in the arguments other than only 2.
Solutions
ch3Task 1 | ch3Task 2 | ch3Task 3 | ch3Task 4
Logical operators are used to combining, disjoining or negating Boolean expressions. Python supports the logical and (and), logical or (or), and the not (not). To understand these operators, we must understand the truth tables to visualize the Boolean expressions.
The purpose is to make conjunctions between two Boolean statements. Both statements must be true to generate a True statement.
The logical and is often used to establish conjunctions, ranges, and inclusion of data or points. Example, we can visualize it, by selecting ALL values between 0 AND 10 as following:
The purpose is to disjoint two Boolean statements. At least one statement must be true to generate a true statement using logical or.
The logical or is often used to have at least one value to proceed. It is also to discard values or ranges of numbers. For example, if we want to discharge all numbers that are not between 0 and 10, we can use the logic or to reduce the search.
Logical not, basically "flips" the boolean value to its opposite by using the not operator.
X
True
False
not(X)
False
True
Example
x = True
y = False
# Output: x and y is False
print('x and y is',x and y)
# Output: x or y is True
print('x or y is',x or y)
# Output: not x is False
print('not x is',not x)
Tasks
Task 6: Write a script that requests the user to enter a number between 0-10. The program shall display “Good Answer” if the number is within the range, otherwise, it will display “Bad Input”
servin@linux-csit-club:~/pythonscripts$ python3 task06.py
enter a number [0,10]: [5]
Good answer
servin@linux-csit-club:~/pythonscripts$ python3 task06.py
enter a number [0,10]: [-1]
Bad input
servin@linux-csit-club:~/pythonscripts$ python3 task06.py
enter a number [0,10]: [667]
Bad input
Task 7: Write a script that requests for 2 numbers and your program shall display them in increasing order.
servin@linux-csit-club:~/pythonscripts$ python3 task07.py
enter a number: [5]
enter a number: [7]
5, 7
servin@linux-csit-club:~/pythonscripts$ python3 task07.py
enter a number: [7]
enter a number: [5]
5, 7
servin@linux-csit-club:~/pythonscripts$ python3 task07.py
enter a number: [5]
enter a number: [5]
5, 5
Task 8: Write a script that requests for 3 numbers and your program shall display them in increasing order.
Solutions
ch3Task 6 | ch3Task 7 | ch3Task 8
Python allows the ability to shortcut conditional statements based on Boolean expressions similar as other languages use the conditional operator or the so-called trinary. For example, if we are interested in shortcut a simple program as follows:
x = int(input("Enter current temperature: "))
if( x >= 60):
print("temperature is hot")
else:
print("temperature is cold")
We can simplify the 5 lines of code by using only 1 as follows:
print("temperature is hot") if( x>= 60) else
print("temperature is cold")
Handling Exceptions
There are some inputs that the user may provide you intentionally or unintentionally. Sometimes the user provides bad input by mistake, perhaps a typo or maybe a misunderstanding of the information required. Sometimes, the user may want to give you a bad input only to "see what happens", this action is often called injections or exploits for input validation. For example, consider Task 8. What would happen if the computer user's input:
is not a number (i.e., a string)
if is a floating number?
There are possible "bad input" that may crash the program. As a good programmer, we need to handle these situations by using proper clauses such as the try, except, and the else.
The try/except/else clauses
Whenever there is a potential hazard to the code, we use the try/except/else clause as shown here
try:
# potential hazard exception
# ... more statements
except:
# Exception handler
else:
# statements in case evrything went well
Some of the Built-in Exceptions can be found here: https://docs.python.org/3/library/exceptions.html. However, the programmer has the ability to create their own.
Check Point
Tasks
Task 9: Extend Task 6 that handles the situation when the user provides you a value that is not numeric value
Task 10: Write a program that reads two number from the script arguments and performs the division between both of them. E.g., if first argument is 10 and second argument is 5, your program shall print 2, since 10/5 = 2. Your program shall handle potential errors.
Task 11: Modify addition.py, this time; you need to avoid the error:
IndexError: list index out of range
Check before the execution of the program, if the script has enough arguments to process the addition of the two arguments, otherwise, have the user known, the options that your script addition.py must-have. E.g.,
Usage: [name of program] [number] [number]
Python has iterable objects that allows to scan or process items one-by-one. We will discuss more iterable objects through the rest of this course, but one of the most common iterable object is the string.
If you remember, a string is composed by characters, and python allows to iterate through the string character-by-character. For example, we know how to access each character by specifying the position as follows: