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#

Hide code cell source

print(type(3.14))
print(type(True))

Hide code cell output

<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 ?

1,000,000

Hide code cell output

(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 “correct” thing. 1,000,000 s an example of a python tuple. More on that later.

What is the type of 1,000,000 ?

x = 1,000,000
type(x)
tuple

What is the result of executing

type(1,000,000)

1.1.3. Exercise 2 #

Come up with a one or two sentence description of what you think type means in the context of programming.

1.2. Variable assignment#

One of the most powerful features of a programming language is the ability to transform representations. In python, representations are managed through the use of variables. A variable is a name that refers to a value, or data structure, or “representation of” something..

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 _ can appear in a name. It is often used in names with multiple words, such as “my_name” or “airspeed_of_unladen_swallow”.

If you give a variable an illegal name, you get a syntax error. Here are some examples.

76trombones = 'big parade'
  Cell In[14], line 1
    76trombones = 'big parade'
     ^
SyntaxError: invalid decimal literal
more@ = 1000000
SyntaxError: invalid syntax
  Cell In[15], line 1
    more@ = 1000000
          ^
SyntaxError: invalid syntax
class = 'Advanced Theoretical Zymurgy'
  Cell In[16], 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 (note that there is no official standard for the Python language. Version 3.12.3 of CPython has the following keywords.

import keyword

print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']

1.4. Expressions and statements#

An expression is a combination of keywords, 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.

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

1.5. Python operators#

Operators are special symbols that represent computations like addition and multiplication. The values the operator is applied to are called operands. Most versions of python provide the following operators.

+

-

*

/

%

//

**

>

<<

==

!=

>

>=

<=

and

or

not

&

|

~

^

>>

<<

=

+=

-=

*=

/=

%=

//=

**=

&=

=

^=

>>=

<<=

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 3#

Have guess as to what the output should be for these expressions.

False and True

Hide code cell output

False
0 and True

Hide code cell output

0
1 and True

Hide code cell output

True
1 and 0

Hide code cell output

0
1 and 1

Hide code cell output

1
1 and 3

Hide code cell output

3
True and 3

Hide code cell output

3
3 and True

Hide code cell output

True
5*2//3

Hide code cell output

3
5*(2//3)

Hide code cell output

0
(5*2)//3

Hide code cell output

3
3**5**2

Hide code cell output

847288609443
3**(5**2)

Hide code cell output

847288609443
(3**5)**2

Hide code cell output

59049
2 if 1 < 2 else 3

Hide code cell output

2
a = 1
b = 1
a == b

Hide code cell output

True
a is b

Hide code cell output

True
a = 1000000
b = 1000000
a == b

Hide code cell output

True
a is b

Hide code cell output

False
a is not b

Hide code cell output

True
a is (not b)

Hide code cell output

False
x = 4
x^3

Hide code cell output

7
x = 17
x >> 2

Hide code cell output

4

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