Unit P3:
Decisions
DECISIONS, BOOLEAN CONDITIONS, STRING
ANALYSIS, AND INPUT VALIDATION
Chapter 3
This Photo by Unknown Author is licensed under CC BY-SA
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 1
Unit Goals
▪ Input of Numeric and String data
▪ Formatting the output
▪ Implement decisions using the if statement
▪ Compare Numbers (integer and floating-point) and Strings
▪ Write statements using the Boolean data type
▪ Validate user input
In this unit, you will learn how to program simple and
complex decisions. You will apply what you learn to the
task of checking user input and computation results.
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 2
Contents
▪ Data Input and Formatted Output
▪ The if Statement
▪ Relational Operators
▪ Nested Branches
▪ Multiple Alternatives
▪ Boolean Variables and Operators
▪ Analyzing Strings
▪ Application: Input Validation
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 3
Input 2.5
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 4
Input and Output
Your Python program
Running in the Python Interpreter
Output
Input
Python Console
(Terminal, Command Prompt)
User of the program
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 5
Input and Output
▪ You can read a String from the console with the input() function:
o name = input("Please, enter your name")
▪ If numeric (rather than string) input is needed, you must convert
the String value to a number
ageString = input("Please, enter your age: ") # String
input
age = int(ageString) # Converted to int
▪ …or in a single step:
age = int(input("Please, enter your age: "))
price = float(input("Please, enter the price: "))
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 6
Formatted output 2.5
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 7
Formatted output
▪ Inserting values inside strings, mainly for the purposes of an
ordered and easy-to-read display
▪ Several methods are available in Python
o String concatenation
o Formatting operator %
o f-Strings Additional information
can be found in:
https://pyformat.info/
o .format() method
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 8
Example
pi = 3.14
r = 2
area = (r**2) * pi
print('The area of a circle of radius '+str(r)+' is '+str(area))
print('The area of a circle of radius %f is %f' % (r, area))
print('The area of a circle of radius {rd} is {ar}'.format(rd=r,ar=area))
print(f'The area of a circle of radius {r} is {area}')
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 9
Format operator %
▪ Outputting floating point values can look strange:
o Price per liter: 1.21997
▪ To control the output appearance of numeric variables, use the
format operator %
"string with format specifiers" % ( value, value, … )
▪ Ex: "Price per liter: %.2f" % (price)
o Each format specifiers is replaced by a computed value
o You may control the details of the formatting
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 10
Formatted output
▪ Examples
print("Price per liter %.2f" %(price))
Price per liter: 1.22
print("Price per liter %10.2f" %(price))
Price per liter: 1.22
10 spaces 2 spaces
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 11
Syntax: format operator
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 12
Format flag examples
▪ Left Justify a String:
print("%-10s" %("Total:"))
▪ Right justify a number with two decimal places
print("%10.2f" %(price))
▪ And you can print multiple values:
print("%-10s%10.2f" %("Total: ", price))
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 13
Volume2.py
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 14
Format Specifier Examples
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 15
f-Strings (Formatted String Literals)
▪ A formatted string literal or f-string is a string literal that is prefixed
with 'f' or 'F'.
▪ These strings may contain replacement fields, which are
expressions delimited by curly braces {}.
▪ While other string literals always have a constant value, formatted
strings are really expressions evaluated at run time.
F-Strings are not in the book. See:
https://docs.python.org/3/reference/lexical_analysis.html#f-strings
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 16
f-String Examples
print(f"the result is {result}")
the result is 5 Adding the =
operator, the name
of the variable will
print(f"the result is {a+b}")
be included in the
the result is 15 string.
This feature is not
print(f'my name is {username=}') supported in
pythontutor.com
my name is username=Pedro
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 17
Formatting in f-Strings
▪ Format specifiers may be added inside the {}, separated with a :
symbol
▪ f"The distance is {dist:8.2} meters"
▪ The syntax and meaning of the format specifiers is the same as the
% operator
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 18
Formatting methods comparison
FORMATTING OPERATOR: % F-STRINGS
▪ "your age is %d" % ( age ) ▪ f"your age is {age}"
▪ Format string ▪ String prefixed by an “f” letter
▪ % placeholders ▪ {…} placeholders
o Specify the data type and formatting options o Specify which variable will be used to replace
the placeholders
o May also be an expression
o Formatting options are also accepted
▪ Actual values are inserted
o Specify which variable will be used to replace ▪ {age} is an actual variable in the
the placeholders surrounding python code
o Taken from the values in %(val, val, … )
second argument
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 19
Format specifiers in the f-String
{VarName : [[fill]align][sign][#][0][width] [.precision][type]}
▪ Symbol ‘:’
o Separates the variable name from the required format
▪ Alignment options for example: < (left alignment)
▪ Sing (+ or -)
▪ #VAL (optional): indicates the spaced occupied by the printed
variable
▪ ‘.’ indicates the number of digits in the fractional part, EX: .2
▪ Conversion type EX: b
https://docs.python.org/3/library/string.html#formatspec
http://cis.bentley.edu/sandbox/wp-content/uploads/Documentation-on-f-strings.pdf
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 20
Alignment options
Option Meaning
Forces the field to be left-aligned within the available space (this is the default for most
'<'
objects).
Forces the field to be right-aligned within the available space (this is the default for
'>'
numbers).
Forces the padding to be placed after the sign (if any) but before the digits. This is used for
'=' printing fields in the form ‘+000000120’. This alignment option is only valid for numeric
types.
'^' Forces the field to be centered within the available space.
https://docs.python.org/3/library/string.html#formatspec
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 21
Sign options
Option Meaning
'+' indicates that a sign should be used for both positive as well as negative numbers.
'-' indicates that a sign should be used only for negative numbers (this is the default behavior).
indicates that a leading space should be used on positive numbers, and a minus sign on
space
negative numbers.
https://docs.python.org/3/library/string.html#formatspec
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 22
Conversion types
Value Type Meaning
str 's' String format. This is the default type for strings and may be omitted.
'b' Binary format. Outputs the number in base 2.
'c' Character. Converts the integer to the corresponding unicode character before printing.
'd' Decimal Integer. Outputs the number in base 10.
int
'o' Octal format. Outputs the number in base 8.
'x' / 'X' Hex format. Outputs the number in base 16, using lower/upper-case letters
'n' Number. Same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters.
'e' / 'E' Exponent notation. Prints in scientific notation using the letter ‘e’ or ‘E’ to indicate the exponent. Default precision is 6.
'f' Fixed-point notation. Displays as a fixed-point number. Default precision is 6.
'F' Fixed-point notation. Same as 'f', but converts nan to NAN and inf to INF.
General format. For a given precision p, rounds the number to p significant digits and then formats the result in either fixed-point
'g'
format or in scientific notation, depending on its magnitude. Default precision is 6.
float
'G' General format. Same as 'g' except switches to 'E' if the number gets too large.
'n' Number. Same as 'g', except that it uses the current locale setting to insert the appropriate number separator characters.
'%' Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign.
Similar to 'g', except that fixed-point notation, when used, has at least one digit past the decimal point. The default precision is as
None high as needed to represent the particular value.
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 23
The if statement 3.1
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 24
The if Statement
▪ A computer program often needs to make decisions based on
input, or circumstances
▪ For example, buildings often ‘skip’ the 13th floor, and elevators
should too
o The 14th floor is really the 13th floor
o So every floor above 12 is really ‘floor – 1’
• if floor > 12, actual floor = floor - 1
▪ The two keywords composing the if statement are:
o if
o else The if statement allows a program to
carry out different actions depending on
the nature of the data to be processed.
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 25
Flowchart of the if Statement
▪ Exactly one of the two branches is executed once
o True (if) branch or False (else) branch
Indentation:
The content of the if and
else branches must be
indented by some spaces
(usually 2 or 4)
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 26
Flowchart with only a True Branch
▪ An if statement may not need a ‘False’ (else) branch
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 27
Syntax 3.1: The if Statement
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 28
Elevatorsim.py
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 29
Example 1
▪ Open the file: elevatorsim.py
▪ Run the program
o Try a value that is less than 13
• What is the result?
o Run the program again with a value that is greater than 13
• What is the result?
▪ What happens if you enter 13?
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 30
Example 1 - corrected
▪ Revised Problem Statement (1):
o Check the input entered by the user:
o If the input is 13, set the value to 14 and print a message
o Modify the elevatorsim program to test the input
▪ The relational operator for equal is “==”
Important Warning:
Do not confuse = with ==
= declares a variable
= assigns a value
== makes an equality comparison
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 31
Example 1 – proposed addendum
▪ Modified Problem Statement
o In some countries the number 14 is considered unlucky.
o What is the revised algorithm?
o Modify the elevatorsim program to “skip” both the 13th and 14th floor
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 32
Compound Statements
▪ Some constructs in Python are compound statements.
o The if statement is an example of a compound statement
▪ Compound statements span multiple lines and consist of a header
and a statement block
▪ Compound statements require a colon “:” at the end of the
header.
if <condition>: header
<instr 1>
compound statement <instr 2> statement block
…
<instr n>
else:
…
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 33
Compound Statements
▪ The statement block is a group of one or more statements, all
indented to the same column
▪ The statement block
o starts on the line after the header
o ends at the first statement that is less indented
▪ Most IDEs properly indent the statement block.
if <condition>: header
<instr 1>
compound statement <instr 2> statement block
…
<instr n>
else:
…
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 34
Compound Statements
▪ Statement blocks can be nested inside the blocks of other
compound statements (of the same or other block type)
▪ In the case of the if construct the statement block specifies:
o The instructions that are executed if the condition is true
o Or skipped if the condition is false
▪ Statement blocks are visual cues that allow you to follow the logic
and flow of a program
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 35
A Common Error
▪ Avoid duplication in branches
▪ If the same code is duplicated in each branch then move it out of
the if statement.
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 36
The Conditional Operator
▪ A “shortcut” you may find in existing code
o It is not used in this course
o The shortcut notation can be used anywhere a value is expected
True branch Condition False branch
Complexity is BAD….
This “shortcut” is difficult to read and a poor programming practice
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 37
Relational operators 3.2
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 38
Relational Operators
▪ Every if statement has a condition
o Usually compares two values with an operator
if floor > 13 :
..
if floor >= 13 :
..
if floor < 13 :
..
if floor <= 13 :
..
if floor == 13 :
..
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 39
Assignment vs. Equality Testing
▪ Assignment: makes something true.
floor = 13
▪ Equality testing: checks if something is true.
Never confuse
if floor == 13 :
=
with
==
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 40
Comparing Strings
▪ Checking if two strings are equal
if name1 == name2 :
print("The strings are identical")
▪ Checking if two strings are not equal
if name1 != name2 :
print("The strings are not identical")
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 41
Checking for String Equality
▪ If any character is different, the two strings will not be equal:
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 42
Relational Operator Examples (1)
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 43
Relational Operator Examples (2)
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 44
Example
▪ Open the file:
o compare.py
▪ Run the program
o What are the results?
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 45
Common Error (Floating Point)
▪ Floating-point numbers have only a limited precision, and
calculations can introduce roundoff errors.
▪ You must take these inevitable roundoffs into account when
comparing floating point numbers.
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 46
Common Error (Floating Point, 2)
▪ For example, the following code multiplies the square root of 2 by
itself.
▪ Ideally, we expect to get the answer 2:
r = math.sqrt(2.0)
if r * r == 2.0 :
print("sqrt(2.0) squared is 2.0")
else :
print("sqrt(2.0) squared is not 2.0 but", r * r)
Output:
sqrt(2.0) squared is not 2.0 but 2.0000000000000004
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 47
The Use of EPSILON
▪ Use a very small value to compare the difference to determine if
floating-point values are ‘close enough’
o The magnitude of their difference should be less than some threshold
o Mathematically, we would write that x and y are close enough if:
EPSILON = 1E-14
r = math.sqrt(2.0)
if abs(r * r - 2.0) < EPSILON :
print("sqrt(2.0) squared is approximately 2.0")
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 48
Lexicographical Order
▪ To compare Strings in ‘dictionary’ like order:
ostring1 < string2
▪ Notes
o All UPPERCASE letters come before lowercase
• ‘A’ comes before ‘a’, but also ‘Z’ comes before ‘a’
o‘space’ comes before all other printable characters
oDigits (0-9) come before all letters
oThe order is ruled by the Basic Latin (ASCII) Subset of Unicode
• Accented characters are not always logical
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 49
Operator Precedence
▪ The comparison operators have lower precedence than arithmetic
operators
o Calculations are done before the comparison
o Normally your calculations are on the ‘right side’ of the comparison or
assignment operator
Calculations
actualFloor = floor + 1
if floor > height + 1 :
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 50
Example
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 51
The Sale Example
▪ The university bookstore has a Kilobyte Day sale every October 24
(10.24), giving an 8 percent discount on all computer accessory
purchases if the price is less than $128, and a 16 percent discount
if the price is at least $128.
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 52
Implementing an if Statement (1)
▪ 1) Decide on a branching condition
o Original price < 128 ?
▪ 2) Write pseudocode for the true branch
o Discounted price = 0.92 * original price
▪ 3) Write pseudocode for the false branch
o Discounted price = 0.84 * original price
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 53
Implementing an if Statement (2)
▪ 4) Double-check relational operators
o Test values below, at, and above the comparison (127, 128, 129)
▪ 5) Remove duplication
o Discounted price = _____ * original price
▪ 6) Test both branches
o Discounted price = 0.92 * 100 = 92
o Discounted price = 0.84 * 200 = 168
▪ 7) Write the code in Python
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 54
The Sale Example (solution)
▪ Open the file:
o sale.py
▪ Run the program several times using different values
o Use values less than 128
o Use values greater that 128
o Enter 128
o Enter invalid inputs
▪ What results do you get?
if originalPrice < 128 :
discountRate = 0.92
else :
discountRate = 0.84
discountedPrice = discountRate * originalPrice
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 55
Nested
Branches 3.3
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 56
Flowchart of a Nested if
Ask for order ▪ Nested if-else
inside true branch
True
of an if statement.
False
Wine? Check ID o Three paths
Serve non- False >= True
alcoholic 21?
drink
Read law Serve wine
Done
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 57
Nested Branches
▪ You can nest an if inside either branch of an if statement.
▪ Simple example: Ordering drinks (pseudo code)
Ask the customer for his/her drink order
if customer orders wine
Ask customer for ID
if customer’s age is 21 or over
Serve wine
nested IF
else
Politely explain the law to the customer
else
Serve customer a non-alcoholic drink
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 58
Tips on Indenting Blocks
▪ Let pyCharm do the indenting for you… (menu: Code – Auto-Indent lines)
▪ This is referred to as “block structured” code. Indenting consistently is
syntactically required in Python, but also makes code much easier to
follow.
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 59
Tax Example: nested ifs
▪ Four outcomes (branches)
• Single
• <= 32000
• > 32000
• Married
• <= 64000
• > 64000
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 60
Flowchart for the Tax Example
▪ Four branches
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 61
Taxes.py (1)
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 62
Taxes.py (2)
▪ The ‘True’ branch (Single)
o Two branches within this branch
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 63
Taxes.py (3)
▪ The ‘False’ branch (Married)
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 64
Running the Tax Example
▪ Open the file:
o taxes.py
▪ Run the program several time using different values for income
and marital status
o Use income values less than $32,000
o Use income values greater than $64,000
o Enter “&” as the marital status
▪ What results do you get?
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 65
Hand-tracing
▪ Hand-tracing helps you understand whether a program works
correctly
▪ Create a table of key variables
o Use pencil and paper to track their values
▪ Works with pseudocode or code
o Track location with a marker
▪ Use example input values that:
o You know what the correct outcome should be
o Will test each branch of your code
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 66
Hand-tracing the Tax Example
▪ Setup
o Table of variables
o Initial values
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 67
Hand-tracing the Tax Example (2)
▪ Input variables
o From user
o Update table
• Because marital status is not “s” we skip to the else on line 25
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 68
Hand-tracing the Tax Example (3)
▪ Because income is not <= 64000, we move to the else clause on
line 28
o Update variables on lines 29 and 30
o Use constants
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 69
Multiple
Alternatives 3.4
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 70
Multiple Alternatives
▪ What if you have more than two branches?
▪ Count the branches for the following earthquake effect example:
o 8 (or greater)
o 7 to 7.99
o 6 to 6.99
o 4.5 to 5.99
o Less than 4.5
When using multiple if statements,
test the general conditions after the
more specific conditions.
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 71
Flowchart of Multiway Branching
True
>= 8.0? Most Structures Fall
False
True
>= 7.0? Many Buildings Destroyed
False
True Many buildings considerably damaged,
>= 6.0?
some collapse
False
True
>= 4.5? Damage to poorly constructed buildings
False
No destruction of buildings
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 72
What is Wrong With This Code?
if richter >= 8.0 :
print("Most structures fall")
if richter >= 7.0 :
print("Many buildings destroyed")
if richter >= 6.0 :
print("Many buildings damaged, some collapse")
if richter >= 4.5 :
print("Damage to poorly constructed buildings")
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 73
elif Statement
▪ Short for: Else, if…
▪ As soon as one of the test conditions succeeds, the statement
block is executed
o No other tests are attempted
▪ If none of the test conditions succeed the final else clause is
executed
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 74
if, elif Multiway Branching
if richter >= 8.0 : # Handle the ‘special case’ first
print("Most structures fall")
elif richter >= 7.0 :
print("Many buildings destroyed")
elif richter >= 6.0 :
print("Many buildings damaged, some collapse")
elif richter >= 4.5 :
print("Damage to poorly constructed buildings")
else : # so that the ‘general case’ can be handled last
print("No destruction of buildings")
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 75
earthquake Example
▪ Open the file:
o earthquake.py
▪ Run the program with several different inputs
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 76
Boolean Variables and
Operators 3.7
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 77
The Boolean logic of electronic computers
▪ In 1847 George Boole introduced a new type of formal logic, based
exclusively on statements for which it was possible to verify their
truth (true or false) in an algebraic way
▪ Computers adopt Boolean logic
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 78
Boolean Variables
▪ Boolean Variables
o Boolean variables can be either True or False
• failed = True
o bool is a Python data type
o A Boolean variable is often called a flag 🏁 because it can be either up
(true) or down (false)
o The condition of the if statement is, in fact, a Boolean value
▪ There are three Boolean Operators: and, or, not
o They are used to combine multiple Boolean conditions
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 79
Combined Conditions: and
▪ Combining two conditions is often used in range checking
o Is a value between two other values?
▪ Both sides of the and must be true for the result to be true
if temp > 0 and temp < 100 :
print("Liquid")
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 80
Remembering a condition
▪ Boolean variables may be used to “remember” a condition, and
test it later.
isLiquid = temp > 0 and temp < 100
if temp > 0 and temp < 100 : # Boolean value True/False
print("Liquid")
if isLiquid :
print("Liquid")
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 81
Chained Comparison Operators
▪ Natural language: “If temperature is within the range from 0 to
100”
▪ Maths: 0 ⩽ temp ⩽ 100
▪ Python: 0 <= temp and temp <= 100
▪ You may also write: 0 <= temp <= 100
o Python allows chained comparison operators
o Most other programming languages do not allow this
o Tip: avoid this shortcut, use an explicit and
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 82
and Flowchart
▪ This is often called ‘range checking’
o Used to validate that the input is between
two values
if temp > 0 and temp < 100 :
print("Liquid")
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 83
Combined Conditions: or
▪ We use or if only one of two conditions need to be true
o Use a compound conditional with an or:
if temp <= 0 or temp >= 100 :
print("Not liquid")
▪ If either condition is true
o The result is true
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 84
or flowchart
▪ Another form of ‘range checking’
o Checks if value is outside a range
if temp <= 0 or temp >= 100 :
print("Not Liquid")
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 85
The not operator: not
▪ If you need to invert a boolean variable or comparison, precede it
with not
if not attending or grade < 18 :
print("Drop?")
if attending and not(grade < 18) :
print("Stay")
▪ For clarity, try to replace not with simpler logic
if attending and grade >= 18 :
print("Stay")
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 86
Note
if not ( a == b ):
# Is equivalent to
if a != b :
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 87
Comparison Example
▪ Open the file:
o Compare2.py
▪ Run the program with several inputs
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 88
Boolean Operator Examples
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 89
Common Errors with Boolean Conditions
▪ Confusing and with or Conditions
o It is a surprisingly common error to confuse and and or conditions.
o A value lies between 0 and 100 if it is at least 0 and at most 100.
o It lies outside that range if it is less than 0 or greater than 100.
▪ There is no golden rule; you just have to think carefully.
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 90
Short-circuit Evaluation: and
▪ Combined conditions are evaluated from left to right
o If the left half of an and condition is false, why look further?
if temp > 0 and temp < 100 :
print("Liquid")
Done!
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 91
Short-circuit Evaluation: or
▪ If the left half of the or is true, why look further?
if temp <= 0 or temp >= 100 :
print("Not Liquid")
Done!
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 92
Some Boolean Properties
▪ Commutative:
o A and B = B and A
o A or B = B or A
▪ Associative:
o A and B and C = (A and B) and C = A and (B and C)
o A or B or C = (A or B) or C = A or (B or C)
▪ Distributive:
o A and (B or C) = A and B or A and C
o A or (B and C) = (A or B) and (A or C)
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 93 93
De Morgan’s law
▪ De Morgan’s law tells you how to negate and and or conditions:
o not(A and B) is the same as not(A) or not(B)
o not(A or B) is the same as not(A) and not(B)
▪ Example: Shipping is higher to AK and HI
if (country != "USA" if not(country=="USA"
and state != "AK" or state=="AK"
and state != "HI") : or state=="HI") :
shippingCharge = 20.00 shippingCharge = 20.00
▪ To simplify conditions with negations of and or or expressions, it’s
a good idea to apply De Morgan’s law to move the negations to the
innermost level.
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 94
String analysis 3.8
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 95
Analyzing Strings – The in Operator
▪ Sometimes it’s necessary to analyze or ask certain questions about
a particular string
▪ Example: it is necessary to determine if a string contains a given
substring. That is, if one string contains an exact match of another
string
o Given this code segment:
name = "John Wayne"
o the expression
"Way" in name
o yields True because the substring "Way" occurs within the string stored in
variable name
▪ The not in operator is the inverse of the in operator
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 96
Substring: Suffixes
▪ Suppose you are given the name of a file and need to ensure that it
has the correct extension
if filename.endswith(".html") :
print("This is an HTML file.")
▪ The endswith() string method is applied to the string stored in
filename and returns True if the string ends with the substring
".html" and False otherwise.
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 97
Operations for Testing Substrings
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 98
Methods: Testing String Characteristics (1)
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 99
Methods for Testing String Characteristics (2)
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 100
Comparing and Analyzing Strings
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 101
Substring Example
▪ Open the file:
o Substrings.py
▪ Run the program and test several strings and substrings
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 102
Input Validation 3.9
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 103
Input Validation
▪ Accepting user input is dangerous
o Consider the Elevator program:
o Assume that the elevator panel has buttons labeled 1 through 20 (but not
13).
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 104
Input Validation
▪ The following are illegal inputs:
o The number 13
if floor == 13 :
print("Error: There is no thirteenth floor.")
o Zero or a negative number
o A number larger than 20
if floor <= 0 or floor > 20 :
print("Error: The floor must be between 1 and 20.")
o An input that is not a sequence of digits, such as five:
• Python’s exception mechanism is needed to help verify integer and floating point values (Chapter
7).
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 105
Elevatorsim2.py
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 106
Elevator Simulation
▪ Open the file:
o elevatorsim2.py
▪ Test the program with a range of inputs including:
o 12
o 14
o 13
o -1
o0
o 23
o 19
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 107
General rule
▪ Never trust user input
▪ When you read information from the user, always check that it
contains acceptable values, before continuing with the program
▪ If values are not acceptable, print a message, and:
o Ask again for a correct value (see Loops, Chapter 4)
o Exit from the program:
from sys import exit
exit("Value not acceptable")
It is impossible to make anything
foolproof because fools are so
ingenious…
(Unattributed variant to Murphy’s Law)
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 108
Summary
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 109
Summary: if Statement
▪ The if statement allows a program to carry out different actions
depending on the nature of the data to be processed.
▪ Relational operators ( < <= > >= == != ) are used to compare
numbers and Strings.
▪ Strings are compared in lexicographic order.
▪ Multiple if statements can be combined to evaluate complex
decisions.
▪ When using multiple if statements, test general conditions after
more specific conditions.
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 110
Summary: Boolean
▪ The type boolean has two values, True and False.
o Python has two Boolean operators that combine conditions: and , or.
o To invert a condition, use the not operator.
o The and & or operators are computed lazily:
• As soon as the truth value is determined, no further conditions are evaluated.
o De Morgan’s law tells you how to negate and & or conditions.
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 111
Summary: python overview
▪ Use the input() function to read keyboard input in a console
window.
▪ If the input is not a string, use int() or float() to convert it to a
number
▪ Use the format specifiers to specify how values should be
formatted.
▪ Use f-strings for easier formatting
Politecnico di Torino, 2022/23 INFORMATICA / COMPUTER SCIENCES 112