1. Variables, expressions and statements#

1.1. Values and types#

A value is one of the basic things a program works with, like a letter or a number. Python is no exception. Here are some values.

3.14
"hello world"
True
7
7

If you run the above cell using ctrl-return the output will be 7. If you want to output all of the values to the output cell, then you can use print.

print(3.14)
print("hello world")
print(True)
print(7)
3.14
hello world
True
7

These values belong to different types : 7 is an integer, and ‘hello world!’ is a string, so-called because it contains a ``string’’ of letters. You (and the interpreter) can identify strings because they are enclosed in quotation marks.

If you are not sure what type a value has, the interpreter can tell you.

type("hello world")
str
type(7)
int

1.1.1. Exercise 1 #

What is the type of 3.14 and True ?

1.1.2. Solution 1#

print(type(3.14))
print(type(True))
<class 'float'>
<class 'bool'>

What about values like ‘17’ and ‘3.2’? They look like numbers, but they are in quotation marks like strings.

type('17')
str
type('3.2')
str

What about 1,000,000 ? This is not a legal integer in Python, but it is legal :

1,000,000
(1, 0, 0)

Python interprets 1,000,000 as a comma-separated sequence of integers. This is the first example we have seen of a semantic error : the code runs without producing an error message, but it doesn’t do the ``right’’ thing. 1,000,000 s an example of a python tuple. More on that later.

1.2. Variable assignment#

One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value.

An assignment statement creates new variables and gives them values :

message = 'And now for something completely different'
n = 17
pi = 3.1415926535897932

One way of representing this assignment is shown below. Note that the variable servers as a label for accessing a value.

title

Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase letters.

The underscore character, \verb”_”, can appear in a name. It is often used in names with multiple words, such as \verb”my_name” or \verb”airspeed_of_unladen_swallow”.

If you give a variable an illegal name, you get a syntax error:

76trombones = 'big parade'
  Cell In [10], line 1
    76trombones = 'big parade'
      ^
SyntaxError: invalid syntax
more@ = 1000000
SyntaxError: invalid syntax
  File "<ipython-input-10-4d9f2740846f>", line 1
    more@ = 1000000
          ^
SyntaxError: invalid syntax
class = 'Advanced Theoretical Zymurgy'
  File "<ipython-input-11-73fc4ce1a15a>", line 1
    class = 'Advanced Theoretical Zymurgy'
          ^
SyntaxError: invalid syntax

1.3. Python Keywords#

It turns out that class is one of Python’s keywords. The interpreter uses keywords to recognise the structure of the program, and they cannot be used as variable names.

Different versions of Python may have different keywords. Version 3.6.9 of CPython has the following :

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

Operators are special symbols that represent computations like addition and multiplication. The values the operator is applied to are called operands.

The operators +, -, *, / and ** perform addition, subtraction, multiplication, division and exponentiation, as in the following examples:

20+32
hour = 6
hour-1  
minute = 12
hour*60+minute   
minute/60   
5**2   
(5+9)*(15-7)
112

1.4. Expressions and statements#

An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions

x = 111
x
x + 17
128

A statement is a unit of code that the Python interpreter can execute. We have seen two kinds of statement: print and assignment.

Technically an expression is also a statement, but it is probably simpler to think of them as different things. The important difference is that an expression has a value; a statement does not.

1.5. Python operators#

Most versions of python provide the following operators :

+ - * / % // ** > < == != >= <= and or not & | ~ ^ >> << = += -= *= /= %= //= **= &= |= ^= >>= <<= is in is not

Some binary operators are left right associative, some are right left. There is also a ternary operator ``if else’’. Try the following exercise to learn more about some of the Python operators.

1.5.1. Exercise 2#

Have guess as to what the output should be for these commands

False and True
False
0 and True
0
1 and True
True
1 and 0
0
1 and 1
1
1 and 3
3
True and 3
3
3 and True
True
5*2//3
3
5*(2//3)
0
(5*2)//3
3
3**5**2
847288609443
3**(5**2)
847288609443
(3**5)**2
59049
2 if 1 < 2 else 3
2
a = 1
b = 1
a == b
True
a is b
True
a = 1000000
b = 1000000
a == b
True
a is b
False
a is not b
True
a is (not b)
False

1.6. Round of errors#

Computers have inexact arithmetic because of rounding errors. This is usually not a problem in computations, but in some cases it can cause unexpected results.

1.6.1. Exampe 1#

v1 = 1/49.0*49
v2 = 1/51.0*51
print(v1)
print(v2)
0.9999999999999999
1.0

Much of the time this would not be an issue. However, never compare floats for equality !!

print(v1 == v2)
False
blob = "hello"
match blob:
    case 2 :
        print(2)
    case "hello" :
        print("hello")
    case a,b :
        print("pair")
    case [1,2,3] :
        print("[1,2,3]")
    case _ :
        print("not matched")
hello