Skip to content

Commit

Permalink
Merge pull request #178 from Python-GIS-book/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
davewhipp authored Oct 13, 2024
2 parents 111a6df + f540c73 commit 81686fa
Show file tree
Hide file tree
Showing 14 changed files with 664 additions and 500 deletions.
2 changes: 1 addition & 1 deletion source/back-matter/md/appendix-6-question-solutions.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ print(first_variable - second_variable) # Fails
### Question 2.5

```python
'Hot62.6'
ValueError
```
<!-- #endregion -->

Expand Down
2 changes: 1 addition & 1 deletion source/back-matter/nb/appendix-6-question-solutions.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@
"### Question 2.5\n",
"\n",
"```python\n",
"'Hot62.6'\n",
"ValueError\n",
"```"
]
},
Expand Down
64 changes: 28 additions & 36 deletions source/part1/chapter-02/md/00-python-basics.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,15 +261,15 @@ weatherForecast = "Hot"
type(weatherForecast)
```

Let's also check the type of `tempFahrenheit`. What happens if you try to combine `tempFahrenheit` and `weatherForecast` in a single math equation such as `tempFahrenheit = tempFahrenheit + 5.0 * weatherForecast`?
Let's also check the type of `tempFahrenheit`. What happens if you try to combine `tempFahrenheit` and `weatherForecast` in a single math equation such as `tempFahrenheit = tempFahrenheit + weatherForecast`?

```python deletable=true editable=true jupyter={"outputs_hidden": false} tags=["raises-exception"]
type(tempFahrenheit)
tempFahrenheit = tempFahrenheit + 5.0 * weatherForecast
tempFahrenheit = tempFahrenheit + weatherForecast
```

<!-- #region deletable=true editable=true -->
In this case we get at `TypeError` because we are trying to execute a math operation with data types that are not compatible. There is no way in Python to multpily decimal values with a character string.
In this case we get at `TypeError` because we are trying to execute a math operation with data types that are not compatible. It is not possible to add a number directly to a character string in Python. In order for addition to work, the data types need to be compatible with one another.
<!-- #endregion -->

<!-- #region deletable=true editable=true slideshow={"slide_type": ""} tags=["question"] -->
Expand All @@ -296,35 +296,50 @@ print(first_variable - second_variable)
<!-- #region editable=true slideshow={"slide_type": ""} -->
## Making different data types work together

In the previous section we saw that not all Python data types are directly compatible with others, which may result in a `TypeError` being raised. This means that (1) it is important to be aware of the data type of variables and (2) some additional steps may be needed to make different data compatible. In the example in the previous section we had `tempFahrenheit` (type `float`) and `weatherForecast` (type `str`) that were not compatible. How can we address this issue if we would like to work with those data together?
In the previous section we saw that not all Python data types are directly compatible with others, which may result in a `TypeError` being raised. This means that (1) it is important to be aware of the data type of variables and (2) some additional steps may be needed to make different data compatible. Let's consider an example where we try to combine `tempFahrenheit` (type `float`) with another temperature value. In this case, the other temperature is stored in a character string `forecastHighStr` (type `str`) with a value of `"77.0"`. As we know, data of type `float` and type `str` are not compatible for math operations. Let's start by defining `forecastHighStr` and then see how we can we address this issue to make these data work together.
<!-- #endregion -->

```python
forecastHighStr = "77.0"
forecastHighStr
```

```python
type(forecastHighStr)
```

<!-- #region editable=true slideshow={"slide_type": ""} -->
### Converting data from one type to another

It is not the case that things like the `tempFahrenheit` and `weatherForecast` cannot be combined at all, but in order to combine a character string with a number we need to perform a *{term}`type conversion`* to make them compatible. Let's convert `tempFahrenheit` to a character string using the `str()` function. We can store the converted variable as `tempFahrenheitStr`.
It is not the case that things like the `tempFahrenheit` and `forecastHighStr` cannot be combined at all, but in order to combine a character string with a number we need to perform a *{term}`type conversion`* to make them compatible. Let's convert `forecastHighStr` to a floating point number using the `float()` function. We can store the converted variable as `forecastHigh`.
<!-- #endregion -->

```python editable=true slideshow={"slide_type": ""}
tempFahrenheitStr = str(tempFahrenheit)
forecastHigh = float(forecastHighStr)
```

<!-- #region editable=true slideshow={"slide_type": ""} -->
We can confirm the type has changed by checking the type of `tempFahrenheitStr` or by checking the output of a code cell with the variable.
We can confirm the type has changed by checking the type of `forecastHigh` or by checking the output of a code cell with the variable.
<!-- #endregion -->

```python editable=true slideshow={"slide_type": ""}
type(tempFahrenheitStr)
type(forecastHigh)
```

```python editable=true slideshow={"slide_type": ""}
tempFahrenheitStr
forecastHigh
```

<!-- #region editable=true slideshow={"slide_type": ""} -->
As you can see, `str()` converts a numerical value into a character string with the same numbers as before. Similar to using `str()` to convert numbers to character strings, `int()` can be used to convert strings or floating point numbers to integers, and `float()` can be used to convert strings or integers to floating point numbers. For example, we could convert `tempFahrenheit` to an integer as follows.
As you can see, `float()` converts a character string to a decimal value representing the number stored in the string. As a result, we can now easily calculate the difference between the forecast high temperature `forecastHigh` and `tempFahrenheit` as the data are now compatible.
<!-- #endregion -->

```python
forecastHigh - tempFahrenheit
```

`float()` can be used to convert strings or integers to floating point numbers, however it is important to note that `float()` can only convert strings that represent numerical values. For example, `float("Cold")` will raise a `ValueError` because `"Cold"` cannot be converted to a number directly. Similar to `float()`, `str()` can convert numbers to character strings, and `int()` can be used to convert strings or floating point numbers to integers. For example, we could convert `tempFahrenheit` to an integer as follows.

```python editable=true slideshow={"slide_type": ""}
tempFahrenheitInt = int(tempFahrenheit)
```
Expand Down Expand Up @@ -364,38 +379,15 @@ print(tempFahrenheitInt + temp_celsius)
<!-- #region editable=true slideshow={"slide_type": ""} tags=["question"] -->
#### Question 2.5

What output would you expect to see when you execute `print(weatherForecast + tempFahrenheitStr)`?
What output would you expect to see when you execute `float(weatherForecast)`?
<!-- #endregion -->

```python editable=true slideshow={"slide_type": ""} tags=["remove_cell"]
# Use this cell to enter your solution.
```

```python editable=true slideshow={"slide_type": ""} tags=["remove_book_cell", "hide-cell"]
```python editable=true slideshow={"slide_type": ""} tags=["remove_book_cell", "hide-cell", "raises-exception"]
# Solution

print(weatherForecast + tempFahrenheitStr)
float(weatherForecast)
```

