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! 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
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
The Python Workshop
The Python Workshop

The Python Workshop: Learn to code in Python and kickstart your career in software development or data science

Arrow left icon
Profile Icon Bird Profile Icon Pons Profile Icon Dr. Lau Cher Han Profile Icon Mario Corchero Jiménez Profile Icon Graham Lee Profile Icon Wade +2 more Show less
Arrow right icon
€47.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (36 Ratings)
Paperback Nov 2019 608 pages 1st Edition
eBook
€33.99 €37.99
Paperback
€47.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Bird Profile Icon Pons Profile Icon Dr. Lau Cher Han Profile Icon Mario Corchero Jiménez Profile Icon Graham Lee Profile Icon Wade +2 more Show less
Arrow right icon
€47.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (36 Ratings)
Paperback Nov 2019 608 pages 1st Edition
eBook
€33.99 €37.99
Paperback
€47.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€33.99 €37.99
Paperback
€47.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

The Python Workshop

1. Vital Python – Math, Strings, Conditionals, and Loops

Overview

By the end of this chapter, you will be able to simplify mathematical expressions with the order of operations using integers and floats; assign variables and change Python types to display and retrieve user information; apply global functions including len(), print(), and input(); manipulate strings using indexing, slicing, string concatenation, and string methods; apply Booleans and nested conditionals to solve problems with multiple pathways; utilize 'for loops' and 'while loops' to iterate over strings and repeat mathematical operations and create new programs by combining math, strings, conditionals, and loops.

This chapter covers the fundamentals of the Python language.

Introduction

Welcome to the Python Workshop. This book is for anyone new to the Python programming language. Our objective is to teach you Python so that you can solve real-world problems as a Python developer and data scientist.

This book will combine theory, examples, exercises, questions, and activities for all core concepts; so that you can learn to use Python best practices to solve real-world problems. The exercises and activities have been chosen specifically to help you review the concepts covered and extend your learning. The best way to learn Python is to solve problems on your own.

The material (in this book) is targeted at beginners but will be equally as beneficial to experienced developers who are not yet familiar with Python. We are not teaching computer science per se, but rather Python, the most beautiful and powerful coding language in the world. If you have never studied computer science, you will learn the most important concepts here, and if you have studied computer science, you will discover tools and tricks for Python that you have never seen before.

Python has become the most popular programming language in the world due to its simple syntax, extensive range, and dominance in the field of machine learning. In this book, you will become fluent in Python syntax, and you will take significant steps toward producing Pythonic code. You will gain experience in Python development, data science, and machine learning.

Many introductory Python books provide full introductions to computer science. Learning computer science with Python is an excellent way to start, but it is not the method of this book. Units on software development and data science are rarely covered in such books. They may be touched upon, but here, they represent 40% of our book.

By contrast, many books on software development and data science are not designed for beginners. If they are, the Python fundamentals that they teach are usually summarized in one brief unit. This book devotes considerable space to Python fundamentals and essentials. Beginners are not only welcome; they are guided every step of the way.

In addition to the unique focus on Python fundamentals and essentials, the fact that the content is written by seasoned educators, data scientists, and developers makes this Python book more than just a text or reference.

Python is not the language of tomorrow; Python is the language of today. By learning Python, you will become empowered as a developer, and you will gain a significant edge over the competition. The journey will be fun, compelling, challenging, and ultimately, rewarding.

Vital Python

In this chapter, we present vital Python concepts, the core elements that everyone needs to know before starting to code. You cover a breadth of topics with a focus on math, strings, conditionals, and loops. By the end of this chapter, you will have a strong foundation in Python, and you will be able to write significant Python programs as you continue with the rest of this book.

You will start with a very famous developer example; that is, Python as a calculator. In addition to the standard operations of addition, subtraction, multiplication, division, and exponentiation, you will learn integer division and the modulus operator. By using only basic Python, you can outperform most calculators on the market.

Next, you'll learn about variables. Python is dynamically typed, meaning that variable types are unknown before the code runs. Python variables do not require special initialization. Our first variables will be integers, floats, and strings. You will identify and convert between types.

Next, in order to work with strings, you will utilize string methods, in addition to indexing, slicing, and string concatenation. You'll also use built-in functions such as print() and input() to communicate with the user.

Moving ahead, you'll encounter Booleans, true or false Python types, that precede conditionals, statements with if clauses that lead to branching. Booleans and conditionals allow us to write more complex programs by taking a greater number of possibilities into account.

