## Using Python as a calculator¶

The following are examples of the kinds of Python expressions that we can use. The In [] lines are the expressions, and the Out [] lines are the values of the expressions.

Simple arithmetic:

In [1]:
4 + 5

Out[1]:
9
In [2]:
15 - 12

Out[2]:
3

Boolean expressions are expressions whose value is either True or False. Note the double equals sign (a single equals sign means something else -- see elsewhere in the lecture.) These are in most ways just like expressions whose values are integers, except the result True/False instead of things like 3.14, 10, or 42.

In [3]:
3 == 4

Out[3]:
False
In [4]:
(2 + 6) == 12

Out[4]:
False

## Going beyond just numbers¶

So far, we have only seen numbers (integers) and boolean values (True and False) as values. Strings (i.e., text) is another possible value.

In [5]:
'Hello'

Out[5]:
'Hello'

In fact, we can add strings:

In [6]:
'ha' + 'ha'

Out[6]:
'haha'

In fact, we can even multiply strings by integers

In [7]:
'ha' * 10

Out[7]:
'hahahahahahahahahaha'

Note that this is the same as

In [8]:
'ha' + 'ha' + 'ha' + 'ha' + 'ha' + 'ha' + 'ha' + 'ha' + 'ha' + 'ha'

Out[8]:
'hahahahahahahahahaha'

So it makes sense that 'ha' * 10 is 'ha' added to itself 9 times.

## Variables¶

Variables are used to store values in memory. They are not really like variables in math -- they are more like labelled boxes where you store values.

In [9]:
memory = 42
memory + 5

Out[9]:
47

First, we store 42 in the variable memory (an assignment statement like the one on line above means "take the value on the right of the =, and store it in the variable on the left of the =")

Note that there's nothing special about calling the variable memory. We could as well have done the following:

In [10]:
engsci = 42
engsci + 5

Out[10]:
47

Note that we can reassign values to variables

In [11]:
exam = 98
exam

Out[11]:
83

## Printing output to screen¶

In order for our program to print something (rather than for a single line), we need to use the print function. For example:

In [12]:
print('hahaha')

hahaha


Note that hahaha had to be in quotes. If it hadn't been, we would get an error:

In [13]:
print(hahaha)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-9216464d7607> in <module>()
----> 1 print(hahaha)

NameError: name 'hahaha' is not defined

What happened here? If hahaha is not in quotes, Python assumes that hahaha is a variable. But we haven't assigned any value to the variable hahaha, is Python reasonably says that it's undefined.

We could, of course, assign a value to the variable hahaha:

In [14]:
hahaha = "not hahaha"
print(hahaha)

not hahaha