Page 1
Dennis Komm
Programming and Problem-SolvingLogical Values and Control Structures
Spring 2020 – March 5, 2020
StringsRepetition
Strings
Strings are “lists of characters” (there are differences)
Characters correspond (mostly) to keys on keyboard
Strings are written in quotation marks
Access to single characters using brackets
String word = "HELLO WORLD"
word[0] is first character
word[1] is second character
. . .
word[len(word)-1] is last character
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 1 / 45
Characters – The Unicode Table
0–18 19–37 38–56 57–75 76–94 95–113 114–127
Dec. Char. Dec. Char. Dec. Char. Dec. Char. Dec. Char. Dec. Char. Dec. Char.
0 NUL 19 DC3 38 & 57 9 76 L 95 _ 114 r1 SOH 20 DC4 39 ’ 58 : 77 M 96 ‘ 115 s2 STX 21 NAK 40 ( 59 ; 78 N 97 a 116 t3 ETX 22 SYN 41 ) 60 < 79 O 98 b 117 u4 EOT 23 ETB 42 * 61 = 80 P 99 c 118 v5 ENQ 24 CAN 43 + 62 > 81 Q 100 d 119 w6 ACK 25 EM 44 , 63 ? 82 R 101 e 120 x7 BEL 26 SUB 45 - 64 @ 83 S 102 f 121 y8 BS 27 ESC 46 . 65 A 84 T 103 g 122 z9 HT 28 FS 47 / 66 B 85 U 104 h 123 {10 LF 29 GS 48 0 67 C 86 V 105 i 124 |11 VT 30 RS 49 1 68 D 87 W 106 j 125 }12 FF 31 US 50 2 69 E 88 X 107 k 126 ~13 CR 32 SP 51 3 70 F 89 Y 108 l 127 DEL14 SO 33 ! 52 4 71 G 90 Z 109 m . . .15 SI 34 "’ 53 5 72 H 91 [ 110 n16 DLE 35 # 54 6 73 I 92 \ 111 o17 DC1 36 $ 55 7 74 J 93 ] 112 p18 DC2 37 % 56 8 75 K 94 ˆ 113 q
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 2 / 45
Page 2
Characters – The Unicode Table
Use functions ord() and chr()
ord(x) returns position of character x in Unicode table
chr(y) returns character at position y in Unicode table
x = input("Enter a character: ")print("The character", x, "is at position", ord(x))
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 3 / 45
Operators
AdditionZahlen: Arithmetische OperationListen und Strings: Zusammenfügen (bei Strings existiert kein append)
daten = [1, 4, 6]daten2 = daten + [5]satz = "Guten Tag"satz2 = satz + ", Urs"satz3 = satz2 + "."
MultiplikationZahlen: Arithmetische OperationListen und Strings: Zusammenfügen
daten = [2, 3] * 5satz = "HA" * 3
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 4 / 45
Caesar Encryption
Symmetric Encryption
Sender Recipient
plaintext
Encryption
ciphertextCommunication
medium(messenger, internet, . . . )
ciphertext
Decryption
plaintext
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 5 / 45
Page 3
Caesar Encryption
Situation
Parties A and B want to communicate over an insecure channel, this timeusing Caesar encryption
Shared key k as number between 1 and 25
A encrypts message by adding k to each character
A sends encrypted message to B
B decrypts message by subtracting k from each character
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 6 / 45
Caesar Encryption
Shift characters by fixed value k by adding k
Example
A B C D E F G H I J K L MW X Y Z A B C D E F G H IN O P Q R S T U V W X Y ZJ K L M N O P Q R S T U V
Plaintext: HELLO WORLD
Ciphertext: DAHHK SKNHZ
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 7 / 45
Caesar Encryption
1. Entered letter is Unicode character between A and ZA B . . . W X Y Z65 66 . . . 87 88 89 90
2. Subtract 65 so that the result is between 0 and 25A B . . . W X Y Z0 1 . . . 22 23 24 25
3. Now add key (for instance, 3) and compute modulo 26A B . . . W X Y Z3 4 . . . 25 0 1 2
4. Finally add 65 to the resultA B . . . W X Y Z68 69 . . . 90 65 66 67
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 8 / 45
Euclidean Division (Modulo Operation)
Using “%,” we obtain the residue of the integer division
Analogously, “//” the part before the decimal point
10 % 3 = 1, because 9 = 3 · 310 % 4 = 2, because 8 = 4 · 211 // 5 = 2, because 10 = 5 · 223 // 4 = 5, because 20 = 4 · 512 % 3 = 0, because 12 = 4 · 3
If x % y == 0, x is divided by y
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 9 / 45
Page 4
Exercise – Caesar Encryption
Write a program that
runs through a given string
decrypts each letter with a key k
tries out each key k
uses the following formula
e = (v− 65− k) % 26 + 65
Decrypt the ciphertext DLUUQLTHUKSHBAOLBYLRHYBMANPIALZZJOVNNP
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 10 / 45
Exercise – Caesar Encryption
for k in range(0, 26):for item in ciphertext:
print(chr((ord(item) - 65 - k) % 26 + 65), end="")print()
for k in range(0, 26):for i in range(0, len(ciphertext)):
print(chr((ord(ciphertext[i]) - 65 - k) % 26 + 65), end="")print()
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 11 / 45
Changing the Step Size
Loops over Lists – Larger Steps
Traverse a list with steps of length 2
data = [5, 1, 4, 3]for i in range(0, len(data), 2):
print(data[i])
Output
All elements at even positions from 0 up to at most len(data) are outputï 5,4
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 12 / 45
Page 5
The Syntax of range
for i in range(start, end, step)
Iteration over all positions from start up to end-1 with step length of step
Shorthand notation
for i in range(start,end) ⇐⇒ for i in range(start,end,1)
Another shorthand notation
for i in range(end) ⇐⇒ for i in range(0, end)
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 13 / 45
Improvement of Caesar Encryption
Use two keys alternatingly for even and odd positions
k = int(input("First key: "))l = int(input("Second key: "))x = input("Text (only uppercase, even length): ")for i in range(0, len(x), 2):
print(chr((ord(text[i])-65 + k) % 26 + 65), end="")print(chr((ord(text[i+1])-65 + l) % 26 + 65), end="")
print()
Still Caesar encryption remains insecure ï Project 1
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 14 / 45
Logical ValuesBoolean Values and Relational Operators
Boolean Values and Variables
Boolean expressions can take on one of two values F or T
F corresponds to “false”
T corresponds to “true”
George Boole [Wikimedia]
Boolean variables in Python
represent “logical values”
Domain {False, True}
Example
b = True # Variable with value TrueProgramming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 15 / 45
Page 6
Relational Operators
a < b (smaller than)a >= b (greater than)
a == b (equals)a != b (unequal to)
number type × number type→ {False, True}
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 16 / 45
Logical ValuesBoolean Functions and Logical Operators
Boolean Functions in Mathematics
Boolean function
f : {F, T}2 → {F, T}
F corresponds to “false”
T corresponds to “true”
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 17 / 45
x ∧ y
“logical and”
f : {F, T}2 → {F, T}
F corresponds to “false”
T corresponds to “true”
x y x ∧ y
F F F
F T F
T F F
T T T
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 18 / 45
Page 7
Logical Operator and
a and b (logical and)
{False, True} × {False, True}→ {False, True}
n = -1p = 3b = (n < 0) and (0 < p) # b = True
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 19 / 45
x ∨ y
“logical or”f : {F, T}2 → {F, T}
F corresponds to “false”
T corresponds to “true”
x y x ∨ y
F F F
F T T
T F T
T T T
The logical or is always inclusive: x or y or both
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 20 / 45
Logical Operator or
a or b (logical or)
{False, True} × {False, True}→ {False, True}
n = 1p = 0b = (n < 0) or (0 < p) # b = False
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 21 / 45
¬x
“logical not”f : {F, T} → {F, T}
F corresponds to “false”
T corresponds to “true”
x ¬x
F T
T F
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 22 / 45
Page 8
Logical Operator not
not b (logical not)
{False, True}→ {False, True}
n = 1b = not (n < 0) # b = True
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 23 / 45
Logical ValuesPrecedences
Precedences
not b and am
(not b) and a
a and b or c and dm
(a and b) or (c and d)
a or b and c or dm
a or (b and c) or d
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 24 / 45
Precedences
7 + x < y and y != 3 * z or not b7 + x < y and y != 3 * z or (not b)
The unary logical operator not
ï provides a stronger binding than binary arithmetic operators
ï These bind stronger than relational operators
ï and these bind stronger than binary logical operators
Some parentheses on the previous slides were actually redundant, butshould still be used
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 25 / 45
Page 9
DeMorgan Rules
not (a and b) == (not a or not b)
not (a or b) == (not a and not b)
Examples
(not black and not white) == not (black or white)
not (rich and beautiful) == (poor or ugly)
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 26 / 45
Application – either . . . or (XOR)
(x or y) and not (x and y) x or y, and not both
(x or y) and (not x or not y) x or y, and one of them not
not (not x and not y) and not (x and y) not none and not both
not ((not x and not y) or (x and y)) not: both or none
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 27 / 45
Control Structures
Control Flow
So far. . .
Up to now linear (from top to bottom)
for loop to repeat blocks
x = int(input("Input: "))
for i in range(1, x+1):print(i*i)
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 28 / 45
Page 10
Control StructuresSelection Statements
Selection Statements
Implement branches
if statement
if-else statement
if-elif-else statement (later)
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 29 / 45
if Statement
if condition:statement
a = int(input("Input: "))if a % 2 == 0:
print("even")
If condition is true,then statement is executed
statement:arbitrary statementbody of the if-Statement
condition: Boolean expression
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 30 / 45
if-else Statement
if condition:statement1
else:statement2
a = int(input("Input: "))if a % 2 == 0:
print("even")else:
print("odd")
If condition is true,then statement1 is executed,otherwise statement2 is executed
condition: Boolean expression
statement1:body of the if-branch
statement2:body of the else-branch
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 31 / 45
Page 11
Layout
a = int(input("Input: "))
if a % 2 == 0:print("even")
else:print("odd")
Indentation
Indentation
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 32 / 45
Control Structureswhile Loops
while Loops
while condition:statement Indentation
statement:arbitrary statementbody of the while loop
condition: Boolean expression
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 33 / 45
while Loops
while condition:statement
condition is evaluatedTrue: iteration starts
statement is executedFalse: while loop ends
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 34 / 45
Page 12
while Loops
s = 0i = 1while i <= 2:
s = s + ii = i + 1
i condition s
i = 1 true s = 1i = 2 true s = 3i = 3 false s = 3
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 35 / 45
Incrementation of Variables
Use simplified syntax for changing values of variables
n = n + 1 is written as n += 1
n = n + i is written as n += i
n = n - 15 is written as n -= 15
n = n * j is written as n *= j
n = n ** 4 is written as n **= 4
. . .
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 36 / 45
The Jump Statements break
break
Immediately leave the enclosing loop
Useful in order to be able to break a loop “in the middle”
s = 0
while True:x = int(input("Enter a positive number, abort with 0: "))if x == 0:
breaks += x
print(s)
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 37 / 45
Control StructuresTermination
Page 13
Termination
i = 1while i <= n:
s += ii += 1
Here and commonly
statement changes its value that appears in condition
After a finite number of iterations condition becomes false
ï Termination
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 38 / 45
Infinite Loops
Infinite loops are easy to generate
while True:print("0")
while not False:print("1")
while 2 > 1:print("2")
. . . but can in general not be automatically detected
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 39 / 45
Halting Problem
Undecidability of the Halting Problem [Alan Turing, 1936]
There is no Python program that can determine, foreach Python program P and each input I, whether P
terminates with the input I
This means that the termination of programs can ingeneral not be automatically checked
Theoretical questions of this kind were the main motivation for Turing to designhis computing machine
Alan Turing [Wikimedia]
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 40 / 45
The Collatz Sequence
Sequence of natural numbers n0, n1, n2, n3, n4, n5, . . .
n0 = n
for every i ≥ 1, ni =
ni−1/2 if ni−1 even
3 · ni−1 + 1 if ni−1 odd
Example for n = 5
5, 16, 8, 4, 2, 1, 4, 2, 1, . . . (repetition at 1)
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 41 / 45
Page 14
Exercise – The Collatz Sequence
Write a program that
takes an integer n as input
outputs the Collatz sequence usingn0 = n and
ni =
ni−1/2 if ni−1 even
3 · ni−1 + 1 if ni−1 odd
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 42 / 45
Exercise – The Collatz Sequence
n = int(input("Compute the Collatz sequence for n = "))
while n > 1: # stop when 1 is reachedif n % 2 == 0: # n is even
n //= 2else: # n is odd
n = 3 * n + 1print(n, end=" ")
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 43 / 45
The Collatz Sequence
Example for n = 27
27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121364 182 91 274 137 412 206 103 310 155 466 233 700 350 175526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 27341367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 4331300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 16080 40 20 10 5 16 8 4 2 1
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 44 / 45
The Collatz Sequence
The Collatz Concecture [Lothar Collatz, 1937]
For every n ≥ 1, 1 will occur in the sequence
Nobody could prove the conjecture so far
If it is wrong, then the while loop for computing theCollatz sequence can be an endless loop for some n
as input
Lothar Collatz [Wikimedia]
Programming and Problem-Solving – Control Structures Spring 2020 Dennis Komm 45 / 45