Finally, you close the chapter with loops that allows us to repeat operations. In particular, we apply while loops and for loops, utilizing break and continue.

For true beginners, this introductory chapter will get you up to speed with basic programming concepts. If you are new to Python, you will see why the Python language is so clear, powerful, and valuable. By the end of this chapter, you will be comfortable running Python basics on their own, and you will be prepared to tackle more of the advanced concepts ahead.

Let's start coding in Python.

Numbers: Operations, Types, and Variables

In the preface, we installed Anaconda, which comes along with Python 3.7 and the Jupyter Notebook. It's time to open a Jupyter Notebook and begin our Pythonic journey.

To Open a Jupyter Notebook

To begin with this book, you need to make sure that you have a Jupyter Notebook open. Here are the steps.

  1. Locate and open your Anaconda Navigator.
  2. Search for Jupyter Notebook in Anaconda Navigator and click on it.
  3. A new window should open in the web browser of your choice.
Figure 1.1: The Jupyter Notebook interface

Figure 1.1: The Jupyter Notebook interface

Note

If you are having trouble, it may mean that your Jupyter Notebook is not set up properly. Go back to the preface or see https://jupyter-notebook.readthedocs.io/en/stable/troubleshooting.html for a troubleshooting guide.

Python as a Calculator

Now that you are all set up, you can begin with the very first interesting topic. Python is an incredibly powerful calculator. By leveraging the math library, numpy, and scipy, Python typically outperforms pre-programmed calculators. In later chapters, you will learn how to use the numpy and scipy libraries. For now, we'll introduce the calculator tools that most people use daily.

Addition, subtraction, multiplication, division, and exponentiation are core operations. In computer science, the modulus operator and integer division are equally essential as well, so we'll cover them here.

The modulus operator is the remainder in mathematical division. Modular arithmetic is also called clock arithmetic. For instance, in mod5 which is a modulus of 5, we count 0,1,2,3,4,0,1,2,3,4,0,1... This goes in a circle, like the hands on a clock.

The difference between division and integer division depends on the language. When dividing the integer 9 by the integer 4, some languages return 2; others return 2.25. In your case, Python will return 2.25.

There are many advantages to using Python as your calculator of choice. The first is that you are not limited to using programs that others have written. You can write a program to determine the greatest common divisor or the Euclidean distance between two points.

Other advantages include reliability, precision, and speed. Python generally prints out more decimal places than most calculators, and it always does what you command it to do.

We'll cover a small sample of what Python can calculate. Complex numbers are previewed as a Python type. Great math libraries such as Turtle, which creates polygons and circles with ease, may be explored in your own time and are mentioned in Chapter 6, The Standard Library. The depth of math required for data analysis and machine learning starts with the foundations laid here.

Note

In this book, copy everything that follows >>> in a cell in your Jupyter Notebook; that is, you exclude >>>. To run code, make sure the cell is highlighted, then press Shift + Enter. You may also press the Run button at the top of the Notebook, but this takes more time. Start thinking like a developer and use keystrokes instead.

Standard Math Operations

You can have a look at the standard math operations and their symbols that we will be using while coding. The following table covers these:

Figure 1.2: Standard math operations

Figure 1.2: Standard math operations

Note

The ** symbol is not universally for exponentiation, but it should be. By definition, exponentiation is repeated multiplication. Using the * symbol twice is representative of repeated multiplication. It's terse, fast, and efficient. Other programming languages require functions to exponentiate.

Python provides an optional method from the math library, math.pow(), but ** is cleaner and easier to use.

Basic Math Operations

We can perform addition on two numbers using the + operator. The following example shows the addition of 5 and 2:

  1. Here, we are using the addition operator, + in the code:
    5 + 2

    You should get the following output:

    7

    We can perform addition on two numbers using the + operator. The following example shows the subtraction of 5 and 2.

  2. Using the subtraction operator in the code, we can perform subtraction on two numbers:
    5 - 2 

    You should get the following output:

    3

    The following example shows the multiplication of 5 by 2.

  3. Using the * multiplication operator to multiply the two numbers is done as follows:
    5 * 2 

    You should get the following output:

    10
  4. Now, use the / division operator and observe the output:
    5 / 2

    You should get the following output:

    2.5

    When dividing two numbers, Python will always return a decimal.

  5. Now the same division can be done using the // operator, which is called integer division. Observe the change in the output:
    5 // 2

    You should get the following output:

    2

    The result of the integer division is the integer before the decimal point.

  6. Now, using the ** exponential operator, we can perform exponentiation:
    5 ** 2

    You should get the following output:

    25

    The next example shows how to use the modulus operator.

  7. Finally, use the modulus operator in the code and observe the output:
    5 % 2

    You should get the following output:

    1

    The modulus operator is performed using the % operator, as shown in step 7. It returns the remainder when the first number is divided by the second.

