Chapter 2: Variables, expressions, and statements


Contents


This notebook is based on "Think Python, 2Ed" by Allen B. Downey
https://greenteapress.com/wp/think-python-2e/


Values and types

  • A value is a basic piece of data
  • Values belong to different types (or, more commonly, datatypes)
  • Python will tell you what type a value is using the type function
  • Integer values are whole numbers
  • Numbers with decimal types are referred to as float-point values

In [1]:
# Integer data
type( 17 )


Out[1]:
int

In [2]:
# Floating-point data
type( 17.0 )


Out[2]:
float

In [3]:
# A number inside a string
type( '17' )


Out[3]:
str

Variables

  • A variable is a name, or label for a value
  • It has no inherent meaning
  • An assignment statement gives a variable a value
  • In Python, it even creates the variable if it hasn't been created before

In [4]:
count = 55
size = 42.0
  • The print function displays the value of a variable

In [5]:
print( count )


55
  • The type of a variable is the type of its value

In [6]:
type( count )


Out[6]:
int

Variable names and keywords

  • Variables names need to be meaningful
  • Don't use x, y, and z as names unless they have real meaning in the problem (like 3-d points)
  • Variable names can be arbitrarily long and can contain:
    • letters
    • numbers
    • underscores
  • They have to begin with a letter
  • You can use uppercase letters, but start variables with a lowercase letter
  • Python is case sensitive so max and Max are different variables
  • An illegal variable name is a syntax error
  • Python has 30 keywords which are words that mean something specific in the language

Statements

  • A statement is a unit of code that the Python interpreter can execute
  • Usually a statement is a single line of code, but
  • It can be longer depending on the type of statement
  • A script (or program) usually contains a sequence of statements

Operators and operands

  • Operators are special symbols that represent computations like addition and multiplication
  • The value(s) to which the operator is applied is called an operand

In [7]:
# Operator: + (addition)
# Operands: 3 and 4
3 + 4


Out[7]:
7

In [8]:
# Operator: - (subtraction)
# Operands: 3 and 4
3 - 4


Out[8]:
-1

In [9]:
# Operator: *tiplication (mul)
# Operands: 3 and 4
3 * 4


Out[9]:
12

In [10]:
# Operator: / (division)
# Operands: 3 and 4
3 / 4


Out[10]:
0.75
  • There is a special division operator // called floor division
  • It throws away the remainder

In [11]:
10 / 3


Out[11]:
3.3333333333333335

In [12]:
10 // 3


Out[12]:
3
  • If either operand is a float, the result is a float

In [13]:
5 * 2


Out[13]:
10

In [14]:
5 * 2.0


Out[14]:
10.0

In [15]:
5.0 * 2


Out[15]:
10.0

In [16]:
5.0 * 2.0


Out[16]:
10.0

Expressions

  • An expression is a combination of values, variables and operators
  • A value or a variable is itself an expression
  • The interpreter evaluates expressions and uses the result for other expressions or simply displays it (if it is executed in the console)
  • A statement is comprised of one or more expressions

Order of operations

  • The order in which operators are evaluated in an expression depends on the rules of precedence
  • Python follows the standard mathematical convention
  • You may know it as PEMDAS
    1. Parenthesis
    2. Exponent
    3. Multiplication
    4. Division
    5. Addition
    6. Subtraction

In [17]:
1.0 / ( 2 * 3.14159 )


Out[17]:
0.15915507752443828

String operations

  • In general, you can't use mathematical operators with string values or variables
  • Even if the strings look like numbers

In [18]:
# Can't divide a string by an integer
# Uncomment to demonstrate
# '13' / 42
  • One exception is the + operator
  • It performs concatenation with strings
  • This means that it joins strings together

In [19]:
'fizz' + 'buzz'


Out[19]:
'fizzbuzz'
  • Another exception is the * operator
  • It repeats a string

In [20]:
'la' * 3


Out[20]:
'lalala'

Comments

  • Comments are a way for you to add notes to your program
  • They improve understanding of your code by describing the why of the code
  • Code already provides the how, so don't have your comments repeat that
  • This assumes that your code is understandable an you have chosen appropriate variable names

In [21]:
# Poor example
# Calculate it
y = 2
x = 2 * 3.14 * y

In [22]:
# Good example
# Calculate circumference of a circle
pi = 3.14
radius = 2
circumference = 2 * pi * radius
  • There are multiple ways to denote comments in your code
  • The easiest is to use the # character
  • Everything from the # to the end of the line is ignored
  • Although the book shows comments to the right of the code, I prefer that you put the comment above the code it describes

Exercises

  • Complete Exercise 2.2 from page 15 of the textbook "Think Python, 2Ed". It has three (3) parts. Write Python code that computes the answer of all three.
    1. The volume of a sphere with radius $r$ is $\frac{4}{3} \pi r^3$. What is the volume of a sphere with radius 5?
    2. Suppose the cover price of a book is \$24.95, but bookstores get at 40% discount. Sipping costs \\$3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?
    3. If I leave my house at 6:52am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?
  • Write Python code that converts three (3) different Fahrenheit temperatures to Celsius temperatures.
  • Write Python code that converts three (3) different distances given in miles to kilometers.