Home Programming The Python Workshop - Second Edition

The Python Workshop - Second Edition

By Corey Wade , Mario Corchero Jiménez , Andrew Bird and 2 more
ai-assist-svg-icon Book + AI Assistant
eBook + AI Assistant $41.99 $28.99
Print $51.99
Subscription $15.99 $10 p/m for three months
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
eBook + AI Assistant $41.99 $28.99
Print $51.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 2: Python Data Structures
About this book
Python is among the most popular programming languages in the world. It’s ideal for beginners because it’s easy to read and write, and for developers, because it’s widely available with a strong support community, extensive documentation, and phenomenal libraries – both built-in and user-contributed. This project-based course has been designed by a team of expert authors to get you up and running with Python. You’ll work though engaging projects that’ll enable you to leverage your newfound Python skills efficiently in technical jobs, personal projects, and job interviews. The book will help you gain an edge in data science, web development, and software development, preparing you to tackle real-world challenges in Python and pursue advanced topics on your own. Throughout the chapters, each component has been explicitly designed to engage and stimulate different parts of the brain so that you can retain and apply what you learn in the practical context with maximum impact. By completing the course from start to finish, you’ll walk away feeling capable of tackling any real-world Python development problem.
Publication date:
November 2022
Publisher
Packt
Pages
600
ISBN
9781804610619

 

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.

Note

This chapter covers the fundamentals of the Python language.

 

Introduction

In this chapter, we will present vital Python concepts; that is, the core elements that everyone needs to know when starting to code. We will cover a breadth of topics while focusing 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, 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. The first variables we will look at will be integers, floats...

 

Technical requirements

The code files for this chapter are available on GitHub at https://github.com/PacktPublishing/The-Python-Workshop-Second-Edition/tree/main/Chapter01.

In the Preface, we learned how to install Anaconda, which comes with the most updated version of Python and Jupyter Notebook. We are using Jupyter Notebook as the default integrated development environment (IDE) for this book because it is sufficient for your entire Python Workshop journey, including the later chapters on data science.

It’s time to open a Jupyter Notebook and begin our Pythonic journey.

Note

The Python code in most of the chapters of this book will work on almost any IDE that supports Python. Feel free to use Colab notebooks, terminals, Sublime Text, PyCharm, or any other IDE that suits your purposes.

Opening a Jupyter Notebook

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

  1. Locate and open Anaconda...
 

Python as a calculator

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 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, which uses mod12.

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...

 

Strings – concatenation, methods, and input()

So far, you have learned how to express numbers, operations, and variables. But 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(), by covering 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...

 

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.

Look at the following example, where we add Ciao within a print statement:

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

The output is as follows:

Should we greet people with Ciao in North Beach?

f-strings

Perhaps the most effective way to combine variables with strings is with f-strings. Introduced in Python 3.6, f-strings are activated whenever the f character is followed by quotations. The advantage is that any variable inside curly...

 

String indexing and slicing

Indexing and slicing are crucial parts of programming. Indexing and slicing are regularly used in lists, a topic that we will cover in Chapter 2, Python Data Structures. In data analysis, indexing and slicing DataFrames is essential to keep track of rows and columns, something you will practice in Chapter 10, Data Analytics with pandas and NumPy.

Indexing

The characters in 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 in computer programming!

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, as shown in the following table:

...
 

Slicing

A slice is a subset of a string or other element. A slice could be the whole element or one character, but it’s more commonly a group of adjoining characters.

Let’s say you want to access the fifth through eleventh letters of a string. So, you start at index 4 and end at index 10, as was explained in the Indexing section. When slicing, the colon symbol (:) is inserted between indices, like so: [4:10].

There is one caveat: the lower bound of a slice is always included, but the upper bound is not. So, in the preceding example, if you want to include the 10th index, you must use [4:11].

Now, let’s have a look at the following example for slicing.

Retrieve the fifth through eleventh letters of the destination variable, which you used in the Indexing section:

destination[4:11]

The output is as follows:

Francis’

Retrieve the first three letters of destination:

destination[0:3]

The output is as follows:

San...

 

Booleans and conditionals

Booleans, named after George Boole, take the values of True or False. Although the idea behind Booleans is rather simple, they make programming much more powerful.

When writing programs, it’s useful to consider multiple cases. If you prompt the user for information, you may want to respond differently, depending on the user’s answer.

