Chapter 18 Numbers and strings, inputs and outputs

18.1 Numbers

As we saw in lectures, there are three types of numbers: integer, float, and complex. Python used to have integer and long as separate types (as in VBA) but these were merged in Python 3. Floats can be entered in two ways, either the standard decimal notation or using exponential notation. A number in exponential notation is written in the form \(a\)e\(b\) where \(a\) is a decimal number and \(b\) is an integer. Then \(a\)e\(b = a\times 10^b\). For example \[1.234e9 = 1.234\times 10^9 = 1,234,000,000\quad \text{and}\quad 1e-4=0.0001.\]

There is no fixed limit on the size of an integer in Python (although your machine will need enough memory to be able to store it). There are limits to the size (and the precision) of a float, which depend on your machine. On my machine the system reports that the largest value available is 1.7976931348623157e+308, just as for VBA.

If your float is too large, it will be assigned the special value inf. This is short for infinity and indicates that you have gone beyond the range of numbers available to you. If your number is negative then the special value -inf will be assigned instead.

In lectures we saw that we have the standard arithmetic operators

a + b\(\quad\quad\) a - b\(\quad\quad\) a * b\(\quad\quad\) a / b\(\quad\quad\) a ** b

of addition, subtraction, multiplication, division, and exponentiation. There are additional operators available, and we give here the most commonly used examples.

The absolute value of a number x is given by abs(x). The operators

x // y\(\quad\quad\) and \(\quad\quad\) x % y

denote the floored quotient of x by y and the remainder of x divided by y respectively. The floored quotient is the largest integer less than or equal to x/y (although its type in Python will only be an integer if both x and y are).

18.2 Strings

Strings are one of the most basic data types used in Python. As we have seen in the VBA section of the module, a string is simply a sequence of characters. In Python anything in quotes is a string, and as we saw in lectures either single or double quotes can be used. Strings are case sensitive, so "Hello World" is not the same string as "hello world".

There are many methods that can be used to modify a string. We will describe a few of the most basic ones in this section, and we will see some more after we have introduced lists.

Suppose that x is a string. In lectures we saw the methods x.upper() and x.lower(), which converted the string into a version using only upper (respectively lower) case letters. Another variation on this theme is x.title() which converts the first letter of each word into upper case, and the rest into lower case. For example

"rAnDom phRASE".title() = "Random Phrase"

There are a number of other ways in which we can modify a given string. Given three strings x, y, and z, the method x.replace(y,z) replaces every occurrence of the substring y in x by z. For example, if x="Mississippi" then

x.replace("ss","tt") = "Mittittippi".

Sometimes we may end up with a string with some blank spaces at the beginning or end. These will be invisible when we print the string, but can cause problems in our code. If we want to be sure that there are no blank spaces at either the beginning of our string then we can use the strip() command. For example

" Mississippi ".strip() = "Mississippi"

Given two strings x and y, we have seen in lectures that x + y is just the concatenation of the given strings. But we saw in the example in Figures 17.6 and 17.7 that this gives an error if x is a string and y is a number. If we wish to treat a number (or some other object) as a string then we can use the function str which converts the given object into a string. So for example

str(22) = "22"

We also have various ways to examine the structure of our string. The simplest of these is the len function, which determines the number of characters in a given string. We can also count the number of occurrences of a substring y inside a given string x using the method x.count(y). For example, if x = "Mississippi" then

len(x) = 11\(\quad\quad\) x.count("p") = 2 \(\quad\quad\) x.count("ss") = 2

In Python when we label the position of objects we start with 0 instead of 1. This is similar to the default way that arrays are numbered in VBA, but will play an even more fundamental role here. This can be very confusing, so we will need to be careful.

Our first example of this is the position of a character in a string. Given a string x we can write x[i] for the \(i\)th character in the string, starting from \(i=0\). So if x = "cat" then

x[0] = "c"\(\quad\quad\)x[1] = "a"\(\quad\quad\)x[2] = "t"

With this numbering convention we can use x.find(y) to find the first occurrence of the substring y in the string x. The answer will be the position where the first occurrence of y starts in x, or -1 if there is no such y. So if x = "Mississippi" then

x.count("p") = 8\(\quad\quad\)x.count("ss") = 2\(\quad\quad\)x.count("sss") = -1

Similarly we have x.rfind(y) which finds the position of the last occurrence of y inside x.

18.3 Input and output, and fstrings

We have seen in lectures that we can request a user input from the Console using the input command, and we can also return output to the Console using the print command.

The input command has the format input(prompt) where prompt is a string containing the message to be displayed when asking for an input. When this command is used Python will stop and wait for an input from the user before continuing. Whatever is input will then be returned as a string. Normally we will use this in the form

user_input = input("Message requesting input: ")

where the value of the input is stored in the variable user_input.

If we wish to treat the input value as a number then we will need to convert the given string to an integer or float. To do this we use either the int or float functions. Each of these functions takes as an input either a number or a string and converts it to either an integer or a float. Note that these functions can also be used to change the type of a number; when int is applied to a float it returns the integer obtained by removing all of the digits after the decimal place. For example

float(2) = 2.0\(\quad\quad\)int(2.4) = 2\(\quad\quad\)int(2.99) = 2\(\quad\quad\)int(-1.7) = -1.

The simplest way to output the result of your code is to use the print command. This command has the form

print(object(s), sep=separator, end=end)

where object(s) are one or more values to be printed, sep is the way these outputs should be separated, and end is the way that the output should end. The latter two arguments are optional, and default to " " and "\n" respectively. The objects to be printed can be of any type, but will be represented as though they are strings.

Here "\n" is the command that starts a new line; changing this will mean that the next thing to be displayed will be on the same line as what has just been printed. There is a similar command "\t" which inserts a tab.

As an example of the various print formats consider the following code

x = 3.5
y = "John"

print()
print("Something", x, "and", y)
print("Something", x, "and", y, sep=", ")
print("Something", x, "and", y, sep="\n")
print("Something", x, "and", y, sep="\n\t")

which generates the output in Figure 18.1. Note that the first print statement is used to generate a blank line.

Output from the code above

Figure 18.1: Output from the code above

Sometimes it is not convenient to have variables printed using the same separator. Suppose that we have a string called username and an integer variable called phonenum and that we wanted to output something like

username's phone number is phonenum

where username and phonenum were replaced by the relevant values.

There is no gap between the first variable and the 's but there is a gap between is and the second variable, so we cannot do this by changing the value of sep. We could try to combine the different parts into a single object but we have to convert the second variable into a string to do this.

Instead we can use an fstring. Fstrings are a relatively new feature of Python that allow for easier formatting of such outputs. To create an fstring, create a string using single or double quotes as usual, but with an f immediately before the first quote. Inside this string you can include other expressions (which need not be strings) in a pair of braces { }. For example, to generate an output as discussed above we could write

f"{userName}'s phone number is {phonenum}."

Fstrings replace the format command, which was more complicated to use, and have the same optional arguments, which can be included inside the braces after a colon. There are many of these, including {x :.3f} which displays the value of x to three decimal places (where the 3 can be replaced by another number), and {x :,} which automatically adds commas to make large numbers easier to read. For example the following code produces the output in Figure 18.2.

print(f"Numbers like {x}, {y}, and {z}")
print(f"Numbers like {x:.2f}, {y:.2f}, and {z:,}")
Output from the code above

Figure 18.2: Output from the code above