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 be in a command/terminal window. In your command/terminal window, type:

$ python

If you are on a Windows machine, you may need to type py or py -3 instead of python to start the Python REPL or to run a Python program. It will depend upon your individual set up and how Python was installed. This will be true for everywhere in the rest of the class. 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.

We’ll be using the Python REPL as a Python “playground”. As we learn together, we’ll type Python code at the REPL to try out our new skills.

Arithmetic

Python has numbers and arithmetic, just like every other programming language. There are two types of numbers you’ll see frequently in Python: integers and floating point numbers. Integers are used for representing whole numbers; that is, numbers that do not have a decimal point in it. Floating point numbers are used for representing non-integers.

You can add integers. You can add floating point numbers. Integers and floating point numbers can work together.

>>> 2 + 2
4
>>> 1.4 + 2.25
3.65
>>> 3.5 + 4
7.5

You can subtract, multiply, and divide numbers.

>>> 4 - 2
2
>>> 2 * 3
6
>>> 5 / 2
2.5

Note

Division between two integers in Python 3 always returns a float. This is a change from division in Python 2. In Python 2 dividing two integers would return an integer, rounded-down. In Python 3, you can think of the / operator as automatically causing the integers to be cast as floats before the division happens.

>>> 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, also known as floor division:

>>> 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 integer numbers like some other languages do:

>>> 2 ** 1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

Python doesn’t care about spacing between numbers, operators, etc. on the same line:

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

Operator precedence is pretty much what you would expect; multiplication comes before addition. Parentheses work for controlling precedence in mathematical operations as well:

>>> 1 + 3 * 4
13
>>> (1 + 3) * 4
16

Variables

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

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

Note

Python does not require declaration of “types” on variables like some other languages. Python is strongly typed, but it is not statically typed. Python keeps track of value types, but it doesn’t restrict what types each variable name can store.

So you can change variable types throughout your code, but this isn’t usually done:

>>> x = 4
>>> x = "a string"

Python 3.5 introduced a kind of type-hinting or type annotations that can be used with a pre-compiler of sorts to analyze if the code is using the correct types. Type hints do not affect the actual execution of Python - the type hints are ignored by the Python 3 interpreter.

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 of numbers.

>>> "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?:

>>> year = 2020
>>> "PyCon " + year
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(year)
'PyCon 2020'

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 as 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'>

String Length

How do we find out how many characters are in a string? In many languages, we can use a method or attribute to get the length; let’s try that:

>>> name = "Trey"
>>> name.length
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'length'
>>> name.length()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'length'

These typical strategies for getting the length of a string don’t work in Python. Instead, Python has a len function. We can use len to find the length of strings:

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

Instead of asking an object what it’s length is, we pass the object into the len function. You might wonder why we have a len function rather than a method like other languages. This is because multiple kinds of things in Python can have a length; as an example, for lists, which we’ll see in a future session, len() will give us the number of elements:

>>> len([1, 2, 3])
3

The len function acts like an operator and can be used on any object that has a length. In fact, if you create your own objects, you can overload the operation of the len function on your objects to mean whatever makes sense for that object. We’ll see more about operator overloading in a future session.

What would happen if we tried to get the len of the number 4?

>>> len(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()

Numbers don’t have a length in Python, so we get an error. Only things that contain other things have a length.

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 Indexing

Strings can also be indexed using square brackets.

Accessing name[0] gives us the second character in the string and name[1] gives us the second:

>>> name[0]
'T'
>>> name[1]
'r'

Python’s strings are zero-indexed, as are lists and other indexable types.

We’ll see indexing more when we talk about lists later.

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 allows for “string formatting” using f-strings. F-strings are strings that treat text surrounded by { and } specially. Text surrounded by these curly braces will be executed as code and the result of this code will be injected into that place in the string. For example:

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

Python also has string has a format method on strings that works similarly:

>>> "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. I recommend using f-strings instead of this style of string formatting with the format method. The format method has been around for longer and you’ll see more code examples that use it though.

Note

You may also see other some programmers use % for string formatting. This is an even older style of string formatting. If you’re already familiar with the syntax, you’re welcome to use it, but keep in mind that f-strings and the format method are more widely used than formatting with %. They are also more powerful for formatting.

>>> "My name is %s which is %s characters long" % (name, len(name))
'My name is Trey which is 4 characters long'