For instance, if the user gives a rating of 0 or 1, you may give a different response than a rating of 9 or 10. The keyword here is if.

Programming based on multiple cases is often referred to as branching. Each branch is represented by a different conditional. Conditionals often start with an if clause, followed by else clauses. The choice of a branch is determined by Booleans, depending on whether the given conditions are True or False.

Booleans

In Python, a Boolean class object is represented by the bool keyword and has a value of True or False.

Note

Boolean values must be capitalized in Python...

 

Loops

Write the first 100 numbers.

There are several assumptions implicit in this seemingly simple command. The first is that the student knows where to start, namely at number 1. The second assumption is that the student knows where to end, at number 100. And the third is that the student understands that they should count by 1.

In programming, this set of instructions may be executed with a loop.

There are three key components to most loops:

  1. The start of the loop
  2. The end of the loop
  3. The increment between numbers in the loop

Python distinguishes between two fundamental kinds of loops: while loops and for loops.

while loops

In a while loop, a designated segment of code repeats, provided that a particular condition is true. When the condition evaluates to false, the while loop stops running. A while loop may print out the first 10 numbers.

You could print the first 10 numbers by implementing the print function 10 times, but using...

 

Summary

You have gone over a lot of material in this introductory chapter. You have covered math operations, string concatenation and methods, general Python types, variables, conditionals, and loops. Combining these elements allows us to write programs of real value.

Additionally, you have been learning Python syntax. You now understand some of the most common errors, and you’re becoming accustomed to the importance that indentation plays. You’re also learning how to leverage important keywords such as range, in, if, and True and False.

Going forward, you now have the key fundamental skills to tackle more advanced introductory concepts. Although there is much to learn, you have a vital foundation in place to build upon the types and techniques discussed here.

In the next chapter, you will learn about some of the most important Python types, including lists, dictionaries, tuples, and sets.

About the Authors
  • Corey Wade

    Corey Wade, M.S. Mathematics, M.F.A. Writing & Consciousness, is the founder and director of Berkeley Coding Academy where he teaches Machine Learning and AI to teens from all over the world. Additionally, Corey chairs the Math Department at Berkeley Independent Study where he has received multiple grants to run after-school coding programs to help bridge the tech skills gap. Additional experiences include teaching Natural Language Processing with Hello World, developing Data Science curricula with Pathstream, and publishing statistics and machine learning models with Towards Data Science, Springboard, and Medium.

    Browse publications by this author
  • Mario Corchero Jiménez

    Mario Corchero Jiménez is a senior software developer at Bloomberg. He leads the Python infrastructure team in London, enabling the company to work effectively in Python and building company-wide libraries and tools. His professional experience is mainly in C++ and Python, and he has contributed some patches to multiple Python open source projects. He is a PSF fellow, having received the Q3 2018 PSF Community Award, is vice president of Python Espaa (the Python Spain association), and has served as Chair of PyLondinium, PyConES17, and PyCon Charlas at PyCon 2018. Mario is passionate about the Python community, open source, and inner source.

    Browse publications by this author
  • Andrew Bird

    Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".

    Browse publications by this author
  • Dr. Lau Cher Han

    Dr Lau Cher Han is a Chief data scientist, and currently the CEO of LEAD, an institution that provides programs on data science, full stack web development, and digital marketing. Well-versed in programming languages: JavaScript, Python, C# and so on he is experienced in web frameworks: MEAN Stack, ASP.NET, Python Django and is multilingual, speaking English, Chinese, Bahasa fluently. His knowledge of Chinese spreads even into its dialects: Hokkien, Teochew, and Cantonese.

    Browse publications by this author
  • Graham Lee

    Graham Lee is an experienced programmer and writer. He has written books including Professional Cocoa Application Security, Test-Driven iOS Development, APPropriate Behaviour and APPosite Concerns. He is a developer who's been programming for long enough to want to start telling other people about the mistakes he's made, in the hope that they'll avoid repeating them. In his case, this means having worked for about 12 years as a professional. His first programming experience can hardly be called professional at all: as it was in BASIC, on a Dragon 32 microcomputer.

    Browse publications by this author
Latest Reviews (3 reviews total)
The Python Workshop - Second Edition
Unlock this book and the full library FREE for 7 days
Start now