Help support the author by donating or purchasing a copy of the book (not available yet)



Chapter 3 - Variables, Floats, Input and Printing

3.1 - Variable Assignment

In the previous chapter we looked at integer expressions. When the interpreter evaluated an expression it simply moved onto the next expression. What if we wanted to store the resulting value? How would we do this? The answer is using variables.

Variables utilize the computers memory to store the data. This might be a good time for some additional reading (it will help you get a better understanding of how computer memory works although it might be a bit advanced for now but feel free to give it a go!) so head over to chapter 24.3.

If you've decided to skip out the extra bit of reading, you can think of main memory or memory (RAM) as cubbyholes with each cubbyhole labeled with some identifier (x for example). When we want to store a value we are essentially telling the computer to put a value Y, into the cubbyhole labeled x. In Python this is called variable assignment. Let's take a look at this in action.

x = 7
y = 5

z = x - y   # The value 2 is now essentially stored in the variable z

These are called assignment statements.

x, y, and z are variables.

The syntax for assignment statements is:

<variable name> = <value you want to store>

For this section you'd be best off by opening up your text editor and a command prompt (terminal window). Create a new file and call it whatever you want but make sure you save it with the .py extension.

Copy the three above assignment statements into the file and save it. Then in your command prompt, run the program (python FILENAME.py). Nothing appears to have happened BUT I'll illustrate below what went on in the background.

The Python interpreter considers each statement in turn from top to bottom, evaluates the expression on the right-hand side, allocates an area of memory for the new variable x and stores the value 7 in the newly allocated memory slot. Well start with the first statement x = 7 and consider what happens in memory:

1) Memory:
    ---------------------------------
    |   |   |   |   |   |   |   |   |   # Expression on right-hand side is evaluated
    ---------------------------------
    
2) Memory:        x
    ---------------------------------
    |   |   |   |   |   |   |   |   |   # Allocate an area of memory for x
    ---------------------------------
    
3) Memory:        x
    ---------------------------------
    |   |   |   | 7 |   |   |   |   |   # Store the value 7 in this area of memory
    ---------------------------------
    
                                        # Move to next statement
                                        # Evaluate right-hand side of expression
4) Memory:        x           y
    ---------------------------------
    |   |   |   | 7 |   |   |   |   |   # Allocate an area of memory for y
    ---------------------------------
 
    
5) Memory:        x           y
    ---------------------------------
    |   |   |   | 7 |   |   | 5 |   |   # Store the value 5 in this area of memory
    ---------------------------------
    
    # Evaluate the right-hand side of next expression (z = x - y)
    # In this case it involves variables so...
    # Look up x in memory and replace x in the expression with the value from memory
    # (z = 7 - y)
    # Look up y in memory and replace y in the expression with the value from memory
    # (z = 7 - 5)
    # Evaluate the expression (z = 2)
    
6) Memory:        x           y   z
    ---------------------------------
    |   |   |   | 7 |   |   | 5 |   |   # Allocate an area of memory for z
    ---------------------------------
 
7) Memory:        x           y   z 
    ---------------------------------
    |   |   |   | 7 |   |   | 5 | 2 |   # Store the value 2 in this area of memory
    ---------------------------------

And so on, executing each assignment statement in turn. However, we could imagine that another statement exists that reads x = 9

In this case we 're-use' (or update) the memory slot as shown below

1) Memory:        x           y   z
    ---------------------------------
    |   |   |   |*7*|   |   | 5 | 2 |   # Memory already allocated for x, re-use it.
    ---------------------------------

2) Memory:        x           y   z
    ---------------------------------
    |   |   |   | 9 |   |   | 5 | 2 |   # The value at memory location x is now 9
    --------------------------------- 

Now we can use this to do some useful things, for example, lets calculate the surface area of earth (approx.).

radius_of_earth = 6371
pi = 3.14
surface_area = 4 * pi * (radius_of_earth ** 2)

IMPORTANT NOTE:

3.2 - Floating-point types

In the previous piece of code about computing the surface area of the earth you may have noticed that I had the statement pi = 3.14

We haven't seen these yet. This is a new type (like integer). They are called floating-point numbers (decimals numbers to the average person). In Python this is the float type.

>>> type(3.14)
<type 'float'>

Floats work pretty much the same as integers (which I'm sure you'd expect). We can perform the same calculations with them. Float expressions also evaluate to float types.

>>> 2.0 // 1.0
2.0
>>> 2.0 * 4.0
8.0

# etc....

I don't know about you, but that division symbol seems strange. Why not just use a single / ?

Well you can! // is for floor division (digits after decimal point are removed). Lets look at how / and // work:

>>> 100 // 3
33
>>> 100 / 3
33.333333333333336

We can see here that when using integers, // rounds down to a whole number (int) but when we use / the result is converted to a float. This is called type casting.

Similarly:

>>> 100.0 // 3.0
33.0
>>> 100.0 / 3.0
33.333333333333336

This is something you need to watch out for when you're doing division. If you use / with integer operands and the resulting value contains digits after the decimal place, you may run into an error if the next part of your code is expecting an integer.

We also have all the other standard operators we've met (float operators in this case).

We can also write negative floats in the expected way:

-3.14

3.3 - Getting user input

Our programs so far haven't really been that interesting and they aren't very beneficial. We can't interact with them when they're running. Most applications these days allow the user to give input (whether that be entering data or clicking options around a screen). In this section we're going to take a look at how you can get input from the user as your program executes.

To do this we use a function, namely input(). We'll get to functions later in this book so don't worry about them, just know that when we type input(), our program will wait for the user to input something at the command prompt.

We can also store the input from the user. This is done as follow:

>>> x = input()
Hello   # User types this
>>> x
'Hello'

By default, input() returns a string (str), thats what the ' ' are around the Hello shows. This is another type which we will get to later but its just textual data (nothing too scary).

Essentially, input() takes in a line from input (we'll get to this later), converts the line into a string and returns it.

We can see that from the above code it might look like our program has frozen (it hasn't). We can add a user friendly prompt that shows when asking the user for input. Lets take a look at a more user friendly program.

>>> name = input("Enter your name: ")
Enter your name: Jake
>>> name
'Jake'

Perfect! We can now have the user input data into our program.

What if we don't want the user to input a string? What if we want an integer or a float?

There are a couple of ways to handle this situation, let's take a look at them:

# Method 1
x = eval(input())

# Method 2
x = int(input())
y = float(input())

Method 1 encapsulates the input() function in another function called eval().

eval() is able to infer the type the user has inputted (if the user inputs 3, then eval() will cast the string '3' to an int. The same happens if the user inputs a float. I don't like this eval() function as it isn't very safe but it works fine here.

I prefer the second method but we will get an error and our program will crash if the user inputs something that can't be cast to an int such as 'hello'.

>>> x = int(input())
Hello
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Hello'
>>>

We get a ValueError. We'll look at different types of errors a little later on. We'll also look at being able to handle these situations (hence why I prefer the second method).

3.4 - The print function

In this section we're going to take another look at that function we came across in the introduction section where we wrote the 'Hello world!' program.

To clarify things for now, you can think of a function as a machine that takes some input, does something with that input, then spits out a value.

In this case, print() takes in something (an argument) and prints it to output (we'll also get to this later).

This, in my opinion, is one of the most useful functions Python has to offer. As we progress through this book and things start to get a little more difficult, I can bet you'll be using this quite a lot.

Let's take a look at how the print() function works:

>>> print("Hello")
Hello
>>> print(3.14)
3.14
>>> print("Hello again")
Hello again

Nothing too complicated! For now though, let's recap on what we've covered so far.

Recap:

Let's look at a program that puts all of this together! (Text editor time)

name = input("What is your name? ")
print("Hi " + name)
number = int(input("What number do you want to be squared? "))
print(number ** 2)

In the line print("Hi " + name), the + joins the string "Hi" and name together to make a single string, this is called string concatenation and we'll come to this later in the strings chapter.

3.5 - Exercises

Important Note:

The solutions to some of these exercises require thinking outside-the-box. Don't expect to arrive at a solution immediately!

Question 1

Assume a population of rabbits doubles every 3 months. Further assume the current population is 11 rabbits i.e. number_of_rabbits = 11

Write a Python program to calculate the rabbit population after 2 years and print the result to the terminal.

Question 2

Extend the above program to allow the user to input the number of rabbits and the time period after which you want to know the rabbit population e.g. 4 years

Question 3

Assume the user is going to input 2 numbers, x and y for example. Write a Python program that will swap the numbers stored in these variables e.g.

# Assume the user has input these
x = 3
y = 11
# Your code to swap here
# After, the variables should be:
# x = 11
# y = 3

Question 4

The goal of this task is to derive a single assignment statement for the following sequences such that, if the variable x has the first value in a sequence, then x will have the next value in the sequence after the assignment statement is executed. And if the assignment statement were executed repeatedly, then x would cycle through all of the values in the sequence.

# EXAMPLE

# Sequence:
# 0 1 2 3 4 5 6 7 ...

#SOLUTION
x = x + 1

Sequence 1:

0 2 4 6 8 10 12 ...

Sequence 2:

0 -1 -2 -3 -4 -5 -6 ...

Sequence 3:

6 -6 6 -6 6 -6.....

Sequence 4 (Difficult):

0 3 6 0 3 6 0 3 6 0 3 6...


Help support the author by donating or purchasing a copy of the book (not available yet)



Previous Chapter - Next Chapter