<!-- #region editable=true slideshow={"slide_type": ""} -->
### Combining text and numbers

Although most mathematical operations are applied to numerical values, a common way to combine character strings is using the addition operator `+`. Let's create a text string in the variable `temp_and_forecast` that is the combination of the `tempFahrenheit` and `weatherForecast` variables. Once we define `temp_and_forecast`, we can print it to the screen to see the result.
<!-- #endregion -->

```python editable=true slideshow={"slide_type": ""}
temp_and_forecast = (
"The current temperature is "
+ str(tempFahrenheit)
+ " and the forecast for today is "
+ weatherForecast
)
```

```python editable=true slideshow={"slide_type": ""}
temp_and_forecast
```

<!-- #region editable=true slideshow={"slide_type": ""} -->
Note that here we are converting `tempFahrenheit` to a character string using the `str()` function within the assignment to the variable `temp_and_forecast`. Alternatively, we could have simply combined `tempFahrenheitStr` and `weatherForecast`.
<!-- #endregion -->
66 changes: 64 additions & 2 deletions source/part1/chapter-02/md/02-text-and-numbers.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,15 @@ To conclude, using the f-string approach is the easiest and most intuitive way t
<!-- #region editable=true slideshow={"slide_type": ""} -->
## Manipulating character strings

Here we demonstrate some of the most useful string manipulation techniques, such as splitting strings based on a given character, replacing characters with new ones, slicing strings, etc.
The aim is to produce a list of weather station locations in Helsinki that are represented in uppercase text (i.e., `KUMPULA, KAISANIEMI, HARMAJA`). The text that we will begin working with is below:
Here we demonstrate some of the most useful string manipulation techniques, such as splitting strings based on a given character, replacing characters with new ones, slicing strings, concatenating strings, etc.
The aim is to produce two lines of text that contain a list of weather station locations in Helsinki in uppercase:

