Numbers, Variables, Strings

REPL

As we cover code together in this workshop, most of the code will be typed at the Python REPL.

REPL stands for Read-Execute-Print Loop.

The REPL:

  1. Reads each character you type
  2. Executes the code you type
  3. Prints out any resulting response, if any
  4. Loops to start over and waits for you to keep typing

To start the REPL, you should have a command/terminal window with your virtual environment activated. In your command/terminal window, type:

$ python

This will start the REPL. You can tell when you are in the REPL because the prompt will change to be >>>.

Exit the REPL with ^Z  <Enter> (ctrl-Z followed by <Enter>) on Windows, or ^D (ctrl-D) on OS X or Linux. Note for OS X, it’s not cmd-D.

Arithmetic

Python has numbers and arithmetic, just like every other programming language.

You can add integers. You can add floating point numbers.

>>> 2 + 2
4
>>> 1.4 + 2.25
3.65

You can subtract, multiply, and divide numbers.

>>> 4 - 2
2
>>> 2 * 3
6
>>> 4 / 2
2.0
>>> 0.5 / 2
0.25

Note that division between two integers in Python 3 returns a float. This is a change from division in Python 2. In Python 2 dividing two integers would return an integer, rounded-down.

>>> 3 / 2
1.5

If you want your integers to round-down like in Python 2, Java, C, and a number of other languages, you can use a double slash:

>>> 3 // 2
1

We can use double asterisks to raise a number to a power. For example, 2 to the 10th power is 1024:

>>> 2 ** 10
1024

Python does not overflow numbers like some other languages do:

>>> 2 ** 1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

Python doesn’t care about spacing between statements on the same line:

>>> 2 + 2
4
>>> 2+2
4

Parentheses work for mathematical operations as well:

>>> (1 + 3) * 4
16

Variables

Just like any other programming language, Python also has variables.

>>> x = 4
>>> x * 3
12

Variables can be used just like any other value:

>>> socks = 2
>>> shirts = 1
>>> shorts = 1
>>> clothing = socks + shirts + shorts
>>> clothing
4

Python has short-hand assignment operators that allow you to do an operation and an assignment at the same time. For example, you can increment or decrement a number like this:

>>> number = 5
>>> number += 7
>>> number
12
>>> number -= 5
>>> number
7

You can use this with most operators. Here’s another example with multiplication and division:

>>> number /= 2
>>> number
3.5
>>> number *= 3
>>> number
10.5

Unlike some other languages, Python does not have a ++ or -- unary operator:

>>> number++
  File "<stdin>", line 1
    number++
           ^
SyntaxError: invalid syntax

Such an operator would not be considered Pythonic because it is less explicit and would provide two ways to do the same thing.

Strings

Python also has strings, which allow you to store text.

>>> "Hello world!"
'Hello world!'

Strings can use double quotes or single quotes, just make sure your quote types line up.

>>> 'Hello!'
'Hello!'

Strings can be joined together through concatenation. String concatenation in Python uses the + operator, the same operator that we use for addition.

>>> "Hello" + "world"
'Helloworld'

We can use variables for strings just like we can for numbers:

>>> name = "Trey"
>>> "Hello my name is " + name
'Hello my name is Trey'

Question: What do you think will happen if we try to concatenate a string and a number?:

>>> "PyCon " + 2016
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly

We get an error; in Python we call this an exception. Python raises an exception to tell us that something is wrong with our code. We’ll cover more about exceptions later in this course.

We can fix the code by converting our number to a string using the str function:

>>> "PyCon " + str(2016)
'PyCon 2016'

In Python, you may not add a number to a string. By converting the number to a string, we can add two strings. Python is now satisfied and concatenates the two strings.

Tip

A function acts a helper and keeps us from retyping code that we use frequently. We can tell it is a function by a term followed by a set of parentheses. Sometimes the parentheses contain a value and sometimes they are empty. We will use many functions in this course.

We can use the type function to check what datatype a variable is.

>>> x = "Guido"
>>> y = 4
>>> type(x)
<class 'str'>
>>> type(y)
<class 'int'>
>>> type(4.0)
<class 'float'>

Another cool function is the len function. We can use len to find the length of strings:

>>> name = "Trey"
>>> len(name)
4

We can also nest function calls (notice the nested sets of parentheses):

>>> "The length of my name is " + str(len(name))
'The length of my name is 4'

String Formatting

String formatting gives us control over what information can be contained in a string and how it looks.

Inserting variables and their values into strings can be awkward:

>>> name = "Trey"
>>> "My name is " + name + " which is " + str(len(name)) + " characters long."
'My name is Trey which is 4 characters long.'

Since Python prefers beautiful and simple code, let’s see if we can make the code above more Pythonic. Python has string formatting that can make this easier. We can put variables inside our strings using the format method:

>>> "My name is {0} which is {1} characters long.".format(name, len(name))
'My name is Trey which is 4 characters long.'

The format method looks for curly braces in our string and replaces them with the arguments we pass within the format parentheses, based on the argument indexes.

So here the first argument, our name, is index 0 and the second argument, the length of our name, is index 1.

We can use these replacement arguments as fields multiple times in our string if we want:

>>> 'I am {0}. The name "{0}" is {1} characters long.'.format(name, len(name))
'I am Trey. The name "Trey" is 4 characters long.'

If all of our arguments are only used once and are presented in the same order that we provide them in our format method, we can leave out the numbers:

>>> "My name is {} which is {} characters long.".format(name, len(name))
'My name is Trey which is 4 characters long.'

Though, that’s a little hard to read and not very Pythonic.

If we want to be more verbose and document our formatted strings more clearly, we can use named arguments in the format function. These named arguments are called “keyword arguments” in Python. We’ll go over these more later.

>>> "My name is {name} which is {length} characters long".format(name=name, length=len(name))
'My name is Trey which is 4 characters long'