In the aforementioned examples, you have used the different math operators and performed operations with them in a Jupyter Notebook. Next, you move on to the order of operations in Python.

Order of Operations

Parentheses are meaningful in Python. When it comes to computation, Python always computes what is in parentheses first.

The Python language follows the same order of operations as in the math world. You may remember the acronym PEMDAS: parentheses first, exponentiation second, multiplication/division third, and addition/subtraction fourth.

Consider the following expression:5 + 2 * -3

The first thing to note is that the negative sign and subtraction sign are the same in Python. Let's have a look at the following example:

  1. Python will first multiply 2 and –3, and then add 5:
    5 + 2 * -3

    You should get the following output:

    –1
  2. If parentheses are placed around the 5 and 2, we obtain a different result:
    (5 + 2) * -3

    You should get the following output:

    –21

If ever in doubt, use parentheses. Parentheses are very helpful for complex expressions, and extra parentheses do not affect code.

In the following exercise, we are going to dive into Python code and work with math operations.

Exercise 1: Getting to Know the Order of Operations

The goal of this exercise is to work with the primary math operations in Python and understand their order of execution. This exercise can be performed on the Python terminal:

  1. Subtract 5 to the 3rd power, which is 53, from 100 and divide the result by 5:
    (100 - 5 ** 3) / 5

    You should get the following output:

    –5.0
  2. Add 6 to the remainder of 15 divided 4:
    6 + 15 % 4

    You should get the following output:

    9
  3. Add 2 to the 2nd power, which is 22, to the integer division of 24 and 4:
    2 ** 2 + 24 // 4

    You should get the following output:

    10

In this quick exercise, you have used Python to perform basic math using the order of operations. As you can see, Python is an excellent calculator. You will use Python often as a calculator in your career as a developer.

Spacing in Python

You may have wondered about spaces in between numbers and symbols. In Python, spaces after a number or symbol do not carry any meaning. So, 5**3 and 5 ** 3 both result in 125.

Spaces are meant to enhance readability. Although there is no correct way to space code, spaces are generally encouraged between operands and operators. Thus, 5 ** 3 is preferable.

Trying to follow certain conventions is perfectly acceptable. If you develop good habits early on, it will make the reading and debugging of code easier later.

Number Types: Integers and Floats

Now you will address the difference between an integer and a float. Consider 8 and 8.0. You know that 8 and 8.0 are equivalent mathematically. They both represent the same number, but they are different types. 8 is an integer, and 8.0 is a decimal or float.

An integer in Python is classified as a type of int, short for integer. Integers include all positive and negative whole numbers, including 0. Examples of integers include 3, -2, 47, and 10000.

Floats, by contrast, are Python types represented as decimals. All rational numbers expressed as fractions can be represented as floats. Samples of floats include 3.0, -2.0, 47.45, and 200.001.

Note

We are only covering text and numeric types in this chapter. Other types will be discussed in subsequent chapters.

Python types can be obtained explicitly using the type() keyword, as you will see in the following exercise.

Exercise 2: Integer and Float Types

The goal of this exercise is to determine types and then change those types in our Python code. This can be performed in the Jupyter Notebook:

  1. Begin by explicitly determining the type of 6 using the following code:
    type(6)

    You should get the following output:

    int
  2. Now, enter type(6.0) in the next cell of your notebook:
    type(6.0)

    You should get the following output:

    float
  3. Now, add 5 to 3.14. Infer the type of their sum:
    5 + 3.14

    You should get the following output:

    8.14

    It's clear from the output that combining an int and a float gives us a float. This makes sense. If Python returned 8, you would lose information. When possible, Python converts types to preserve information.

    You can, however, change types by using the type keyword.

  4. Now, convert 7.999999999 to an int:
    int(7.999999999)

    You should get the following output:

    7
  5. Convert 6 to a float:
    float(6)

    You should get the following output:

    6.0

