WELCOME TO
COMP 208!
Lecture 2: Binary numbers, Python basics
January 9/10, 2020
Instructor: Jonathan Campbell
Plan for today
• Binary numbers
• Use of binary in computers
• Python basics
• Values & types
• Variables
2
Question poll test
• Session ID:
• http://mcgill.ca/polling
What is the brain of the computer?
A. The CPU
B. The hard drive
C. The printer
D. The system administrator
3
Binary numbers
Decimal number system
• The number system we use in every day life.
• Contains ten digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
• We say it has a base of 10 because it has 10 digits.
Two thousand nineteen 2 0 1 9
5
Decimal number system
Each digit in the sequence is a different power of 10.
E.g., for the number 2019:
Powers of 10
103 102 101 100
(Place Value) (1000) (100) (10) (1)
Digit 2 0 1 9
2019 = 2 × 103 + 0 × 102 + 1 × 101 + 9 × 100
6
Binary number system
• The number system used to represent
information in computers.
• Contains two digits: 0, 1.
• So it's base 2.
• To represent a regular decimal number,
we use a sequence of bits. E.g.,
183 1 0 1 1 0 1 1 1
7
Binary number system
Each digit in the sequence is a different power of 2.
E.g., for the binary number 11010:
Powers of 2
24 23 22 21 20
(Place Value) (16) (8) (4) (2) (1)
Digit 1 1 0 1 0
110102
8
Converting from binary to decimal
Multiply each digit by the corresponding power of 2, and add.
E.g., for 11010:
Powers of 2
24 23 22 21 20
(Place Value) (16) (8) (4) (2) (1)
Digit 1 1 0 1 0
= 1 × 24 + 1 × 23 + 0 × 22 + 1 × 21 + 0 × 20
110102 = 2610
9
Converting from decimal to binary
• The "divide by 2" algorithm.
• Take the number, divide it by 2,
and record the remainder (0 or 1).
• Then take the result of the division (the quotient)
and divide that by 2, record remainder, and so on.
• Then the binary number is the reversed sequence
of remainders.
10
Decimal to binary - example (1)
Let's convert 109 to binary:
1. Repeatedly divide
the number by 2
until result is 0.
11
Decimal to binary - example (2)
Let's convert 109 to binary:
2. Write the remainders
from bottom to top:
1, 1, 0, 1, 1, 0, 1
109 =
11011012
12
Binary in computers
Bits
• A bit is a binary digit (i.e., either 0 or 1).
• The most basic unit of information in a computer.
• All data in the computer is represented by bits.
Real world data
Computers
numbers
work with
text
binary numbers
images
(0’s & 1’s)
audio/video
14
Bytes
• A byte is a collection of 8 bits.
• "Megabyte" = 1 million bytes
• "Gigabyte" = 1 billion bytes
• "Terabyte" = 1 trillion bytes
15
Bits in Python
• We don't deal with bits/bytes directly in Python.
• Python has abstractions like 'integer' or 'character',
letting us write code with regular numbers and letters.
• But it's important to know as a foundation of computing.
16
Integers in binary
• We already saw how to represent positive integers
109 =
11011012
• For negative numbers, we use an extra bit for the sign:
-109 = 109 =
111011012 011011012
17
Finite precision
" Digits of π run forever:
3.14159265358979323846264338327950
28841…
● Since we have finite bits, we can only
have finite precision. E.g., with 64 bits:
3.141592653589793
18
Real numbers in binary
0100000000001001
0010000111111011
0101010001000100 3.141592653589793
0010110100011000
Floating-point
format
(64 bits)
19
Text in binary
01101000 h
01100101 e
01101100 l
Character encoding
01101100 (e.g. ASCII or Unicode) l
01101111 o
Computer stores Characters we
text data as bytes see on screen
(1 byte = 8 bits)
20
Images, audio & video
• Even for complex data, the idea remains the same.
• We use a content format to represent this data as bits.
• Programs are then written that can process these bits.
• E.g., an image program reads bits in a .png file
and displays it on screen as an image.
• We already know some of these formats:
• Images: jpeg, png
• Audio: mp3, m4a, wma
• Video: mp4, avi, wmv
21
For further info
• Computer heuristics lecture -- Richard Feynman
https://www.youtube.com/watch?v=EKWGGDXe5MA
22
Python
Our first Python program
print("Hello World")
1. Launch Thonny.
2. Put the above code in the top-left editing area.
3. Press the Run button (green circle/white triangle).
4. Choose a place to save the file.
5. The code will run; we see its output in the bottom-left.
25
Our first Python program
Here is a multi-line program.
print("Hello World")
print("This is our first Python program!")
26
Errors
We have to make sure to respect the syntax of Python.
That means, for example, closing parentheses '(' that we have
opened.
print("Hello World")
print("This is our first Python program!")
print("I think I'm forgetting something...."
If we try to run this code, we get:
SyntaxError
27
Interactive mode
• In the bottom-left of Thonny, where output is shown,
we can also write code directly, one line at a time.
• We write code after the ">>>", which is called the prompt.
• The code we type is run as soon as we hit [return].
• But code we write there can't be saved to a file. So we only
use it to test out short things that we don't need to save.
28
Values & Types
Values
• A value is a piece of data that is stored and manipulated
in computer memory by a program.
• A value is also called an object.
30
Types
• Every value has a type associated with it.
• Python has the following basic types:
• int: whole numbers, like 123, 1000, -54, 0, etc.
• float: real numbers, like 0.1, 3.14, etc.
• str: text (strings): "Hello World","COMP 208", etc.
• We will see more later ('bool' next class).
31
print()
• The print() function allows us to display values on screen.
• (More on what a function is later.)
>>> print("Hello World!")
Hello World!
>>> print(3000)
3000
>>> print(3.1415)
3.1415
32
Printing multiple values
• The print() function can print multiple values.
• We separate the values with commas:
>>> print('Radius of circle:', 5)
Radius of circle: 5
>>> print('Area of circle with radius', 5,
'is', 78.5)
Area of circle with radius 5 is 78.5
33
type()
• The type() function gives us the type of a value.
>>> print(type("Hello World!"))
<class 'str'>
>>> print(type(3000))
<class 'int'>
>>> print(type(3.1415))
<class 'float'>
34
Comments
• Code can be hard to read.
• So it's good to add notes in our code
to describe what's going on.
• These notes are called comments.
• Comments begin with a "#" symbol.
They are ignored by Python.
35
Comments
# Author: (your name here)
# My first Python program!
# Printing something to the screen
print("Hello World!")
# Now printing the type of "Hello World".
print(type("Hello World!"))
36
The int type
• An integer value can only contain the digits 0-9.
>>> print(12345)
12345
>>> print(12345a)
SyntaxError: invalid syntax
37
The float type
• If a dot ('.') is included in a number, it is considered a float.
>>> print(3.14)
3.14
>>> print(123.) # adding a dot makes it a float
123.0
>>> print(type(123.))
<class 'float'>
>>> print(.001) # no digits before dot is OK
0.001
38
Basic operations on numbers
Operation Example Result
Addition 7 + 12 19
Subtraction 3.14 - 2.78 0.3600000000000003
Multiplication 2 * 3.1416 6.2832
Division 33 / 8 3.3
39
Basic operations on numbers (2)
Operation Example Result
Modulus 27 % 10 7
Exponentiation 2 ** 3 8
Negative -(3 + 8) -11
Any combination 2 + 6*2 - 8**2 / 4 -2.0
40
Division vs. floor division
• The division operator ("/") gives us
a floating point number as result for any division,
even if both numbers are integers.
• The floor division operator ("//") rounds down
to the nearest whole number.
If both numbers are ints, result will be integer.
>>> print(105 / 60)
1.75
>>> print(105 // 60)
1
41
Modulus operator
• The modulus operator ("%") divides two numbers
and gives us the remainder.
>>> print(105 // 60)
1
>>> print(105 % 60)
45
# 105 divided by 60 is 1 with 45 remainder
42
Arithmetic operators and result type (1)
Left
Right
Result
Operator Examples
type type type
3 + 5 → 8
both ints int 15 * 3 → 45
Addition (+)
3 // 2 → 1
Subtraction (-)
Multiplication (*)
3 - 1.5 → 1.5
Exponentiation (**)
2.5 * 3.5 → 8.75
Floor Division (//)
at least
float 1.5 ** 2 → 2.25
Modulo (%) one float
3.5 - 1.5 → 2.0
3.2 // 2 → 1.0
43
Arithmetic operators and result type (2)
Left
Right
Result
Operator Examples
type type type
3 / 5 → 0.6
Division (/) int and/or float float
3.14 / 3.14 → 1.0
In summary,
" For division (/), result is always float
" For other operators,
○ if both operands are int, then result is int
○ if any operand is float, then result is also float
44
Order of arithmetic operations
• When an expression is evaluated, there is an order
of operations that is followed, similar to mathematics.
PEDMAS:
1. Parentheses
2. Exponentiation
3. Division & Multiplication
4. Addition & Subtraction
45
Order of operations: examples
# operator ** has higher priority than + & -
>>> print(2 ** 3 + 1) # 23 + 1 (not 23+1)
9
# operator ** has higher priority than * & /
>>> print(2 ** 4 / 2) # 24 / 2 (not 24/2)
8.0
46
Order of operations: examples (2)
# parentheses () have higher priority than all
>>> print( 2 ** (4 / 2) ) # 24/2
4.0
# addition, then multiplication, due to ()
>>> print((2 + 3) * (2 + 3))
25
# multiplication higher priority than addition
>>> print(2 + 3 * 2 + 3)
11
47
Order of operations: examples (3)
• Multiplication & division have the same priority
• Addition & subtraction have the same priority
• In case of ties, operations are evaluated from left to right.
>>> print(12 + 23 - 10) # left to right
25
>>> print(10 / 5 * 2) # left to right
4.0
>>> print(10 / (5 * 2)) # using () to change priority
1.0
48
Order of operations: examples (4)
• Let's say we want to evaluate with x being 10.
>>> print((10 ** 3 - 1) / 2) # correct
499.5
>>> print(10 ** 3 - 1 / 2) # incorrect
999.5
• Here, we must use parentheses, because exponentiation
is performed before subtraction or division.
49
The string type
• String values can be created
using double or single quotes.
• The quotes are not part of the value
-- they just indicate the start and end of the string.
>>> print("This is a string!")
This is a string!
>>> print('This is a string as well!')
This is a string as well!
50
Strings (2)
>>> print("") # printing an empty string
>>> print(type("")) # type of an empty string
<class 'str'>
51
Strings (3)
• Strings in single quotes can contain double quotes,
and vice-versa.
>>> print('They said: "The answer is 42"')
They said: "The answer is 42"
• But this gives an error because quotes don't match:
>>> print("Seems like a normal string...')
SyntaxError: invalid syntax
52
Basic operations on strings
• We can find the length (number of characters)
of a string using len().
>>> print(len('Hello'))
5
>>> print(len("Hello World"))
11 # length includes spaces
>>> print(len("")) # empty string
0
53
Basic operations on strings (2)
• We can put two strings together using the + sign.
>>> print("hello " + "world")
'hello world'
>>> print("123" + "456")
'123456' # not an arithmetic addition
54
Basic operations on strings (3)
• We can easily make a string repeat itself using *.
>>> print("hello " * 5)
'hello hello hello hello hello '
>>> print("1" * 10)
'1111111111' # not a numeric multiplication
>>> print("-" * 20)
'--------------------'
55
Variables
Variables
• So far we've mainly used Python as a calculator.
• Sometimes, we would like to remember results of
computations, so we don't have to recompute all the time.
>>> print("Sum is:", 10 + 5)
Sum is: 15
# to print the sum again,
# we have to redo the addition
• Variables allow us to remember values for later use.
57
Making a variable
• We can use a variable as follows to store a value:
>>> result = 10 + 5
>>> print("Sum is:", result)
Sum is: 15
# Now we can do other things with the result
# without having to recompute it.
>>> print("Square of the sum is:", result * result)
Square of the sum is: 225
58
Variables and assignment
• A variable in Python is a name that refers to a
specific value (object) in computer memory.
• We create a variable using the equals sign =
which is called an assignment operator.
59
Variables and assignment (2)
# assign the value 123 to variable x
>>> x = 123
>>> print("The value of x is", x)
The value of x is 123
60
Resources
• Binary/decimal conversion
https://www.purplemath.com/modules/numbbase.htm
• Think Python 2e
http://greenteapress.com/thinkpython2/thinkpython2.pdf
Sections 1.1-1.5, 1.7 (pgs. 1-6)
Exercises 1.1, 1.2 (pgs. 7-8)
Sections 2.1, 2.4-2.8 (pgs. 9-13)
Exercises 2.1, 2.2 (pgs. 14-15)
61
Reminders
• Tutorials next week/office hours to be announced soon.
• Sign up for account at mcgill.ca/polling.
(Real question polling starting next week.)
62