```
Our selection includes 3 weather stations (KUMPULA, KAISANIEMI, HARMAJA).
The first observation is from 01/01/1882.
```

The text that we will begin working with is below.
<!-- #endregion -->

```python editable=true slideshow={"slide_type": ""}
Expand Down Expand Up @@ -167,3 +174,58 @@ print(stations_upper)
print(stations_lower)
print(stations_capitalize)
```

<!-- #region editable=true slideshow={"slide_type": ""} -->
### Concatenating strings

Although most mathematical operations are applied to numerical values, a common way to combine (or concatenate) character strings is using the addition operator `+`. Let's try to complete our task of creating our target sentences by concatenating three separate character strings into one. As a reminder, the text we are aiming to produce reads:

```
Our selection includes 3 weather stations (KUMPULA, KAISANIEMI, HARMAJA).
The first observation is from 01/01/1882.
```

We can first define some values we will need to create the target text.
<!-- #endregion -->

```python
first_day = "1"
first_month = "1"
first_year = "1882"
number_of_stations = "3"
```

Note that if we were working with numerical values we would need to convert them to character strings using the `str()` function. Luckily, we already have character strings, so we can proceed with creating our sentences.

As you may have noticed, our date should have the day and month represented with two characters (i.e., with a leading zero). We could use the `+` operator to add together `"0"` and our day or month value (e.g., `first_day = "0" + first_day`), however adding leading zeros to text is a common operation for ensuring consistent widths of text in data files, for example. Because of this, we can use the `.zfill()` function for strings to add leading zeros to our day and month values, as shown below.

```python
first_day = first_day.zfill(2)
first_month = first_month.zfill(2)
```

```python
first_day
```

As you can see, the `.zfill()` function adds leading zeros before a number up to the number of characters specified when using it. In our case, we specified we want `2` characters, so one leading zero was added to our character strings. At this point, we can create a date string we can use for creating our sentences.

```python
date = first_day + "/" + first_month + "/" + first_year
date
```

Looks good. Now we can define the remaining pieces needed to create our sentences and concatenate them to form the target sentences. Note that we want to have the second sentence on a separate line, which means we will need to insert a special character to split the text onto two lines. For this, we can use the newline character `\n`, which indicates the end of a line. Text that follows the newline character will appear on a separate line. In our example, we can simply include `\n` in the character string where we would like the line to be split.

```python
first_part = "Our selection includes " + number_of_stations
second_part = " weather stations (" + stations_upper + ").\n"
third_part = "The first observation is from " + date + "."
```

```python editable=true slideshow={"slide_type": ""}
sentences = first_part + second_part + third_part
print(sentences)
```

Nice! By simply breaking down the sentence into smaller character string segments we were able to use the `+` operator to create two sentences containing several numerical values combined in various ways. It is important to pay attention to spaces and characters such as parentheses, if you have them in your string, but otherwise string concatenation is an easy way to build more complex strings from smaller pieces.
Loading

0 comments on commit 81686fa

Please sign in to comment.