In this exercise, you determined types by using the type() keyword, and you changed types between integers and floats. As a developer, you will need to use your knowledge of variable types more often than you might expect. It's not uncommon to be unsure of a type when dealing with hundreds of variables simultaneously, or when editing other people's code.

Note

Type changing will be revisited again in this chapter, referred to as casting.

Complex Number Types

Python includes complex numbers as an official type. Complex numbers arise when taking the square roots of negative numbers. There is no real number whose square root is -9, so we say that it equals 3i. Another example of a complex number is 2i + 3. Python uses j instead of i.

You can take a look at the following code snippet to learn how to work with complex number types.

Divide 2 + 3j by 1 - 5j, enclosing both operations within parentheses:

(2 + 3j) / (1 - 5j)

You should get the following output:

–0.5+0.5j

For more information on complex numbers, check out https://docs.python.org/3.7/library/cmath.html.

Errors in Python

In programming, errors are not to be feared; errors are to be welcomed. Errors are common not only for beginners but for all developers. You will learn skills to handle errors in Chapter 4, Extending Python, Files, Errors, and Graphs. For now, if you get an error, just go back and try again. Python errors in Jupyter Notebooks won't crash your computer or cause any serious problems but they will just stop running the Python code.

Variables

In Python, variables are memory slots that can store elements of any type. The name variable is meant to be suggestive, as the idea behind a variable is that the value can vary throughout a given program.

Variable Assignment

In Python, variables are introduced the same way as in math, by using the equals sign. In most programming languages, however, order matters; that is, x = 3.14 means that the value 3.14 gets assigned to x. However, 3.14 = x will produce an error because it's impossible to assign a variable to a number. In the following exercise, we will implement this concept in code to give you a better understanding of it.

Exercise 3: Assigning Variables

The goal of this exercise is to assign values to variables. Variables can be assigned any value, as you will see in this exercise. This exercise can be performed in the Jupyter Notebook:

  1. Set x as equal to the number 2:
    x = 2

    In the first step, we assigned the value 2 to the x variable.

  2. Add 1 to the variable x:
    x + 1

    You should get the following output:

    3

    Once we add 1 to x, we get the output of 3, because the variable has 1 added to it.

  3. Change x to 3.0 and add 1 to x:
    x = 3.0
    x + 1

    You should get the following output:

    4.0

    In this step, we change the value of x to 4.0, and as in the previous 2 steps, we will be adding 1 to the x variable.

By the end of this quick exercise, you may have noticed that in programming, you can assign a variable in terms of its previous value. This is a powerful tool, and many developers use it quite often. Furthermore, the type of x has changed. x started as an int, but now x = 3.0 which is a float. This is allowed in Python because Python is dynamically typed.

Changing Types

In some languages, it's not possible for a variable to change types. This means that if the y variable is an integer, then y must always be an integer. Python, however, is dynamically typed, as we saw in Exercise 3, Assigning Variables and as illustrated in the following example:

  1. y starts as an integer:
    y = 10
  2. y becomes a float:
    y = y – 10.0
  3. Check the type of y:
    type(y)

    You should get the following output:

    float

In the next topic, you will be looking at reassigning variables in terms of themselves.

Reassigning Variables in Terms of Themselves

It's common in programming to add 1 to a variable; for instance, x = x + 1. The shorthand for this is to use += as in the following example:

x += 1

So, if x was 6, x is now 7. The += operator adds the number on the right to the variable and sets the variable equal to the new number.

Activity 1: Assigning Values to Variables

In this activity, you will assign a number to the x variable, increment the number, and perform additional operations.

By completing this activity, you will learn how to perform multiple mathematical operations using Python. This activity can be performed in the Jupyter Notebook.

The steps are as follows:

  1. First, set 14 to the x variable.
  2. Now, add 1 to x.
  3. Finally, divide x by 5 and square it.

    You should get the following output:

    9.0

    Note

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

Variable Names

To avoid confusion, it's recommended to use variable names that make sense to readers. Instead of using x, the variable may be income or age. Although x is shorter, someone else reading the code might not understand what x is referring to. Try to use variable names that are indicative of the meaning.

There are some restrictions when naming variables. For instance, variables cannot start with numbers, most special characters, keywords, nor built-in types. Variables also can't contain spaces between letters.

According to Python conventions, it's best to use lowercase letters and to avoid special characters altogether as they will often cause errors.

Python keywords are reserved in the language. They have special meanings. We will go over most of these keywords later.

Running the following two lines always shows a current list of Python keywords:

