2. Variables, Expressions and Statements

Values, Data Types, and ID

A value (object) is one of the fundamental things — like a word or a number — that a program manipulates.

Objects are classified into different classes, or data types.

Every object has an identity, a type and a value.

In [1]:
print(type("Hello, World!"))
print(type(17))
print("Hello, World!")
<class 'str'>
<class 'int'>
Hello, World!
In [2]:
print(type(3.2))
print(id(3.2))
<class 'float'>
140730377995368
In [3]:
print(type("3.2"))
print(id("3.2"))
<class 'str'>
140730378229272
In [4]:
print(type('This is a string.') )
print(type("And so is this.") )
print(type("""and this.""") )
print(type('''and even this...''') )
print(type('''and even this...''')  is str)
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
True
  • Double quoted strings can contain single quotes inside them.
  • Single quoted strings can have double quotes inside them.
In [5]:
print("Bruce's beard")
print('The knights who say "Ni!"')
Bruce's beard
The knights who say "Ni!"

Strings enclosed with three occurrences of either quote symbol are called triple quoted strings.

They can contain either single or double quotes.

In [6]:
print('''"Oh no, Ben's bike is broken!"''')
"Oh no, Ben's bike is broken!"

Triple quoted strings can even span multiple lines.

In [7]:
print('''This message will span
several lines
of the text."""''')
This message will span
several lines
of the text."""

For string, the surrounding quotes are not part of the value.

In [8]:
print('Hi')
print("Hi")
print('Hi' == "Hi")
print('Hi' is "Hi")
Hi
Hi
True
True
In [9]:
print(42000)
print(42,000)
42000
42 0
In [10]:
print(42, 17, 56, 34, 11, 4.35, 32)
print(3.4, "hello", 45)
42 17 56 34 11 4.35 32
3.4 hello 45

Exercise

1. How can you determine the type of a variable?
(A) Print out the value and determine the data type based on the value printed.
(B) Use the type function.
(C) Use it in a known equation and print the result.
(D) Look at the declaration of the variable.
2. What is the data type of ‘this is what kind of data’?
(A) Character
(B) Integer
(C) Float
(D) String

Type conversion functions

Python type conversion function:

  • int

  • float

  • str

  • bool

In [11]:
print(3.14, int(3.14))
print(3.9999, int(3.9999))  
print(3.0, int(3.0))
print(-3.999, int(-3.999))  
print("2345", int("2345"))  
print(17, int(17)) 
3.14 3
3.9999 3
3.0 3
-3.999 -3
2345 2345
17 17
In [12]:
print(int("23bottles"))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-06d3fcee09e6> in <module>
----> 1 print(int("23bottles"))

ValueError: invalid literal for int() with base 10: '23bottles'
In [13]:
print(float("123.45"))
print(type(float("123.45")))
print(type(float("123.45")) is float)
print(type("123.45") is str)
123.45
<class 'float'>
True
True
In [14]:
print(str(17))
print(str(123.45))
print(type(str(123.45)))
17
123.45
<class 'str'>

Implicit conversion

Narrow to wide:

bool ⇒ int ⇒ float

1.0/2

Exercise

What value is printed when the following statement executes?
print( int(53.785) )
(A) Nothing is printed. It generates a runtime error.
(B) 53
(C) 54
(D) 53.785

Variables

A variable is a name that refers to a value.

Assignment statements create new variables and also give them values to refer to.

In [15]:
message = "What's up, Doc?"
n = 17
pi = 3.14159

The assignment statement links a name, on the left hand side of the operator(=), with a value, on the right hand side.

In [16]:
message = "What's up, Doc?"
n = 17
pi = 3.14159

print(message)
print(n)
print(pi)
What's up, Doc?
17
3.14159
In [17]:
message = "What's up, Doc?"
n = 17
pi = 3.14159

print(type(message))
print(type(n))
print(type(pi))
print(id(pi))
<class 'str'>
<class 'int'>
<class 'float'>
140730377995608

Variables are variable.

They can change over time

You can assign a value to a variable, and later assign a different value to the same variable.

In [18]:
day = "Thursday"
print(day)
day = "Friday"
print(day)
day = 21
print(day)
Thursday
Friday
21

Variable Names and Keywords

Variable names can be arbitrarily long.

They can contain both letters and digits, but they have to begin with a letter or an underscore.

Exercise: which variable names is illegal?

76trombones = "big parade"
more$ = 1000000
class = "Computer Science 101"
_, _class, class_, __name, __name__ = 2,3,4,5,6
In [19]:
76trombones = "big parade"
more$ = 1000000
class = "Computer Science 101"
  File "<ipython-input-19-738a78e2a131>", line 1
    76trombones = "big parade"
              ^
SyntaxError: invalid syntax

Python keywords

- - - - - - -
and as assert break class continue def
elif else except exec finally for from
global if import in is lambda nonlocal
not or pass raise return try while
with yield True False None

Programmers generally choose names for their variables that are meaningful to the human readers of the program — they help the programmer document, or remember, what the variable is used for.

Exercise

Is the following a legal variable name in Python? 
A_good_grade_is_A+
(A) True
(B) False

Statements and Expressions

A statement is an instruction that the Python interpreter can execute.

An expression is a combination of values, variables, operators, and calls to functions.

Expressions need to be evaluated.

In [20]:
print(1 + 1)
print(len("hello"))
2
5

The evaluation of an expression produces a value

In [21]:
y = 3.14
x = len("hello")
print(x)
print(y)
5
3.14

Evaluate variable y in Python shell or Notebook

In [26]:
>>> y = 3.14
>>> x = len("hello")
>>> print(x)
5
>>> print(y)
3.14
>>> y
3.14
5
3.14
Out[26]:
3.14
In [23]:
y
Out[23]:
3.14

Operators and Operands

Operators are special tokens that represent computations like addition, multiplication and division.

The values the operator works on are called operands.

Type int

  • Values: integers

  • Ops: +, –, *, /, //, %, **

Type float

  • Values: real numbers

  • Ops: +, –, *, /, **

Type bool

  • Values: True and False

  • Ops: not, and, or

Type str

  • Values: string literals
    • Double quotes: "abc"
    • Single quotes: 'abc'
  • Ops: + (concatenation)
20 + 32
hour - 1
hour * 60 + minute
minute / 60
5 ** 2
(5 + 9) * (15 - 7)
In [27]:
print(2 + 3)
print(2 - 3)
print(2 * 3)
print(2 ** 3)
print(3 ** 2)
5
-1
6
8
9
In [28]:
minutes = 645
hours = minutes / 60
print(hours)
10.75
In [29]:
print(7 / 4)
print(7 // 4)
minutes = 645
hours = minutes // 60
print(hours)
1.75
1
10
In [30]:
quotient = 7 // 3     
print(quotient)
remainder = 7 % 3
print(remainder)
2
1
In [31]:
total_secs = 7684
hours = total_secs // 3600
secs_still_remaining = total_secs % 3600
minutes =  secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining % 60
print("Hrs=", hours, "mins=", minutes, "secs=", secs_finally_remaining)
Hrs= 2 mins= 8 secs= 4

Exercise

1. Evaluate the following expressions.

18 / 4
18 // 4
5 ** 2
9 * 5
5 % 2
9 % 5
6 % 6
0 % 7

Order of Operations

Operations are performed in a set order

  • Parentheses make the order explicit

  • Python processes operators in fixed order in absence of parentheses

In [32]:
2*1 + 3
2*(1 + 3)
Out[32]:
8

Precedence of Python Operators

  • Exponentiation: **
  • Unary operators: + –
  • Binary arithmetic: * / // %
  • Binary arithmetic: + –
  • Comparisons: < > <= >=
  • Equality relations: == !=
  • Logical not
  • Logical and
  • Logical or
In [33]:
print(2**1+1)
print(3*1**3)
print(2*3-1)
print(6-3+2)
print(6-(3+2))
3
3
5
5
1

Exercise

1. Calculate ${2^3}^2$

In [34]:
print(2 ** 3 ** 2)
print((2 ** 3) ** 2) 
512
64

2. Evaluate the following expressions.

2*3
2 ** 3
5+2*5
(5 + 2) * 5
-4 - -4 - -4
2 ** 2 ** 0
(2 ** 2) ** 0
6/2
6/4
6.0 / 4
6 / 4.0
9.0 * 0.5
9.0 ** 0.5
6%2
7%2
6.2 % 4

3. Evaluate bool expressions.

3<5
3 < 5 and 5 < 3
True
true
True and False
True or False
not True
not not False
not False and True
not (False or True)
True and False and True
True or (False and True)
(5/0==1) and False
False and (5/0==1)

Reassignment

It is legal to make more than one assignment to the same variable.

A new assignment makes an existing variable refer to a new value (and stop referring to the old value).

In [35]:
a = 5
b = a
print(a, b)
a = 3
print(a, b)
5 5
3 5

Exercise

After the following statements, x is ___ and y is ___?
x = 15
y = x
x = 22

Updating Variables

update: the new value of the variable depends on the old

x = x + 1

In [36]:
x = 6        # initialize x
print(x)
x = x + 1    # update x
print(x)
6
7

Input

Python uses a built-in function to accomplish data input: input

In [37]:
n = input("Please enter your name: ")
print("Hello", n)
Please enter your name: rty
Hello rty
Note
It is very important to note that the input function returns a string value.
In [39]:
str_seconds = input("Please enter the number of seconds you wish to convert")
total_secs = int(str_seconds)

hours = total_secs // 3600
secs_still_remaining = total_secs % 3600
minutes =  secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining  % 60

print("Hrs=", hours, "mins=", minutes, "secs=", secs_finally_remaining)
Please enter the number of seconds you wish to convert45.2
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-39-ddbcfcf82058> in <module>
      1 str_seconds = input("Please enter the number of seconds you wish to convert")
----> 2 total_secs = int(str_seconds)
      3 
      4 hours = total_secs // 3600
      5 secs_still_remaining = total_secs % 3600

ValueError: invalid literal for int() with base 10: '45.2'

Exercise

What is printed when the following statements execute?
n = input("Please enter your age: ")
# user types in 18
print ( type(n) )
(A) <class 'str'>
(B) <class 'int'>
(C) <class 18>
(D) 18

Operations on strings

+ : concatenation
* : repetition
In [40]:
print("Hello" + "World")
print("Hello"*3)
HelloWorld
HelloHelloHello

Exercise

1 Alarm clock problem

You look at the clock and it is exactly 2pm. You set an alarm to go off in 51 hours. At what time does the alarm go off?

2 Alarm clock problem in general

Write a Python program to solve the general version of the above problem. Ask the user for the time now (in hours), and ask for the number of hours to wait. Your program should output what the time will be on the clock when the alarm goes off.

3 Compound interest problem

$ A = P\left( 1 + \frac{r}{n} \right)^{nt} $

where:

P is the original principal sum
r is the nominal annual interest rate
n is the compounding frequency
t is the overall length of time in years.
In [ ]: