Chapter 1. Why Python?: Similar but Different

Image

Python starts counting from zero, which should sound familiar.

In fact, Python has a lot in common with other programming languages. There are variables, loops, conditionals, functions, and the like. In this, our opening chapter, we take you on a high-level whistle-stop tour of Python’s basics, introducing the language without getting too much into the weeds. You’ll learn how to create and run code with Jupyter Notebook (running inside VS Code). You’ll see how lots of programming functionality comes built-in to Python, which you’ll leverage to get stuff done. You’ll also learn that although Python shares a lot of its ideas with other programming languages, how they manifest in your Python code can be, well, different. Now, don’t get the wrong idea here: we’re talking different good, not different bad. Read on to learn more…

Image

Sure. Let’s get to know Python.

We are going to wait to talk about the project in the next chapter. For now, let’s concentrate on getting to the point where you’ve a firm grasp of some of the basics, such as using your toolchain to create, edit, and run your Python code. Let’s also introduce some of Python’s language features to give you the feel you require. We’re going to keep the example simple, mainly using it to present a Python overview as opposed to using Python to solve a particular problem (there’s lots of that coming soon).

Note

And, don’t worry: everything mentioned in this chapter’s overview is covered in more detail later in this book.

As the interview with Python confirms, there’s a bunch of reasons for Python’s popularity. We’ve listed the takeaways we gleaned from the interview at the bottom of this page.

Let’s spend some time considering these takeaways in more detail. Once you’ve surveyed our list, grab a pencil—yes, a pencil—and meet us at the top of the next page!

  • Image Python code is easy to read.

  • Image Python comes with a Standard Library.

  • Image Python has practical, powerful, and generic built-in functions (BIFs).

  • Image Python comes with built-in data structures.

  • Image Python has the Python Package Index (PyPI).

  • Image Python doesn’t take itself too seriously.

Note

Don’t underestimate the importance of this last one.

Getting ready to run some code

There’s a tiny bit of housekeeping to work through before you get run any code.

To help keep things organized, let’s create a folder on your computer called Learning. You can put this folder anywhere on your hard drive, so long as you remember where you put it, as you are going to use it all the time. [If you need to, put your new Learning folder inside a HeadFirst folder to distinguish it from any other Learning folder you may have.]

With your new Learning folder created, start VS Code.

Image
Note

Don’t feel bad if you skipped the Intro. You aren’t the first to do this, and won’t be the last. Image

Image

Each time you work with VS Code in this book, you’ll open your Learning folder as needed. Do this now before continuing.

Preparing for your first Jupyter experience

OK. You’re running VS Code, and you’ve opened your Learning folder. Let’s create a new notebook by first selecting the File menu, then selecting the New File… menu option. You’ll be presented with three choices:

Image
Image

VS Code creates and opens a new, untitled notebook called Untitled-1.ipynb, which appears on screen, and looks something like this:

Image

Drum roll, please. You’re now ready to type in and run some Python code.

Let’s pop some code into your notebook editor

Your cursor is waiting in that empty code cell. Before you type in anything, let’s take a moment to review the first four lines of code from this chapter’s example:

Image

Let’s see what happens when you type this code into your notebook.

Press Shift+Enter to run your code

When you press Shift+Enter, the code in the currently selected cell runs. The focus then moves to the next cell in your notebook. If no “next cell” exists, Jupyter creates a new one for you:

Note

When you see “Shift+Enter” in this book, press and hold down the Shift key, then tap the Enter key (before releasing both).

Image
Image

Yes, those four lines of code ran.

However, no output was produced, so nothing has appeared on screen. What has happened is that Python has imported the random library, as well as defined those three variables: suits, faces, and numbered.

So… Python code really is easy to read… and run

Besides Jupyter, there are other ways to run Python code, and you’ll learn about some of them as you work through this book. However, using VS Code with Jupyter is—in our view—the perfect way to read, run, experiment, and play with Python code when first learning the language. So get ready to spend a lot of time in Jupyter and VS Code.

Before moving on, take a moment to select File then Save from the VS Code menu to save your notebook under the name Cards.ipynb.

Note

Be sure to do this now!

Image

No, but it’s a great tool to use when first learning the language as Jupyter hooks into Python’s built-in REPL to run each of your code cells. You’ll learn how to run your code outside of a notebook later in this book but—for now—all you need to worry about is using notebooks within VS Code (as you follow along).

Note

For more on what a REPL is, look here: https://en.wikipedia.org/wiki/Read-eval-print_loop.

Image

Yes. Python is an interpreter that is designed to run each line of code as and when it sees it. To be technically correct, Python does compile your code, but it all happens behind the scenes (to relieve you of the burden of doing it yourself). All you have to do is write your code, then run it: Python takes care of the details, and Jupyter’s Shift+Enter mechanism makes it easy for you to control when the execution happens.

Image

Yes, when you see code presented within a grey box, you can assume it’s code to be entered into a code cell in your current notebook ready for execution with Shift+Enter. To follow along, type the code in each grey box into your notebook, then run it (as needed) with Shift+Enter.

Image

Right! And Python’s for loop is what you’d use. Let’s take a quick look at how you’d use for to do this.

What if you want more than one card?

Your draw function is a great start, drawing one card from the deck each time the function is executed. But, what if you want to draw more than one card?

Although it would be a little ridiculous to suggest manually invoking your draw function as many times as needed, most programmers instead reach for a loop. You’ll learn more about Python’s loops later in this book. For now, here’s how you’d use Python’s for loop to execute the draw function five times:

Image
Image

That’s Python’s default variable.

It’s typical for most loops to have a loop variable associated with them (with “i” being a particular favorite name among many programmers). However, if your loop’s code doesn’t use that variable’s value, Python lets you use the underscore character instead.

When you see the underscore in code, think “Ah ha! A variable is syntactically required here, but it’s value isn’t used, so the variable hasn’t been named.”

Image

Yes, the same card is being drawn twice.

The trouble here is that the draw funciton is returning the Queen of Diamonds twice. Whoops!

Let’s take a closer look at what draw is doing to see why this is happening.

Take a closer look at the card drawing code

The draw function is only three lines long, but still packs a punch. Take a look:

Image

We know: all those * characters surrounding the word “randomly” in those annotations weren’t enough of a clue, were they? Although the draw code succeeds at selecting a random card, it doesn’t guard against returning the same card twice. After all, in most card games, once a card is selected from the deck, it’s rarely put straight back in, is it? If this was “real” card drawing code (as opposed to a made up example designed to support this chapter’s Python overview), we’d likely use a different data structure to the arrays currently used, right?

The Big 4: list, tuple, dictionary, and set

Python’s excellent built-in support for data structures is legendary, and is often cited as the main reason most Python programmers love Python.

As this is your opening chapter, we’re not going to overload you with any sort of in-depth discussion of these data structures right now. There are lots of pages (entire chapters, in fact) dedicated to The Big 4 later in this book.

Although we haven’t called out their use specifically, you have already encountered lists and tuples. While rather cheekily referring to these as arrays earlier, each of these “arrays” are in fact a bona fide, honest to goodness, Python list:

Image

You’ve also seen your fair share of tuples, too. Every time you invoke the draw function, it gives you back a tuple:

Note

Here’s a quick question: how would you pronounce “tuple”? To rhyme with “couple” or to rhyme with “quadruple”? It’s anyone’s guess, really. Image

Image

You’d be forgiven for thinking tuples look at little weird, and we’d have to agree that we think they look a little weird, too. Don’t let this worry you.

You’ll learn more about both lists and tuples later in this book. Although both lists and tuples have their uses, they are not a great fit when it comes to modeling a deck of cards. Some other data structure is needed here. But, which one?

Note

Hint: there is a big clue in the title of this page.

Model your deck of cards with a set

Sets in Python are likes sets from math class: they contain a collection of unique values where duplicates are not allowed.

Note

Don’t worry if you guessed “dictionary” (after all, it was always going to be one or the other). You’ll learn all about dictionaries later in this book.

Sets in Python also make it especially convenient to add and remove objects. And, yes, other data structures can add/remove objects too, but—typically—you have to find the object first, then remove it. Or you have to search for the object to ensure it’s not already in the data structure before adding it. In both these cases, that’s two operations for add and two operations for remove (with the other data structures).

Not so with sets.

A single operation adds to the set, and another operation removes from the set, relieving you of the need to do all that searching. In our mind, using a set to model a deck of playing cards is a near perfect fit.

Continue to follow along in your Cards.ipynb notebook while we first create an empty set, then learn a bit about sets, before adding the 52 playing cards, then removing cards from the deck as needed.

Image

Now that your set exists and is assigned to a (rather imaginatively named) variable called deck, let’s learn a little about it. Two of Python’s built-in functions (BIF) help here: type and len:

Image

“BIF” is shorthand for “built-in function.”

Now that your set exists, how can you determine what you can do with it? Well… there’s a BIF for that.

The print dir combo mambo

When provided with the name of any Python object, the dir BIF returns a list of the object’s attributes that, in the case of the deck variable, are the attributes associated with a set object.

As you can see (below), there are an awful lot of attributes associated with a Python set. Note how the output from dir is combined with a call to the print BIF, ensuring the displayed output is drawn across your screen as opposed to down your screen, which cuts down on the amount of scrolling required of your poor fingers. This may not be something to dance about but—hey!—every little bit helps.

Image
Image

Here’s a simple rule to follow when looking at the output from print dir: For now, ignore the attributes that begin and end with a double underscore. You’ll learn why they exist later in this book, but—for now—ignore, ignore, ignore!

Getting help with dir’s output

You might not think this to look at it, but you’ll likely use the dir BIF more than any other BIF when working with Python, especially when experimenting within a Jupyter notebook. This is due to dir’s ability to fess up the list of attributes associated with any object. Typically, these attributes include a list of methods that can be applied to the object.

Although it might be tempting (albeit a little absurd) to randomly execute any of the methods associated with the deck variable to see what they do, a more sensible approach is to read the documentation associated with any one method…

Image

Now, don’t worry: we aren’t about to send you off to wade through thousands of pages of online Python documentation. That’s the help BIF’s job:

Image

Populate the set with cards

At the bottom of the last page (and as luck would have it) we used the help BIF to view the Python documentation for the add method, which is built into every Python set. Knowing what add does, let’s look at some code which uses the “raw” card data from earlier to build a deck of cards:

Image
Image

Yes, we did. And that’s OK.

Python’s data structures can grow and shrink as needed, so there’s no need to predeclare their size.

The Python interpreter handles all the underlying details for you. Memory is dynamically allocated and deallocated as needed, freeing you to create the code you need.

This feels like a deck of cards now

Now that your deck of cards is a set, you can better model its behavior.

Sadly, randomly selecting a card from the deck is complicated by the fact the random.choice technique from earlier in this chapter doesn’t work with sets. This is a pity, as it would’ve been nice to use random.choice(deck) to pick a card from your deck but—alas—this won’t work.

Note

For now, don’t worry about why this is.

Not to worry. A quick hack lets you first convert a copy of your set of cards to a list, which can then be used with random.choice. It couldn’t be more straightforward:

Image

Having selected a card (it’s the Ace of Spades for us, but is likely a different card if you’re following along), we should really remove the card from the deck so that subsequent random choices no longer select it.

Image

What exactly is “card”?

If you’re wondering what the card variable is, don’t forget about type, which reports the type of the value currently assigned to card:

Image
Image

Yes. And it’s almost too easy.

Although you’ve already seen the in keyword as part of your for loop, on it’s own in is quite something.

Flip the page to learn more about this Python superpower.

Need to find something?

As mentioned at the bottom of the last page, you’ve already met the in keyword:

Image

But the in keyword can do much more: it can search.

Given any Python data structure, in can perform a membership test, checking to see if a value is found therein. Let’s check to see if the Ace of Hearts in still in our deck. Be sure to follow along, and remember to use Shift+Enter to run each cell:

Image

Let’s pause and take stock

Recall the list gleaned from the interview with Python at the start of this chapter. Although this overview isn’t tackling this list in order (what rebels we are), at this stage you can place a checkmark against those points you’ve been introduced to:

  • Image Python code is easy to read. Image

  • Image Python comes with a Standard Library.

  • Image Python has practical, powerful, and generic built-in functions (BIFs). Image

  • Image Python comes with built-in data structures. Image

  • Image Python has the Python Package Index (PyPI).

  • Image Python doesn’t take itself too seriously.

Image

Great, we’re making progress!

Now… in a rather shocking break with tradition, let’s look at the remaining three points in the order they appear in the list.

First up is the Python Standard Library.

Python ships with a rich standard library

The Python Standard Library (PSL) is the name used to refer to a large collection of Python functions, types, modules, classes, and packages bundled with Python. These are guaranteed to be there once Python is installed.

Image

When you hear programmers refer to Python as coming with “batteries included,” they are referring in part to the PSL. There’s a lot to it: https://docs.python.org/3/library/index.html.

In this book, “PSL” is short-hand for the “Python Standard Library.”

Image
Image

Yes. And we’ve all been there.

You open up your latest gift only to realize it hasn’t come with everything you need: the batteries are missing. Cue the sad music…

Python, on the other hand, rarely disappoints as the PSL comes with lots of built-in libraries. You’ve already seen (and used) the random library, but there’s so much more. Let’s take a closer look.

Image

There sure is a lot going on there.

Our goal is to give you a flavor of what’s in the PSL, not for you to explore it in any great detail.

Note

To be clear: we’re not talking about coffee…

You are not expected to know all of this, nor remember what’s on the last page, although there are three points you should consider.

  • Image You’ve only scratched the surface.

    The PSL has a lot in it, and what’s on the previous two pages provides the briefest of glimpses. As you work through this book, we’ll call out uses of the PSL so you don’t miss any.

  • Image The PSL represents a large body of tested code that you don’t have to write, just use.

    As the PSL has existed for decades now, the modules it contains have been tested to destruction by legions of Python programmers all over the globe. Consequently, you can use PSL modules with confidence.

  • Image The PSL is guaranteed to be there, so you can rely on its modules being available.

    Other than for some very specific edge cases (such as a tiny embedded microcontroller providing a minimal Python environment), you can be sure your code that uses any PSL module will be portable to other systems that also support the PSL.

With Python you’ll only write the code you need

The PSL is a prime example of Python working hard to ensure you only write new code when you absolutely have to. If a module in the PSL solves your problem, use it: Resist the urge to code everything from scratch.

And when it comes to reusing code, there’s more than the PSL to mine.

Image

Python’s package ecosystem is to die for

Not being content with what’s already included in the PSL, the Python community supports an online centralized repository of third-party modules, classes, and packages. It’s called the Python Package Index and lives here: https://pypi.org.

Known as PyPI (and pronounced “pie-pea-eye”), the index is a huge collection of software. Once you find what you’re looking for, installing is a breeze, and you’ll get lots of practice installing from PyPI as this book progresses.

For now, take ten minutes to visit the PyPI site (shown below) and take a look around.

Image
Image

No. Just remember it’s there.

Like with the PSL, the mountains of libraries and modules available on PyPI exists to make your life easier (and to save you from writing code which already exists).

BTW: That search box on PyPI’s homepage is your friend…

  • Image Python code is easy to read. Image

  • Image Python comes with a Standard Library. Image

  • Image Python has practical, powerful, and generic built-in functions (BIFs). Image

  • Image Python comes with built-in data structures. Image

  • Image Python has the Python Package Index (PyPI). Image

  • Image Python doesn’t take itself too seriously.

Note

We’re almost there. There’s just this last point to discuss.

Image

OK. If it works for you, sure, follow your Zen!

Seriously, though, when a programming language is named in honor of a bunch of comedians, it should come as no surprise that things get a little silly sometimes. This is not a bad thing.

The Python documentation is literally littered (sorry) with references to Monty Python. Where other documentation favors foo and bar, the Python docs favor parrots, spam, and eggs. Or is it eggs and spam? Anyway, as the documentation states: you don’t have to like Monty Python to use Python, but it helps. Image

Image

Python comes with a few Easter eggs that demonstrate how Python programmers sometimes don’t take themselves too seriously, and also don’t mind when other folk have a bit of fun at their expense. To see what we mean, return to your notebook one last time, and, in two new code cells, run each of the following lines of code. Enjoy!

Image
Image
  • Image Python doesn’t take itself too seriously. Image

Note

And with that, your overview is done!

Image

And we can help you with that.

In the next chapter we introduce—and start immediately working on—a real-world problem that you’ll solve with Python code. Working together, we’ll build a solution while learning more Python, revisiting the material from this chapter in more detail when needed, and as this book progresses.

Before getting to all that, though, take some time to review the chapter summary on the next page before testing your retention skills with this chapter’s crossword puzzle.

See you in the next chapter, Chapter 2, which is actually your second chapter as we started counting from zero (just like Python).

Just when you thought you were done…

Go grab your scissors, as here’s a handy cutout chart of the Jupyter Notebook keyboard shortcuts we view as essential. You’ll get to use all of these are you learn more about Jupyter. For now, Shift+Enter remains the most important combination:

Image
Note

Just as well, as we asked you to take your scissors to what’s on the flipside!

Get Head First Python, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.