Comp 112

Lecture 2

Expressions, Variables, Statements and Programs

2017.02.07

Expressions and Values

A Simple Expression Language

Integer Values (0, 1, 2, -3, etc.)

Integer Arithmetic:

Boolean Values (True, False)

Boolean Logic:

Numeric Comparisons:

Evaluating Compound Expressions

The expression:

16 % 7 < 3 and 2 == 3 ** 2 // 4

parses as:

((16 % 7) < 3) and (2 == ((3 ** 2) // 4))

and evaluates to:

True

Types

Types classify expressions.

To ask Python the type of an expression, use:

type (<expression>)

e.g.

type (2 + 3)

The type of an expression is always the same as the type of its value.

Floats

What happens if we try to do division (/)?

Overloading is when different (but usually related) operations are given the same notation.

The types are used to tell them apart.

Strings

Statements

Variables

Variables (“references”, “assignables”) are names that refer to values.

Rules for variable names:

Variable Assignment

An assignment statement causes a variable to refer to the value of an expression:

<variable> = <expression>
life_the_universe_and_everything = 42

The value of the variable becomes that of the expression assigned to it.

life_the_universe_and_everything

Warning: assignment is not mathematical equality! Read “=” as “gets”, and note the difference to “==” (“is equal to”).

Variable Assignment Process

When an assignment statement is executed:

  1. First, the expression on the right is evaluated to a value.

  2. Next, that value is assigned to the variable on the left.

x = 1 + 1
x = x * x

Variable Tables

As Python runs a program, it repeatedly consults and updates its variable table to keep track of the program’s state.

Programs

Unlike the interactive interpreter, running a program from a file does not cause the value of every expression to be displayed.

x = 2
y = 3
x + y

Comments

Comments in Submissions

Every script file you turn in should begin with a comment containing:

  1. your name
  2. your Wesleyan email address
  3. the course number and your lab section
  4. the assignment name or number
  5. the date
"""
Jane Hacker
jhacker@wesleyan.edu
COMP 112, section 6
Homework 2
2017.02.07
"""

To Do This Week: