2016 September 12,

CS 111: Python as a Calculator

Launch the Python interpreter using the directions of the preceding section. Remember when I compared Python to a calculator? Enter each of the following commands (pressing Return after each one), to see what they do.

3.0 + 6.5

2.2 - 17.2

14.3 * 2.0

14.3 / 2.0

3.0 ** 4.0

Question 02A: What does the ** operator do?

When you do long computations on a hand calculator, it is helpful to store intermediate results in memory. On primitive calculators you put a value into memory using the M+ key, you retrieve a value using the MR key, and so on. On more recent calculators, there are multiple memory slots, called A, B, C, etc., where you can store results.

Python can also store values in memory, using the = operator. Try these commands, in order:

x = 5.7

x

3.0 + x

x

y = x ** 2.0

z = x - y

z

z = x + y

z

z = z + 3.0

z

The x, y, and z in the preceding example are called variables. A variable is a named location in the computer's memory. Once you've assigned a value to a variable using =, you can use the value any time you want by simply invoking the variable's name. You can also assign a new value to a variable at any time.

Question 02B: Does = have the same meaning in Python as it does in a math class? Does the term variable have the same meaning in Python as it does in a math class?

Question 02C: What happens when you try to use a variable's value before you've stored a value in that variable? Test it!

Question 02D: What happens when you compute sin(0)?

Variable names are not limited to single letters. Try these commands:

timmy_smith = 3 ** 2

timmy_smith = timmy_smith + 7.0

celsius = 20

fahrenheit = 1.8 * celsius + 32

You can name your variables however you like — almost. A variable name must consist of upper-case letters, lower-case letters, digits, and underscores. Also, a variable name should begin with a letter.