import keyword
print(keyword.kwlist)

You should get the following output:

Figure 1.3: Output showing the Python keywords

Figure 1.3: Output showing the Python keywords

Note

If you use any of the preceding keywords as variable names, Python will throw an error.

Exercise 4: Variable Names

The goal of this exercise is to learn standard ways to name variables by considering good and bad practices. This exercise can be performed in Jupyter:

  1. Create a variable called 1st_number and assign it a value of 1:
    1st_number = 1

    You should get the following output:

    Figure 1.4: Output throwing a syntax error

    Figure 1.4: Output throwing a syntax error

    You'll get the error mentioned in the preceding screenshot because you cannot begin a variable with a number.

  2. Now, let's try using letters to begin a variable:
    first_number = 1
  3. Now, use special characters in a variable name, as in the following code:
    my_$ = 1000.00

    You should get the following output:

    Figure 1.5: Output throwing a syntax error

    Figure 1.5: Output throwing a syntax error

    You get the error mentioned in Figure 1.4 because you cannot include a variable with a special character.

  4. Now, use letters again instead of special characters for the variable name:
    my_money = 1000.00

In this exercise, you have learned to use underscores to separate words when naming variables, and not to start variables' names with numbers nor include any symbols. In Python, you will quickly get used to these conventions.

Multiple Variables

Most programs contain multiple variables. The same rules apply as when working with single variables. You will practice working with multiple variables in the following exercise.

Exercise 5: Multiple Variables in Python

In this exercise, you will perform mathematical operations using more than one variable. This exercise can be performed in the Jupyter Notebook:

  1. Assign 5 to x and 2 to y:
    x = 5
    y = 2
  2. Add x to x and subtract y to the second power:
    x + x - y ** 2

    You should get the following output:

    6

    Python has a lot of cool shortcuts, and multiple variable assignment is one of them. Here's the Pythonic way of declaring two variables.

    Note

    Pythonic is a term used to describe code written in the optimum readable format. This will be covered in Chapter 7, Becoming Pythonic.

  3. Assign 8 to x and 5 to y in one line:
    x, y = 8, 5
  4. Find the integer division of x and y:
    x // y

    You should get the following output:

    1

In this exercise, you practiced working with multiple variables, and you even learned the Pythonic way to assign values to multiple variables in one line. It's rare to only work with one variable in practice.

Comments

Comments are extra blocks of code that do not run. They are meant to clarify code for readers. In Python, any text following the # symbol on a single line is a comment. Comments followed by the # symbol may be inline or above the text.

Note

Consistent use of comments will make reviewing and debugging code much easier. It's strongly advisable to practice this from here on out.

Exercise 6: Comments in Python

In this exercise, you will learn two different ways to display comments in Python. This exercise can be performed in the Jupyter Notebook:

  1. Write a comment that states This is a comment:
    # This is a comment

    When you execute this cell, nothing should happen.

  2. Set the pi variable as equal to 3.14. Add a comment above the line stating what you did:
    # Set the variable pi equal to 3.14
    pi = 3.14 

    Adding the comment clarifies what follows.

  3. Now, try setting the pi variable as equal to 3.14 again, but add the comment stating what you did on the same line:
    pi = 3.14  # Set the variable pi equal to 3.14

    Although it's less common to provide comments on the same line of code, it's acceptable and often appropriate.

    You should get the following output from the Jupyter notebook:

Figure 1.6: Output from the Jupyter Notebook using comments

Figure 1.6: Output from the Jupyter Notebook using comments

In this exercise, you have learned how to write comments in Python. As a developer, writing comments is essential to make your code legible to others.

Docstrings

