Lecture Notes
Introduction to Programming and Algorithm Design (COP-1000)

Variables, expressions, and statements

This chapter introduces the basic building blocks of programming languages: variables, operators, expressions, and statements. Don't forget to study and learn the terms in the glossary on page 19.


Values and types

  • Remember our definition of computer: A machine that stores and manipulates information under the control of a changeable program.
  • This "information" is composed of individual values (how many gallons, the temperature in degrees Celsius, etc.)
  • The values we manipulate are of many different types, but we'll concern ourselves for now with the three basic data types that Python handles:
Type Abbreviation Definition Example
Integer int Exact whole number 13
Floating-point float Approximate number with a fractional value 13.27
String str Sequence of characters "Hello"
  • You can use the built-in function type() to display a value's type:

>>> type(13)
<type 'int'>
>>> type(13.27)
<type 'float'>
>>> type("Hello")
<type 'str'>
>>> type("13")
<type 'str'>

  • Note in the last example above, "13" is a str, not an int, because it is enclosed in quotations

Variables

  • A variable is a name that refers to a value (also called an identifier)
  • More specifically, a variable refers to a place in memory where a value is stored
  • In Python, a variable is created with an assignment statement, that creates a variable name and assigns a value to it:

>>> greeting = "Hello"
>>> temp = 78.4
>>> testGrade = 95

  • The = is called the assignment operator and is pronounced "gets" (as in "testGrade gets 95")
  • A variable's type is the type of the value to which it refers:

>>> type(greeting)
<type 'str'>
>>> type(temp)
<type 'float'>
>>> type(testGrade)
<type 'int'>


Variable names and keywords

  • You (the programmer) choose the names for the variables in your program
  • Some rules to follow in choosing variable names:
    • Use only letters and numbers and the underscore character
    • Must start with a letter
    • No embedded spaces
    • Can be arbitrarily long
    • Should be meaningful (i.e., descriptive)
    • Use all lowercase except "camel case" multipleWordVariableNames
    • Can't be a Python keyword
  • You'll get a compiler syntax error if you violate one of these rules:

>>> my variable = 7
SyntaxError: invalid syntax


Statements

  • A statement is a complete instruction that the Python interpreter can execute
  • A statement may produce output (like a print statement) or not (like an assignment statement)
  • A statement is usually typed on one line
  • A sequence of statements is called a script or a program
  • A program is usually written with a text editor which is often the editing window in the Python IDLE and saved to a file

Operators and operands

  • Operators are symbols that are used to represent computations
  • The values on which the operator acts are called operands
  • In the expression a + 6, the operator is +, and the operands are a and 6
  • The operators used in Python for operations on numeric values are:
Operator Operation Example Result

+
-
*
/
 
**
%
abs()

addition
subtraction
multiplication
division
 
exponentiation
remainder (modulus)
absolute value

2 + 7
2 - 7
2 * 7
7 / 2
7.0 / 2
2 ** 7
7 % 2
abs(-5)

9
-5
14
3
3.5
128
1
5

  • Note that division ( / ) is integer division if both operands are integers: the result of the division is an integer (any fractional part is discarded); if either (or both) operand is a floating point value, the result is a floating point (any fractional part is retained)
  • The remainder operator ( % ) yields the integer remainder of dividing the first integer operand by the second

Evaluating expressions

  • An expression is a combination of one or more values and variables (operands), joined by operators
  • When the interpreter encounters an expression, it evaluates it, which means reducing it to a single value
  • If the expression was entered by itself in the interactive mode, the expression is evaluated and the result displayed:

>>> 4 * 3 / 2
6

  • If an expression is encountered on a line by itself in a program, it is evaluated but nothing is displayed
  • An expression is almost always part of a statement (like this assignment statement):

>>> x = 5 * 4
>>>


Order of operations

  • If an expression contains only one operator, there is no confusion as to how to evaluate it
  • But if an expression contains two or more operands, the order in which the operations are performed makes a great deal of difference; for example:

2 + 3 * 4 -> 20 (if + is performed before *)
2 + 3 * 4 -> 14 (if * is performed before +)

  • Every programming language reference has a precedence table that documents the order in which operators are evaluated in an expression; here is the one for Python
  • Most operators with the same precedence are evaluated left-to-right in an expression
  • Notice parentheses are the highest precedence, so they can be used to force the desired order of operations; even if parentheses are not required, they are sometimes used for clarity:

c = (5.0 / 9.0) * (f - 32)

  • See the sample program f2c.py

Operations on strings

  • So far we have discussed just expressions containing numeric values, variables, and operators
  • In Python, two operators are provided that operate on strings
  • The concatenation operator + joins two strings:

>>> firstName = "Bill"
>>> lastName = "Day"
>>> fullName = lastName + ", " + firstName
>>> print fullName
Day, Bill

  • The repetition operator * generates a new string by repeating a string the specified number of times

>>> cheer = "Hi"
>>> cheers = cheer * 3
>>> print cheers
HiHiHi


Comments

  • When you write a program, it is often helpful to insert comments to document your code to make it more maintainable
  • In Python anything following the # character on a line is ignored by the interpreter (although it is saved with your source code)
  • Use comments to document (source code filename, date written, short description), or to explain a tricky or complex part of your logic; don't use comments if the purpose or logic of the code is self-evident

Composition

  • In programming, composition means to perform more than one thing in a single statement
  • For example, this line evaluates an expression and displays the result:

>>> print "Bye" * 5
ByeByeByeByeBye

  • We will use composition a lot, especially when we get to functions (the next chapter)
 Updated: 12.13.2010