Lecture 2
Lecture 2
Programming
Steve James
Lecture 2
PYTHON3 DEMO
RECAP
Algorithms
• Individual, well-defined, predictable
instructions (finite).
• Direction of logic flow. Once an instruction is
executed, it passes control to another
instruction.
• Guaranteed to terminate.
Programming Languages
• Lowest level: binary
• Then assembly (mnemonics)
• Then high-level language
– Interpreter converts code to executable
instructions
Python
x = 42
y = 23
x = y
y = 17
All Together Now
a = 7 a: 7
b = 9 d gets a’s value
c = "?" If a changes, d b: 9
x = 1.2 stays the same
d = a c: 1 | “?”
s1 = "Hello world"
d = a + b x: 1.2
s2 = "1.2"
s1 = 91 d: 7
d: 16
s2: 3 | “1.2”
s1: 91
Finally
• Must declare a variable before we use it
x = y + 2 # WTF is y?!
y = 20 # Too late! We needed it for the previous line
ARITHMETIC OPERATORS
Operators
• Use operators to perform basic calculations
– Addition, subtraction, multiplication, division,
modulus
x = 8
y = 7
20 + 3 # 23
x - y # 1
5 * 10 # 50
9 / 2 # 4.5
9 % 2 # 1
DANGER!!!
• In Python3, 9 / 2 gives 4.5
• In Python2, 9 / 2 gives 4
• In C++, 9 / 2 gives 4
…
…
=86.0
BASIC INPUT/OUTPUT
Input and Output
• We want our programs to be flexible
– e.g. find a student’s marks given their student
number
• So we need to be able to accept input from
users and display the results!
line = input()
points_total = int(input())
average_score = float(input())
Prompting
• Warning: do not do this for automatically
marked submissions!
print("Hello world")
x = 23
print(x)
Bad Good
print("Please enter an integer:")
x = int(input())
print("The number you entered was", x)
x = int(input())
print(x)
I enter 42.
I enter 42.
Produces output
Produces output
WRONG! CORRECT!
Example
• Calculate amount after adding VAT
vat = 0.15
print("Enter amount:")
prevat = float(input()