Docstrings, short for document strings, state what a given document, such as a program, a function, or a class, actually does. The primary difference in syntax between a docstring and a comment is that docstrings are intended to be written over multiple lines, which can be accomplished with triple quotes """. They also introduce a given document, so they are placed at the top.

Here is an example of a docstring:

"""
This document will explore why comments are particularly useful 
when writing and reading code.
"""

When you execute this cell, nothing really happens. Docstrings, like comments, are designed as information for developers reading and writing code; they have nothing to do with the output of code.

Activity 2: Finding a Solution Using the Pythagorean Theorem in Python

In this activity, you will determine the Pythagorean distance between three points. You will utilize a docstring and comments to clarify the process.

In this activity, you need to assign numbers to the x, y, and z variables, square the variables, and take the square root to obtain the distance, while providing comments along the way and a docstring to introduce the sequence of steps. To complete this activity, you'll utilize multiple variables, comments, and docstrings to determine the Pythagorean distance between three points.

The steps are as follows:

  1. Write a docstring that describes what is going to happen.
  2. Set x, y, and z as equal to 2, 3, and 4.
  3. Determine the Pythagorean distance between x, y, and z.
  4. Include comments to clarify each line of code.

    You should get the following output:

    5.385164807134504

    Note

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

So far, in this chapter, you have used Python as a basic calculator, along with the order of operations. You examined the difference between int and float values and learned how to convert between them. You can implement variable assignment and reassign variables to make programs run more smoothly. You also utilized comments to make code more readable and learned how to identify syntax errors. In addition, you learned a couple of cool Python shortcuts, including assigning multiple variables to one line. As an added bonus, you explored Python's complex number types.

Next, you'll explore Python's other main type, strings.

Strings: Concatenation, Methods, and input()

You have learned how to express numbers, operations, and variables. What about words? In Python, anything that goes between 'single' or "double" quotes is considered a string. Strings are commonly used to express words, but they have many other uses, including displaying information to the user and retrieving information from a user.

Examples include 'hello', "hello", 'HELLoo00', '12345', and 'fun_characters: !@ #$%^&*('.

In this section, you will gain proficiency with strings by examining string methods, string concatenation, and useful built-in functions including print() and len() with a wide range of examples.

String Syntax

Although strings may use single or double quotes, a given string must be internally consistent. That is, if a string starts with a single quote, it must end with a single quote. The same is true of double quotes.

You can take a look at valid and invalid strings in Exercise 7, String Error Syntax.

Exercise 7: String Error Syntax

The goal of this exercise is to learn appropriate string syntax:

  1. Open a Jupyter Notebook.
  2. Enter a valid string:
    bookstore = 'City Lights'
  3. Now enter an invalid string:
    bookstore = 'City Lights"

    You should get the following output:

    Figure 1.7: Output with invalid string format

    Figure 1.7: Output with invalid string format

    If you start with a single quote, you must end with a single quote. Since the string has not been completed, you receive a syntax error.

  4. Now you need to enter a valid string format again, as in the following code snippet:
    bookstore = "Moe's"

    This is okay. The string starts and ends with double quotes. Anything can be inside the quotation marks, except for more quotation marks.

  5. Now add the invalid string again:
    bookstore = 'Moe's'

    You should get the following output:

Figure 1.8: Output with the invalid string

Figure 1.8: Output with the invalid string

This is a problem. You started and ended with single quotes, and then you added an s and another single quote.

A couple of questions arise. The first is whether single or double quotes should be used. The answer is that it depends on developer preference. Double quotes are more traditional, and they can be used to avoid potentially problematic situations such as the aforementioned Moe's example. Single quotes eliminate the need to press the Shift key.

In this exercise, you have learned the correct and incorrect ways of assigning strings to variables, including single and double-quotes.

Python uses the backslash character, \, called an escape sequence in strings, to allow for the insertion of any type of quote inside of strings. The character that follows the backslash in an escape sequence may be interpreted as mentioned in Python's official documentation, which follows. Of particular note is \n, which is used to create a new line:

Figure 1.9: Escape sequences and their meaning

Figure 1.9: Escape sequences and their meaning

Note

For more information on strings, you can refer to https://docs.python.org/2.0/ref/strings.html.

Escape Sequences with Quotes

Here is how an escape sequence works with quotes. The backslash overrides the single quote as an end quote and allows it to be interpreted as a string character:

bookstore = 'Moe\'s'

Multi-Line Strings

Short strings always display nicely but, what about multi-line strings? It can be cumbersome to define a paragraph variable that includes a string over multiple lines. In some IDEs, the string may run off the screen, and it may be difficult to read. In addition, it might be advantageous to have line breaks at specific points for the user.

Note

Line breaks will not work inside single or double quotes.

When strings need to span multiple lines, Python provides triple quotes, using single or double quotation marks, as a nice option.

Here is an example of triple quotes (''') used to write a multi-line string:

vacation_note = ''' 
During our vacation to San Francisco, we waited in a long line by 
Powell St. Station to take the cable car. Tap dancers performed on 
wooden boards. By the time our cable car arrived, we started looking 
online for a good place to eat. We're heading to North Beach.
'''

Note

Multi-line strings take on the same syntax as a docstring. The difference is that a docstring appears at the beginning of a document, and a multi-line string is defined within the program.

The print() Function

The print() function is used to display information to the user, or to the developer. It's one of Python's most widely used built-in functions.

Exercise 8: Displaying Strings

In this exercise, you will learn different ways to display strings:

  1. Open a new Jupyter Notebook.
  2. Define a greeting variable with the value 'Hello'. Display the greeting using the print() function:
    greeting = 'Hello'
    print(greeting)

    You should get the following output:

    Hello

    Hello, as shown in the display, does not include single quotes. This is because the print() function is generally intended for the user to print the output.

    Note

    The quotes are for developer syntax, not user syntax.

  3. Display the value of greeting without using the print() function:
    greeting

    You should get the following output:

    'Hello'

    When we input greeting without the print() function, we are obtaining the encoded value, hence the quotes.

  4. Consider the following sequence of code in a single cell in a Jupyter Notebook:
    spanish_greeting = 'Hola.'
    spanish_greeting
    arabic_greeting = 'Ahlan wa sahlan.'

    When the preceding cell is run, the preceding code does not display spanish_greeting. If the code were run on a terminal as three separate lines, it would display Hola., the string assigned to spanish_greeting. The same would be true if the preceding sequence of code were run in three separate cells in a Jupyter Notebook. For consistency, it's useful to use print() any time information should be displayed.

  5. Display the Spanish greeting:
    spanish_greeting = 'Hola.'
    print(spanish_greeting)

    You should get the following output:

    Hola.
  6. Now, display the Arabic greeting message, as mentioned in the following code snippet:
    arabic_greeting = 'Ahlan wa sahlan.'
    print(arabic_greeting)

    You should get the following output:

    Ahlan wa sahlan.

    The compiler runs through each line in order. Every time it arrives at print(), it displays information.

In this exercise, you have learned different ways to display strings, including the print() function. You will use the print() function very frequently as a developer.

String Operations and Concatenation

The multiplication and addition operators work with strings as well. In particular, the + operator combines two strings into one and is referred to as string concatenation. The * operator, for multiplication, repeats a string. In the following exercise, you will be looking at string concatenation in our string samples.

Exercise 9: String Concatenation

In this exercise, you will learn how to combine strings using string concatenation:

  1. Open a new Jupyter Notebook.
  2. Combine the spanish_greeting we used in Exercise 8, Displaying Strings, with 'Senor.' using the + operator and display the results:
    spanish_greeting = 'Hola'
    print(spanish_greeting + 'Senor.')

    You should get the following output:

    HolaSenor.

    Notice that there are no spaces between greeting and name. If we want spaces between strings, we need to explicitly add them.

  3. Now, combine spanish_greeting with 'Senor.' using the + operator, but this time, include a space:
    spanish_greeting = 'Hola '
    print(spanish_greeting + 'Senor.')

    You should get the following output:

    Hola Senor.
  4. Display the greeting 5 times using the * multiplication operator:
    greeting = 'Hello'
    print(greeting * 5)

    You should get the following output:

    HelloHelloHelloHelloHello

By completing this exercise successfully, you have combined strings using string concatenation using the + and * operators.

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.

String Indexing and Slicing

Indexing and slicing are crucial parts of programming. In data analysis, indexing and slicing DataFrames is essential to keep track of rows and columns, something we will practice in Chapter 10, Data Analytics with pandas and NumPy. The mechanics behind indexing and slicing dataFrames is the same as indexing and slicing strings, which we will learn in this chapter.

Indexing

The characters of Python strings exist in specific locations; in other words, their order counts. The index is a numerical representation of where each character is located. The first character is at index 0, the second character is at index 1; the third character is at index 2, and so on.

Note

We always start at 0 when indexing.

Consider the following string:

destination = 'San Francisco'

'S' is in the 0th index, 'a' is in the 1st index, 'n' is in the 2nd index, and so on. The characters of each index are accessed using bracket notation as follows:

destination[0]

You should get the following output:

'S'

To access the data from the first index, enter the following:

destination[1]

You should get the following output:

'a'

To access the data from the second index, enter the following:

destination[2]

You should get the following output:

'n'

The character value for San Francisco and the corresponding index count is shown in Figure 1.15:

Figure 1.15: Diagrammatic representation of the character values and the corresponding positive index values

Figure 1.15: Diagrammatic representation of the character values and the corresponding positive index values

Now, try adding a -1 as the index value and observe the output:

destination[-1]

You should get the following output:

'o'

Note

Negative numbers start at the end of the string. (It makes sense to start with -1 since -0 is the same as 0.)

To access the data from the rear of San Francisco, we use the negative sign in this case -2:

destination[-2]

You should get the following output:

'c'

The following figure 1.16 mentions the characters sco from the word Francisco, and the corresponding index count:

Figure 1.16: Index value for the negative values for San Francisco

Figure 1.16: Index value for the negative values for San Francisco

Here is one more example:

bridge = 'Golden Gate'
bridge[6]

You should get the following output:

' '

You may be wondering whether you did something wrong because no letter is displayed. On the contrary, it's perfectly fine to have an empty string. In fact, an empty string is one of the most common strings in programming.

Left arrow icon Right arrow icon

Key benefits

  • Build key Python skills with engaging development tasks and challenging activities
  • Implement useful algorithms and write programs to solve real-world problems
  • Apply Python in realistic data science projects and create simple machine learning models

Description

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.

Who is this book for?

This book is designed for anyone who is new to the Python programming language. Whether you're an aspiring software engineer or data scientist, or are just curious about learning how to code with Python, this book is for you. No prior programming experience is required.

What you will learn

  • Write clean and well-commented code that is easy to maintain
  • Automate essential day-to-day tasks with Python scripts
  • Debug logical errors and handle exceptions in your programs
  • Explore data science fundamentals and create engaging visualizations
  • Get started with predictive machine learning
  • Keep your development process bug-free with automated testing
Estimated delivery fee Deliver to Estonia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 06, 2019
Length: 608 pages
Edition : 1st
Language : English
ISBN-13 : 9781839218859
Category :
Languages :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Estonia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Nov 06, 2019
Length: 608 pages
Edition : 1st
Language : English
ISBN-13 : 9781839218859
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 118.97
40 Algorithms Every Programmer Should Know
€37.99
The JavaScript Workshop
€32.99
The Python Workshop
€47.99
Total 118.97 Stars icon

Table of Contents

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

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(36 Ratings)
5 star 66.7%
4 star 16.7%
3 star 5.6%
2 star 0%
1 star 11.1%
Filter icon Filter
Top Reviews

Filter reviews by




Kindle Customer May 21, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book, very detailed exercises, and all around really useful. Highly recommended if you are thinking of dipping your toes into Python!
Amazon Verified review Amazon
Briana D. Oct 16, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I purchased this book because I’m just starting out with learning programming and this was recommended as a guide suitable for a beginner. I suppose it’s to be expected that students of this text would need to execute the code themselves rather than just read it in the book. The fact that the publisher guides you on how to do this is very appreciated. I find the book’s corresponding videos on the publisher’s website to be particularly helpful in clarifying some points made in the text.I saw a review that mentioned the text font made the book hard to follow. There was also mention that it hadn’t been proofread. I feel like this person MUST have been reviewing an entirely different book! While I’ve not yet completed the book, thus far I’ve not encountered anything that would speak to more proofreading needing to be done. And the text font and layout caught my attention immediately in such a positive and exciting way when I first opened the book. I expected the text to be tiny and difficult to read. Wow, the text is incredibly pleasing to the eyes and easy to follow.I would have paid twice as much for this book!
Amazon Verified review Amazon
J May 25, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I bought this for my boyfriend, as he wanted to learn coding! He said it’s very informative and he likes it so much he plans on getting the kindle version eventually!
Amazon Verified review Amazon
CatrerP007 Apr 03, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was recommended this book by my computer science professor to learn python.I wanted to learn python on my own and I can say, it's a very easy book to follow, especially compared to C++. I highly recommend it to anyone wanting to learn python l.
Amazon Verified review Amazon
William Hall Feb 10, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The Python Workshop by Packt Publications is a very thorough guide to getting started with Python. It covers everything you need to know to be able tobuild great Python projects, and is also a great resource for experienced developers. Although the book is geared toward Python beginners, you will need priorknowledge of javascript, and html and css.They cover everything from the basics right up to advanced topics, and include information on how to dockerize your apps; including maching learning, data analysiswith Pandas and numPy, working with files, error handling, ...etc.All the examples in the book are easy to follow, and if you purchase the print copy you have access to videos and guided solutions, if needed. I would highlyrecommend this book for anyone wanting to learn Python, as it is very easy to follow along with the code examples, and the concepts are very well explained. Getyour copy today.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela