2 Variables and basic types
Any changes you make to the code on this page, including your solutions to exercises, are temporary. If you leave or reload the page, all changes will be lost. If you would like to keep your work, copy and paste your code into a separate file or editor where it can be saved permanently.
2.1 Variables
Variables are essential in (almost) any programming language; they are used to label and store values in memory (so that we can use these values later).
In Python, a new variable is created by assignment:
variable_name = some_valueIn the following example, we use three assignments to create variables width, height and area. As the code is being executed line by line, we are allowed to use width and height when we calculate the value assigned to the variable area. Finally, we include all variables (and some text) as arguments in print on the last line.
Using an undefined variable will lead to an error:
Note that variable names (also known as identifiers) must only contain underscores, letters and digits. They cannot start with a digit and they cannot be a keyword (reserved words that have a special meaning).
Variable names are case-sensitive, i.e. area and Area denote two different variables.
A common practice is to use snake_case for variable names, i.e. lower case, words separated by an underscore, for example total_area.
Tip: Always use nouns that describe the purpose of variables so that it is easy for other people (and also for you) to read your code.
Avoid using the names of existing built-in or imported functions and types, since this will make it impossible to use them. For example,
print(max(4, 2, 1, 5, 3)) # Max is a built-in function returning the maximum of the passed argumentswill print 5, the maximum of the numbers passed to the max functions.
However, if we now define our own variable and name it max:
max = 10we will no longer be able to use the built-in max function:
print(max(4, 2, 1, 5, 3))TypeError: 'int' object is not callable
Names of built-in functions and types that beginners often choose as variable names: len, min, max, sum, id, map, range, bool, int, float, str, list, dict, set, tuple.
Note for beginners: If you are not sure if some name is already taken, try to use it or print it; if you get a NameError, the name is not used yet.
We can change the value associated with a variable, for example (note especially the last assignment):
Each value in Python belongs to some type, for example, 1 is an int (for integer), 7.5 is a float (a floating-point number), while "Welcome to the course!" is a str (for string).
We can use type() to get the type of its argument:
2.2 Numbers
Let’s look at the numeric types first. As we have seen above, the int type (class) is used for integer numbers (\(\{\dots, -2, -1, 0, 1, 2, \dots\}\)), while the float type is used for real (also known as floating-point) numbers. (Python also supports complex numbers, but we will not cover them here.)
If a numeric literal (i.e., a fixed number in your program) does not contain a decimal point, Python will use the int type, and if it does, the float type. If you need to use e.g. 0 as a float, use 0.0 (or just 0.)
The most important mathematical operations between numbers (sorted by their precedence) are:
- Parentheses:
() - Exponentiation:
** - Unary
+,- - Multiplication:
*, division:/, floor division://, remainder:% - Addition:
+, subtraction:-
An example of a little bit more complex expression (a combination of literals, variables, operators and functions):
A small, but very important digression: while integers can be stored in the computer memory exactly, this is not always the case for floating-point numbers. Consider the following example (== is used to test if the values on both sides are equal):
Surprising, right? A computer uses limited memory to store floating-point numbers, so only certain numbers can be stored exactly. Others, like 0.1 and 0.2, have to be rounded to the closest number the computer can represent. That tiny rounding error is what makes 0.1 + 0.2 slightly different from 0.3.
Let’s see what is really being stored by printing these numbers with 30 decimal places:
Note that 0.1 + 0.2 does not line up perfectly with 0.3. Do not use == to compare floating-point numbers! Instead, check if they are “close enough”:
For more details on 0.1 + 0.2 vs. 0.3, check out this website.
Exercise: Finish the code in the following cell so that the values or variables x and y are swapped. (This time, try to solve the exercise without searching for a solution.)
You might have tried something like this:
x = y
y = xThis does not work because by the time you reach line 2, x already holds the value of y, so the original value of x is lost. Try using a new variable to store the original value of x before you overwrite it.
x = 0.1
y = 0.2
# Option 1
tmp = x
x = y
y = tmp
# Option 2 (without using a temporary variable)
# x = x + y
# y = x - y
# x = x - y
# Option 3, using tuples (we will learn about them later)
# Python rocks!
# x, y = y, x
print(x, y)2.3 Strings
Single-line string literals are enclosed in either single or double quotes:
A special case of string is the empty string, a string that has 0 characters:
String enclosed in single quotes may contain double quotes and vice versa. Another option how to include quotes is to use escape characters \" or \'.
Tabs and newlines can be inserted with \t resp. \n:
You might wonder how we can include a backslash (e.g. in file paths in Windows) if this character is used in escape characters. You can either use \\ or use a raw string literal as shown in the following example:
Python also supports multi-lined strings, which are enclosed in “triple quotes” (''' or """):
To get the length of a string (i.e., the number of its characters) we use the built-in len function:
Exercise: What is the length of the empty string?
len('')2.3.1 Indexing and slicing
A string is a sequence of characters (letters, digits, punctuation marks, white spaces and control characters such as \n):
| Forward index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
| H | e | l | l | o | , | w | o | r | l | d | ! | ||
| Backward index | -13 | -12 | -11 | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
To get a single character we use the [] operator and specify the index of the character:
Using a non-existing index raises an error:
We can also use negative indexes: -1 refers to the last character, -2 to the second-last one, etc.:
To get a slice (a part or a substring) of a string we use the slice operator ([:]) and specify the start index (inclusive) and the end index (exclusive!) of the slice:
Omitting the start index means “from the beginning”:
Omitting the end index means “until the end”:
We can use negative indexes in slices too:
With slices, using non-existing indexes does not raise an error, but returns the empty string:
Strings are immutable: we are not able to alter an existing string (but we can of course construct a new string and assign it to the same variable). The following code will raise an error:
2.3.2 Concatenation and repetition
We have already seen that we can concatenate strings by using + and repeat a string by multiplying it with an integer:
2.4 Introduction to lists
A list is an ordered collection of values. (Lists are often called arrays in other programming languages.) Note that in Python, the individual elements might be of different types.
Lists can be created by specifying its elements, separated by commas, between square brackets ([ and ]):
The len function (that we have used to return the length of a string) works with lists too, returning the number of the elements:
Similar to strings (which are sequences of characters), we can use the index [] and slice [:] operators to access individual elements and slices:
Question: In the previous cell, can we name the variable list instead of lst?
Unlike strings, which are immutable, lists are mutable so we can change the individual elements:
It is also possible to change all elements in a slice using a single assignment:
The list being assigned to a slice might have more or fewer elements than the slice:
Later we will return to lists and see other (and more ergonomic) ways how to add, insert and remove their elements, but let us already now look at how to append a (single) element to the end of a list:
Looking at the second line, lst.append calls the .append method of the list lst. A method is like a function, but it is tied to a specific object (such as a list or a string) and operates on that object. If the object is mutable, the method can even modify it directly. In this case, lst.append updates lst by adding the argument (i.e., 'E') to the end of the list.
2.5 Splitting strings and joining lists of strings
We will often need to split a string containing multiple items separated by a given separator (e.g. a comma). We can use the string method .split to do that:
Exercise: Change the separator in the previous code to , (without a space). What happens if you execute the cell again? Try also to change the separator to a character (or a string) that does not occur in the given string at all and answer the same question.
When using “,” as the separator (without the space), the elements list is:
['Homer', ' Marge', ' Bart', ' Lisa', ' Maggie']
All elements after the first include a leading space.
If you don’t specify the separator, the words will be split by any type of space (and empty strings discarded):
To concatenate a list of strings and separate them with a given separator, we can use the string method .join (note, that unlike in many other languages, we use the separator as the method’s object and the list as the argument):
Exercise: Strings are immutable, so we cannot change them. But we can always create a new string by using the above-mentioned operators, and assign it to the same variable. Write a program that “replaces” the first character in a given string (say “Python”) with another string (say “Br”).
Solution
string = "Python"
replacement = "Br"
string = replacement + string[1:]
print(string)