Book Image

The Python Workshop

By : Olivier Pons, Andrew Bird, Dr. Lau Cher Han, Mario Corchero Jiménez, Graham Lee, Corey Wade
Book Image

The Python Workshop

By: Olivier Pons, Andrew Bird, Dr. Lau Cher Han, Mario Corchero Jiménez, Graham Lee, Corey Wade

Overview of this book

Have you always wanted to learn Python, but never quite known how to start? More applications than we realize are being developed using Python because it is easy to learn, read, and write. You can now start learning the language quickly and effectively with the help of this interactive tutorial. The Python Workshop starts by showing you how to correctly apply Python syntax to write simple programs, and how to use appropriate Python structures to store and retrieve data. You'll see how to handle files, deal with errors, and use classes and methods to write concise, reusable, and efficient code. As you advance, you'll understand how to use the standard library, debug code to troubleshoot problems, and write unit tests to validate application behavior. You'll gain insights into using the pandas and NumPy libraries for analyzing data, and the graphical libraries of Matplotlib and Seaborn to create impactful data visualizations. By focusing on entry-level data science, you'll build your practical Python skills in a way that mirrors real-world development. Finally, you'll discover the key steps in building and using simple machine learning algorithms. By the end of this Python book, you'll have the knowledge, skills and confidence to creatively tackle your own ambitious projects with Python.
Table of Contents (13 chapters)

String Interpolation

When writing strings, you may want to include variables in the output. String interpolation includes the variable names as placeholders within the string. There are two standard methods for achieving string interpolation: comma separators and format.

Comma Separators

Variables may be interpolated into strings using commas to separate clauses. It's similar to the + operator, except it adds spacing for you.

You can have a look at an example here, where we add Ciao within a print statement:

italian_greeting = 'Ciao'
print('Should we greet people with', italian_greeting, 'in North Beach?')

You should get the following output:

Should we greet people with Ciao in North Beach?

Format

With format, as with commas, Python types, ints, floats, and so on, are converted into strings upon execution. The format is accessed using brackets and dot notation:

owner = 'Lawrence Ferlinghetti'
age = 100
print('The founder of City Lights Bookstore, {}, is now {} years old.'.format(owner, age))

You should get the following output:

The founder of City Lights Bookstore, Lawrence Ferlinghetti, is now 100 years old.

The format works as follows: First, define your variables. Next, in the given string, use {} in place of each variable. At the end of the string, add a dot (.) followed by the format keyword. Then, in parentheses, list each variable in the desired order of appearance. In the next section, you will look at the built-in string functions available to a Python developer.

The len() Function

There are many built-in functions that are particularly useful for strings. One such function is len(), which is short for length. The len() function determines the number of characters in a given string.

Note that the len() function will also count any blank spaces in a given string.

You'll use the arabic_greeting variable used in Exercise 8, Displaying Strings:

len(arabic_greeting)

You should get the following output:

16

Note

When entering variables in Jupyter notebooks, you can use tab completion. After you type in a letter or two, you can press the Tab key. Python then displays all valid continuations that will complete your expression. If done correctly, you should see your variable listed. Then you can highlight the variable and press Enter. Using tab completion will limit errors.

String Methods

All Python types, including strings, have their own methods. These methods generally provide shortcuts for implementing useful tasks. Methods in Python, as in many other languages, are accessed via dot notation.

You can use a new variable, name, to access a variety of methods. You can see all methods by pressing the Tab button after the variable name and a dot.

Exercise 10: String Methods

In this exercise, you will learn how to implement string methods.

  1. Set a new variable, called name, to any name that you like:
    name = 'Corey'

    Note

    Access string methods by pressing the Tab button after the variable name and dot (.), as demonstrated in the following screenshot:

    Figure 1.10: Setting a variable name via the dropdown menu

    Figure 1.10: Setting a variable name via the dropdown menu

    You can scroll down the list to obtain all available string methods.

  2. Now, convert the name into lowercase letters using the lower() function:
    name.lower()

    You should get the following output:

    'corey'
  3. Now, capitalize the name using the capitalize() function:
    name.capitalize()

    You should get the following output:

    'Corey'
  4. Convert the name into uppercase letters using upper():
    name.upper()

    You should get the following output:

    'COREY'
  5. Finally, count the number of o instances in the word 'Corey':
    name.count('o')

    You should get the following output:

    1

In this exercise, you have learned about a variety of string methods, including lower(), capitalize(), upper(), and count().

Methods may only be applied to their representative types. For instance, the lower() method only works on strings, not integers or floats. By contrast, built-in functions such as len() and print() can be applied to a variety of types.

Note

Methods do not change the original variable unless we explicitly reassign the variable. So, the name has not been changed, despite the methods that we have applied.

Casting

It's common for numbers to be expressed as strings when dealing with input and output. Note that '5' and 5 are different types. We can easily convert between numbers and strings using the appropriate type keywords. In the following exercise, we are going to be using types and casting to understand the concepts much better.

Exercise 11: Types and Casting

In this exercise, you will learn how types and casting work together:

  1. Open a new Jupyter Notebook.
  2. Determine the type of '5':
    type('5')

    You should get the following output:

    str
  3. Now, add '5' and '7':
    '5' + '7'

    You should get the following output:

    '57'

    The answer is not 12 because, here, 5 and 7 are of type string, not of type int. Recall that the + operator concatenates strings. If we want to add 5 and 7, we must convert them first.

  4. Convert the '5' string to an int using the code mentioned in the following code snippet:
    int('5')

    You should get the following output:

    5

    Now 5 is a number, so it can be combined with other numbers via standard mathematical operations.

  5. Add '5' and '7' by converting them to int first:
    int('5') + int('7')

    You should get the following output:

Figure 1.11: Output after adding two integers converted from a string

Figure 1.11: Output after adding two integers converted from a string

In this exercise, you have learned several ways in which strings work with casting.

The input() Function

The input() function is a built-in function that allows user input. It's a little different than what we have seen so far. Let's see how it works in action.

Exercise 12: The input() Function

In this exercise, you will utilize the input() function to obtain information from the user:

  1. Open a new Jupyter Notebook.
  2. Ask a user for their name. Respond with an appropriate greeting:
    # Choose a question to ask
    print('What is your name?')

    You should get the following output:

    Figure 1.12: The user is prompted to answer a question

    Figure 1.12: The user is prompted to answer a question

  3. Now, set a variable that will be equal to the input() function, as mentioned in the following code snippet:
    name = input()

    You should get the following output:

    Figure 1.13: The user may type anything into the provided space

    Figure 1.13: The user may type anything into the provided space

  4. Finally, select an appropriate output:
    print('Hello, ' + name + '.')

    You should get the following output:

Figure 1.14: After pressing Enter, the full sequence is displayed

Figure 1.14: After pressing Enter, the full sequence is displayed

Note

input() can be finicky in Jupyter Notebooks. If an error arises when entering the code, try restarting the kernel. Restarting the kernel will erase the current memory and start each cell afresh. This is advisable if the notebook stalls.

In this exercise, you have learned how the input() function works.

Activity 3: Using the input() Function to Rate Your Day

In this activity, you need to create an input type where you ask the user to rate their day on a scale of 1 to 10.

Using the input() function, you will prompt a user for input and respond with a comment that includes the input. In this activity, you will print a message to the user asking for a number. Then, you will assign the number to a variable and use that variable in a second message that you display to the user.

The steps are as follows:

  1. Open a new Jupyter Notebook.
  2. Display a question prompting the user to rate their day on a number scale of 1 to 10.
  3. Save the user's input as a variable.
  4. Display a statement to the user that includes the number.

    Note

    The solution for this activity can be found via this link.