## 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 :
4 + 5

Out:
9
In :
15 - 12

Out:
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 == 4

Out:
False
In :
(2 + 6) == 12

Out:
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 :
'Hello'

Out:
'Hello'

In fact, we can add strings:

In :
'ha' + 'ha'

Out:
'haha'

In fact, we can even multiply strings by integers

In :
'ha' * 10

Out:
'hahahahahahahahahaha'

Note that this is the same as

In :
'ha' + 'ha' + 'ha' + 'ha' + 'ha' + 'ha' + 'ha' + 'ha' + 'ha' + 'ha'

Out:
'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 :
memory = 42
memory + 5

Out:
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 :
engsci = 42
engsci + 5

Out:
47

Note that we can reassign values to variables

In :
exam = 98
exam

Out:
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 :
print('hahaha')

hahaha


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

In :
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 :
hahaha = "not hahaha"
print(hahaha)

not hahaha