# Computer Systems - dcs.bbk.ac.uk Introduction to Programming Department of Computer Science and Information Systems Lecturer: Tingting Han [email protected] Autumn 2019 and Spring 2020 Week 6: Relational Operators and Boolean Variables Birkbeck College, U. London 1 Revision: Strings String literals: "Hello", 'World!' Length: len("Hello") # value 5 Convert a number to a string: str(5)

# value "5" str(34.2) # value "34.2" String concatenation: "H"+"W" # value "HW" PFE Section 2.4.4 2 Revision: Strings Indexing How are strings indexed? From left to right, starting from 0 How are individual characters obtained? using [index], e.g. "Cakes" # value "a" How to obtain individual characters using negative indices?

"Cakes"[-3] # value "k" Valid indices for "Cakes" -5? 5? 0? 2.0? -5, -4, -3, -2, -1, 0, 1, 2, 3, 4 PFE Section 2.4.4 3 Revision: Escape Sequences \" \n include the character double quote in a string e.g. "a\"b" len("a\"b" )=? print("a\"b") ? len("a\"b" )= 3,

result is a"b new line e.g. "*\n*", len("*\n*")=? len("*\n*")=3 result is * print("*\n*") ? * \\ include the character backslash in a string e.g. "a\\b" len("a\\b" )=? print("a\\b") ? len("a\\b" )= 3, result is a\b PFE Section 2.4 4 Revision: Format Specifiers %5d, e.g. print("%5d" % 56)

# three spaces then 56 %5d place an integer right justified in a field of 5 characters %8.2f, e.g. print("%8.2f" % -586.189) # one space then -586.19 %8.2f place a floating point number with two digits after the decimal point right justified in a field of 8 characters. The decimal point and the sign, if present, each count as characters %-9s, e.g. print("%-9s" % "Hello") # Hello then four spaces %-9s place a string left justified in a field of 9 characters PFE Section 2.5.3 5 Relational Operators Python Math Notation Description

PFE Section 3.2 6 Relational Operators Python > >= Math Description Notation > Greater than Greater than or equal PFE Section 3.2 7 Relational Operators Python > >=

< <= Math Description Notation > Greater than Greater than or equal < Less than Less than or equal PFE Section 3.2 8 Relational Operators Python Math Description Notation >

> Greater than >= Greater than or equal < < Less than <= Less than or equal == = Equal != Not equal The result of the comparing two values using relational operators: True or False PFE Section 3.2 9 Examples of Relational Operators 3<=4

True True 3!=5-1 3=<4 True Error, use <=, not =< 3=6/2 3>4 Syntax error, use == to test for equality False 4<4 3==5-2 False 4<=4 True 3==6/2

True 1.0/3.0 == 0.333333333 False, the values are close, but not exactly equal 1.0/3.0 == 0.3333333333333333 is True "10" > 5 Error A string cannot be compared with a number PFE Section 3.2 10 Relational Operators and Strings name1 = "John" name2 = "John" name3 = "Smith" name1 == name2 # True name1 == name3 # False

name1 != name3 # True PFE Section 3.2 11 Ordering of Single Characters All uppercase letters come before lowercase letters Numbers come before letters The space character comes before all printable characters Empty string comes before all non-empty characters Example "" < " " <"0" < "1" < "9" "A" < < "B" < "Z" < "a" < "b" < "z Use ord() function to check the value of a character. E.g., ord("A") is 65, ord(" ") is 32.

PFE Section 3.2 12 ASCII Chart https://www.commfront.com/pages/ascii-chart 13 Extended ASCII Chart https://www.commfront.com/pages/ascii-chart 14 Lexicographic Ordering of Strings Python's relational operators compare strings in lexicographic order. Lexicographic order: similar to the way in a dictionar string1 < string2, if string1 comes before string2 in a

dict. "Hammer"<"Hello" string1 == string2, if string1 are string2 are identica How does Python compare strings? E.g. "catch" and "cart"? "coal" and "coat"? "tone" and "ton"? PFE Section 3.2 15 Summary of Lexicographic Ordering Given strings s1, s2, find the longest string s such that s1 = s + u1

If If If If s2 = s + u2 u1 == u2 == "", then s1 == s2 u1 == "" and u2 "", then s1 < s2 u1 != "" and u2 == "", then s1 > s2 u1 != "" and u2 != "", then if u1 < u2 then s1 < s2 if u1 > u2 then s1 > s2 Example 1 Example 2 Example s1 s2 "catch" "cart"

u1 "tch" s is the longest common string between s1 and s2 (see Example 5) (see Example 4) (see Example 3) (see Example 2) (see Example 1) u2 "rt" compare order "t" > "r" s1 > s2 "coal" "coats" "l" "ts"

"l" < "t" s1 < s2 "tone" "ton" "" "e" > ''" s1 > s2 "e" 16 Boolean Variables Variables of type bool have the value True or the value False, e.g. failed = False passed = True True and False are special values, not numbers or

strings. True and False are reserved words What about true and false? PFE Section 3.7 17 Boolean Operators A Boolean operator takes one or more Boolean values as input and produces a Boolean value as output. Example: and input: two Boolean values True, True output: True and yields True if both inputs are True Wave the flag when the road is clear and the cars are ready flag = True and True The Boolean variable flag has the PFE Section 3.7 value True

18 Truth Tables A True True Fals e Fals e B A and B True True False False True False False False PFE Section 3.7 19 Boolean Operators A Boolean operator takes one or more Boolean

values as input and produces a Boolean value as output. Example: or input: two Boolean values True, False output: True or yields True if at least one input is True Fail the game if bumping into a poisonous mushroom or time is up fail = True or False The Boolean variable fail PFE Section has3.7 the value True 20 Truth Tables A True True Fals e

Fals e B A and B True True False False True False False False A B True True True Fals e Fals True e Fals Fals e e PFE Section 3.7 A or B True

True True False 21 Boolean Operators A Boolean operator takes one or more Boolean values as input and produces a Boolean value as output. Example: not input: ONE Boolean value False output: True or yields True if the input is False Press the button if colour is not purple press = not isPurple The Boolean variable press has the value False PFE Section 3.7 if isPurple is True

22 Truth Tables A True True Fals e Fals e B A and B True True False False True False A B True True True Fals e Fals True False False e

A notFals A Fals True False e e False True PFE Section 3.7 A or B True True True False 23 Boolean Operator Examples

0 < 200 and 200 < 100 False 0 < 200 or 200 < 100 True 0 < 200 or 100 < 200 True x=-7 0>x or x<100 and x>50 (0>x or x<100) and x>50 is False 0>x or (x<100 and x>50) is True The and operator has a higher precedence than the or operator So 0>x or x<100 and x>50 is True PFE Section 3.2 24 Boolean Operator Examples

0 < 200 and 200 < 100 False 0 < 200 or 200 < 100 True not (0 < 200) False not (0 < 200) or (100 < 200) not ((0 < 200) or (100 < 200)) is False (not (0 < 200)) or (100 < 200) is True The not operator has a higher precedence than the and/or operator

0 < 200 or 100 < 200 True x=-7 0>x or x<100 and x>50 (0>x or x<100) and x>50 is False frozen == True 0>x or (x<100 and x>50) is True frozen The and operator has a higher There is no need to compare a precedence than the or operator So 0>x or x<100 and x>50 is True Boolean variable with True frozen == False not frozen 25 The Operators and, or Avoid confusing the operators and, or

E.g. x in the range 0 to 100 inclusive 0 <= x and x <= 100 E.g. x outside the range 0 to 100 inclusive x < 0 or x > 100 26 Chaining Relational Operators The expression 0 <= value <= 100 is equivalent in Python to value >= 0 and value <= 100 Example: The expression a < x > b is equivalent to a < x and x > b x = 9 3 <

8 < 3 < PFE Section 3.7 x > 8 True x > 3 True x > 9 False 27 Short Circuit Evaluation Logical expressions x and y and x or y are evaluated left to right. Evaluation stops when the value of the expression is known. Examples: True or Anything

# True False and Anything # False PFE Section 3.7 28 Short Circuit Evaluation Another example: fun() is a user-defined function It will print "Yes" in the shell and return True What will the following statements do in the shell? True and fun() Print "Yes", True False and fun() No print, False True or fun() No print, True False or fun() Print "Yes", True

Yet another example: quantity > 0 and price/quantity < 10 # False if quantity == 0 29 De Morgans Law Motivation example Charge a higher shipping rate if the destination is not within the continental United States Not US part of the US, but not continental: Alaska and Hawaii if not (country == "USA" and state != "AK" and state != "HI") : shippingCharge = 20.00 When not is applied on the outermost level of the condition, it becomes harder to understand what it means. PFE Section 3.7 30 De Morgans Law It tells us how to negate and and or conditions Version 1 not(A and B) is the same as (not A) or (not B)

Version 2 not(A or B) is the same as (not A) and (not B) To prove Version 2 from Version 1, write not (A or B) = not (not not A or not not B) #not not = identity = not not (not A and not B) # apply Version 1 = not A and not B PFE Section 3.7#not not = identity31 Example of De Morgans Law Charge a higher shipping rate if the destination is not within the continental United States part of the US, but not continental: Alaska and Hawaii if not (country == "USA" and state != "AK" and state != "HI") : shippingCharge = 20.00 if(country != "USA" or state == "AK" or state == "HI") : shippingCharge = 20.00 Usually it is a good idea to push negations to the

innermost level PFE Section 3.7 32 PFE Review Question R3.20 Of the following pairs of strings, which comes first in lexicographic order? >"Tom", "Jerry" <"Tom", "Tomato" >"church", "Churchill" <"car manufacturer", "carburettor" <"36", "A1" <"36", "a1" PFE R3.20 33 Examples Let x, y, z be variables with integer values. Construct a Boolean expression that is True if and only if exactly one of x, y, z is equal to zero.

Construct a Boolean expression with the following truth table, using one or more of the operators and, or, not. A True True False False B Expressio n True False False True True True False False PFE Section 3.7 34 Examples Let x, y, z be variables with integer values. Construct a Boolean expression that is True if and only if exactly one of x, y, z is equal to zero.

(x==0 and y!=0 and z!=0) or (x!=0 and y==0 and z!=0) or (x!=0 and y!=0 and z==0) PFE Section 3.7 35 Examples Construct a Boolean expression with the following truth table, using one or more of the operators and, or, not. A True True False False B Expressio n True False False True True True

False False exclusive or (A and not B) or (not A and B) (A or B) and not (A and B) (A or B) and (not A or not B) PFE Section 3.7 36 Saturday Sessions One-to-one session Help with your Python questions Every Saturday 20-min time slots

20th October - 15th December inclusive (9 weeks) 15:00, 15:20, 15:40, 16:00, 16:20, 16:40, 17:00, 17:20, 17:40 Venue: MAL151/G22 Tutor: Donal/Julio Birkbeck College, U. London Free, but you need to book first 37 How to Book By email

First come first served You may state which slot you prefer, but not always available Book at least one working day in advance Put Booking Out Of Hours Session in the title State which week you want The latest a booking can be made will be on the Thursday of that week Which email account?

[email protected] Birkbeck College, U. London 38