Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The Python Workshop

You're reading from   The Python Workshop Learn to code in Python and kickstart your career in software development or data science

Arrow left icon
Product type Paperback
Published in Nov 2019
Publisher Packt
ISBN-13 9781839218859
Length 608 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (6):
Arrow left icon
Andrew Bird Andrew Bird
Author Profile Icon Andrew Bird
Andrew Bird
Graham Lee Graham Lee
Author Profile Icon Graham Lee
Graham Lee
Corey Wade Corey Wade
Author Profile Icon Corey Wade
Corey Wade
Dr. Lau Cher Han Dr. Lau Cher Han
Author Profile Icon Dr. Lau Cher Han
Dr. Lau Cher Han
Olivier Pons Olivier Pons
Author Profile Icon Olivier Pons
Olivier Pons
Mario Corchero Jiménez Mario Corchero Jiménez
Author Profile Icon Mario Corchero Jiménez
Mario Corchero Jiménez
+2 more Show less
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Vital Python – Math, Strings, Conditionals, and Loops 2. Python Structures FREE CHAPTER 3. Executing Python – Programs, Algorithms, and Functions 4. Extending Python, Files, Errors, and Graphs 5. Constructing Python – Classes and Methods 6. The Standard Library 7. Becoming Pythonic 8. Software Development 9. Practical Python – Advanced Topics 10. Data Analytics with pandas and NumPy 11. Machine Learning Appendix

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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime