CS 1 Lecture 3

Variables, values, and expressions

Professor Devin Balkcom
devin@cs.dartmouth.edu
office: Sudikoff 206

http://www.cs.dartmouth.edu/~cs1

Reminders

Variables

Assignment statement:

  1. Create a variable, if it does not exist.
  2. Copy the value on the right into the variable on the left.

Variable names vs. strings

Strings have quotation marks around them. Variable names don't.

= does not mean equal

Bad math:

$x = 5$
$x = 6$

Legal python:

(Good) variable names

meaning_of_life = 42

Variables can change code behavior

Exercise: big smile

Do exercise: big smile from the online notes for chapter 2 now.

How memory works

01011100 10110101 11011011 00001111 10101010

bit: A binarity digit, with the value 0 or 1.

byte: A group of 8 bits in memory.

I need five volunteers.

Encoding data in binary

01 01 11 00 10 11 01 01 11 01 10 11 
 b  b  d  a  c  d  b  b  d  b  c  d   

Imagine this is a secret code, with:

code value
00 a
01 b
10 c
11 d

How many bits for each type of data?

How many bits long should my bit-pattern be to give a unique pattern to every student in CS 1?

How many eight-bit patterns are there?

count code
1 00000000
2 00000001
3 00000010
... ...
256 11111111

Interpreting memory

To interpret a value in memory, Python needs to know:

  1. the address: where the value is
  2. the length: how many bits it is
  3. the type: how it is encoded

For each variable, Python keeps track of all that for you. (You just use the name, and Python does the rest.)

Types of values

Integer type

meaning_of_life = 42

An int is typically 4 bytes long on a modern machine.

$2^{32}$ is $4294967296$

Floating point type

# number of molecules in an avocado
avocado_number = 6.02e23 

weight_of_ant_in_grams = .004

# these are different!
meaning = 42.0    
life = 42

Used to represent big or small numbers. 8 bytes.

If floats and ints are both 8 bytes, how can a float hold a number bigger than 9223372036854775807?

String type

lukes_father = "Darth Vader"

We can use one byte per character, using ASCII code.

Fortunately, there are no more than 256 letters, digits, etc. Right?

Not if you write Chinese. A story for another day.

Boolean type

i_love_cs = True

One bit should be enough to represent true or false.

(Actually, Python uses a whole byte. So wasteful.)

Expressions

You can use an expression anywhere a value is required.

Expression examples

Converting between types

Code style

Bad code:

x = 73
y = x / 12
z = x % 12

print y
print z

Code style

With meaningful variable names:

height_in_inches = 73
feet = height_in_inches / 12
inches = height_in_inches % 12

print feet
print inches