From 1db063fed5b745d92cd7bd8c917487ca64d0ef77 Mon Sep 17 00:00:00 2001 From: Dave Whipp Date: Wed, 2 Oct 2024 12:47:12 +0300 Subject: [PATCH] Add missing md files --- .../md/appendix-6-question-solutions.md | 2 +- .../part1/chapter-02/md/00-python-basics.md | 64 ++++++++----------- .../chapter-02/md/02-text-and-numbers.md | 52 ++++++++++++++- 3 files changed, 79 insertions(+), 39 deletions(-) diff --git a/source/back-matter/md/appendix-6-question-solutions.md b/source/back-matter/md/appendix-6-question-solutions.md index e5392000..71d4c378 100644 --- a/source/back-matter/md/appendix-6-question-solutions.md +++ b/source/back-matter/md/appendix-6-question-solutions.md @@ -63,7 +63,7 @@ print(first_variable - second_variable) # Fails ### Question 2.5 ```python -'Hot62.6' +ValueError ``` diff --git a/source/part1/chapter-02/md/00-python-basics.md b/source/part1/chapter-02/md/00-python-basics.md index 50c1b1c6..32069685 100644 --- a/source/part1/chapter-02/md/00-python-basics.md +++ b/source/part1/chapter-02/md/00-python-basics.md @@ -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 ``` -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. @@ -296,35 +296,50 @@ print(first_variable - second_variable) ## 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. +```python +forecastHighStr = "77.0" +forecastHighStr +``` + +```python +type(forecastHighStr) +``` + ### 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`. ```python editable=true slideshow={"slide_type": ""} -tempFahrenheitStr = str(tempFahrenheit) +forecastHigh = float(forecastHighStr) ``` -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. ```python editable=true slideshow={"slide_type": ""} -type(tempFahrenheitStr) +type(forecastHigh) ``` ```python editable=true slideshow={"slide_type": ""} -tempFahrenheitStr +forecastHigh ``` -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. +```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) ``` @@ -364,38 +379,15 @@ print(tempFahrenheitInt + temp_celsius) #### 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)`? ```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) ``` - - -### 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. - - -```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 -``` - - -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`. - diff --git a/source/part1/chapter-02/md/02-text-and-numbers.md b/source/part1/chapter-02/md/02-text-and-numbers.md index 0ac1b262..28ae05ee 100644 --- a/source/part1/chapter-02/md/02-text-and-numbers.md +++ b/source/part1/chapter-02/md/02-text-and-numbers.md @@ -86,8 +86,8 @@ To conclude, using the f-string approach is the easiest and most intuitive way t ## 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 the following text, which contains a list of weather station locations in Helsinki that are represented in uppercase text: `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. ```python editable=true slideshow={"slide_type": ""} @@ -167,3 +167,51 @@ print(stations_upper) print(stations_lower) print(stations_capitalize) ``` + + +### 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. + + +```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, out 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. + +```python +first_part = "Our selection includes " + number_of_stations +second_part = " weather stations (" + stations_upper +third_part = "). The first observation is from " + date + "." +``` + +```python editable=true slideshow={"slide_type": ""} +sentences = first_part + second_part + third_part +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. Well done!