Introduction to Algorithms &
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
TYPES, VARIABLES & VALUES
Variable
• Stores information in memory
• Symbolic name (identifier) → some data
(value)
• Not quite mathematical variable: Let 𝑥 = 12𝜋
…
– We wouldn’t say: …
Now let 𝑥 = 𝜋 2
…
Types
• Specifies what kind of data the variable can
hold
• Depending on language, vars may have a type
– Static vs dynamic typing
• Python variables do not have a type
(dynamic)!
• A single variable can hold any kind of data
Python Data Types
Name Values Allowed Example Literals
Integer Any integer of any size! 0, -1, 2145, 0xa3
Float Real-valued numbers within some range and 1.2, -0.6, .3,
to some precision (~15 decimal places) 1.4e10
Boolean True or false values only True, False
String Any sequence of characters “T-Pain sucks”,
“Jeff”
Complex* A real and imaginary part of a complex 2+7j
number
See https://realpython.com/python-data-types for more!
Names
• A unique identifier
• Starts with a letter or underscore; contains letters,
digits, and underscores
• Case-sensitive
• Users can’t define names that are taken as keywords
Choose meaningful names
– Abbreviations and acronyms can confuse people
– Short names can be meaningful
– Don’t use overly long names
• Lower-case with words separated by underscores
preferable e.g. total_amount
Reserved Keywords for Python3
False None True and as
assert break class continue def
del elif else except finally
for from import in is
lambda nonlocal not or pass
raise return try while with
yield
DIFFERENT LANGUAGES HAVE DIFFERENT KEYWORDS
Declaration/Assignment
• For variables, need value and name
• Assign name to a value
meaning_of_life = 42
y = 2.45824406892
some_name = "Pogba's Haircuts"
• Uses equal sign; LHS names value of RHS
Not mathematical equals
Assignment
• Use equal sign; LHS set to the value of RHS
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
s1: 11 | “Hello world”
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
These are comments
Python
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
• This is called integer division!
• In Python3, use 9 // 2 which gives 4
Mathematical Functions
• Python provides set of built-in functions
pow(2, 4) # or equivalently 2**4 = 16
abs(-16) # 16
round(2.929489384) # 3
See https://docs.python.org/3/library/functions.html for more!
Rules of Precedence
• Operators have precedence (like BODMAS)
Precedence Operator Evaluation
Operation
Level /Symbol Direction
0 (first) () parentheses Inner ones
evaluated first
Left-to-right
1 ** exponentiation Groups right-to-
left
2 (unary) - negation (unary minus) Right-to-left
3 *, /, % product, division, Left-to-right
modulus
4 +, - addition, subtraction Left-to-right
Question
• What is:
6 // 4 + −9 % 3 ∗ 2 / −100 ∗ −3 − −(17∗5)
…
…
=86.0
When in doubt, use brackets/simplify!
Python
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!
• Input is done with input()
• Output is done with print()
Input
• input() reads in a string from the user.
– Returns when the user enters a new line
line = input()
• If we don’t want a string, we must cast it
points_total = int(input())
average_score = float(input())
Prompting
• Warning: do not do this for automatically
marked submissions!
• We can be polite and inform the user what we
want them to input
print("Please enter your password and press Enter")
password = input()
Output
• print() displays something on the screen
print("Hello world")
x = 23
print(x)
• We can also print multiple values on the same
line
print("The best number is", 42)
A Note on Submissions
Submissions are marked by output only
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
Please enter an integer
42
The number you entered was 42
WRONG! CORRECT!
Example
• Calculate amount after adding VAT
vat = 0.15
print("Enter amount:")
prevat = float(input()
postvat = prevat * (1 + vat)
print("The amount including VAT is", postvat)