(This page has no text content)
(This page has no text content)
The Quick Python Book, Fourth Edition 1. welcome 2. 1_About_Python 3. 2_Getting_started 4. 3_The_Quick_Python_overview 5. 4_The_absolute_basics 6. 5_Lists,_tuples,_and_sets 7. 6_Strings 8. 7_Dictionaries 9. 8_Control_flow
welcome Thank you for purchasing the MEAP for The Quick Python Book, 4th edition. To get the most benefit from this book, you’ll want to have some established skills in programming, either in Python or in another programming language like Java, C++, Ruby, Javascript, or something similar. Since this book assumes an understanding of common data types and flow control structures, experience with only HTML or SQL may not be a good fit. The first edition of this book was written over 25 years ago, so it has stood the test of time. Over that time Python has evolved enormously from the version 1.5 of the first edition. When I took over as author of the 2nd edition, covering Python 3.1, I was stunned at how many details had changed, even while the overall feel of Python had stayed the same. While the changes in the third edition (for Python 3.6) and this edition (Python 3.13) have been more manageable, Python has continued to develop, with the addition of new control structures, libraries, and more. In addition to the changes in the language, we have also worked to improve the format of the book itself, adding quick check questions to test your knowledge, chapter labs and a case study to help consolidate your learning, and in this edition, a critical discussion of how to use and evaluate AI code generation as part of the labs and case study. Finally, the way one uses Python has evolved, and one of the most popular environments for using Python has become the Jupyter notebook, which combines text and code in a browser based interface, which makes using Python much easier, particularly for data exploration. Since Jupyter can be served via the web, various services can support it, and for this edition we have shared the the source code (with a couple of exceptions) as Jupyter notebooks hosted in a Github repository. Those notebooks can be opened in Colaboratory, Google’s Jupyter based service, with a single click from the file in the repository. Of course one can still use the tried and true Python shell as well as sophisticated new IDE’s like Visual Studio Code.
All of this means that while Python has been around over 30 years, and The Quick Python Book for 25, in this edition we have combined the experience and feedback from past editions with the latest features of Python and current tools and presentation. We also would love your feedback, questions, and comments in liveBook discussion forum to help us make this edition the best one in 25 years. As they say, if you see something, say something. Finally, to both new readers and old friends of The Quick Python Book, thank you so much for checking out this MEAP edition. —Naomi Ceder In this book welcome 1 About Python 2 Getting started 3 The Quick Python overview 4 The absolute basics 5 Lists, tuples, and sets 6 Strings 7 Dictionaries 8 Control flow
1 About Python This chapter covers Why use Python? What Python does well What Python is improving This book is intended to help people get a solid general understanding of Python as quickly as possible, avoiding getting bogged down in advanced topics, but covering the essentials to write and read Python code. In particular, this book is intended for people are coming to Python from other languages and those who know a bit of Python are looking to level up their skills as Python continues to gain popularity, particularly in areas like data science, machine learning, and the sciences. While no prior knowledge of Python is needed, some knowledge and experience with programming is necessary to get the most out of this book. After introducing Python and offering some advice on getting started with a Python environment, there is a quick summary of Python’s syntax, followed by chapters that build from the built-in data types up through creating functions, classes, and packages, as well as some more advanced features and a case study in handling data. With the rise of AI tools based on Large Language Models (LLM’s) it is now possible to generate increasing amounts of usable code if (and it’s a big “if”) one has enough knowledge of coding to guide the process intelligently. While this book is not a tutorial on AI and its use in code generation, in the coding problems posed at the end of each chapter starting with chapter 5, there will also be examples of AI responses to the same questions along with a brief discussion of what the AI got right (and wrong). This will help build an understanding of how to approach using AI tools to generate code that actually works. Read the rest of this chapter if you want to know how Python compares to
other languages and its place in the grand scheme of things. If you are interested in the AI tools this book refers to, check out the end of chapter 2 for a bit about those. Skip ahead—go straight to chapter 3—if you already have Python installed and want to start learning Python right away. The information in this chapter is a valid part of this book—but it’s not absolutely necessary for programming with Python. 1.1 Why should I use Python? Hundreds of programming languages are available today, from mature languages like C and C++, to newer entries like Rust, Go, and C#, to enterprise juggernauts like Java, to the more web-oriented JavaScript and Typescript. This abundance of choice makes choosing a programming language difficult. Although no one language is the right choice for every possible situation, I think that Python is a good choice for a large number of programming problems, and it’s also a good choice if you’re learning to program. Millions of programmers around the world use Python, and the number grows every year. Python continues to attract new users for a variety of reasons. It’s a true cross-platform language, running equally well on Windows, Linux/UNIX, and Macintosh platforms, as well as others, ranging from supercomputers to cell phones. It can be used to develop small applications and rapid prototypes, but it scales well to permit development of large programs. It comes with a powerful and easy-to-use graphical user interface (GUI) toolkit, web programming libraries, and more. Python has also become a vital tool for scientific computing and for data science, machine learning, and work with artificial intelligence. And it’s free. 1.2 What Python does well Python is a modern programming language developed by Guido van Rossum in the 1990s (and named after a famous comedic troupe). Although Python isn’t perfect for every application, its strengths make it a good choice for many situations.
1.2.1 Python is easy to use Programmers familiar with traditional languages will find it easy to learn Python. All of the familiar constructs—loops, conditional statements, arrays, and so forth—are included, but many are easier to use in Python. Here are a few of the reasons why: Types are associated with objects, not variables. A variable can be assigned a value of any type, and a list can contain objects of many types. This also means that type casting usually isn’t necessary and that your code isn’t locked into the straitjacket of predeclared types. But while types are not required for variables, Python does allow type hints that allow developers to check that their code is consistent in the type of object used for parameters, return values, etc. Python typically operates at a much higher level of abstraction. This is partly the result of the way the language is built and partly the result of an extensive standard code library that comes with the Python distribution. A program to download a web page can be written in two or three lines! Syntax rules are very simple. Although becoming an expert Pythonista takes time and effort, even beginners can absorb enough Python syntax to write useful code quickly. Python is well suited for rapid application development. It isn’t unusual for coding an application in Python to take one-fifth the time it would in C or Java and to take as little as one-fifth the number of lines of the equivalent C program. This depends on the particular application, of course; for a numerical algorithm performing mostly integer arithmetic in for loops, there would be much less of a productivity gain. For the average application, the productivity gain can be significant. 1.2.2 Python is expressive Python is a very expressive language. Expressive in this context means that a single line of Python code can do more than a single line of code in most other languages. The advantages of a more expressive language are obvious: The fewer lines of code you have to write, the faster you can complete the
project. The fewer lines of code there are, the easier the program will be to maintain and debug. To get an idea of how Python’s expressiveness can simplify code, consider swapping the values of two variables, var1 and var2. In a language like Java, this requires three lines of code and an extra variable: int temp = var1; var1 = var2; var2 = temp; The variable temp is needed to save the value of var1 when var2 is put into it, and then that saved value is put into var2. The process isn’t terribly complex, but reading those three lines and understanding that a swap has taken place takes a certain amount of overhead, even for experienced coders. By contrast, Python lets you make the same swap in one line and in a way that makes it obvious that a swap of values has occurred: var2, var1 = var1, var2 Of course, this is a very simple example, but you find the same advantages throughout the language. 1.2.3 Python is readable Another advantage of Python is that it’s easy to read. You might think that a programming language needs to be read only by a computer, but humans have to read your code as well: whoever debugs your code (quite possibly you), whoever maintains your code (could be you again), and whoever might want to modify your code in the future. In all of those situations, the easier the code is to read and understand, the better it is. The easier code is to understand, the easier it is to debug, maintain, and modify. Python’s main advantage in this department is its use of indentation. Unlike most languages, Python insists that blocks of code be indented. Although this strikes some people as odd, it has the benefit that your code is always formatted in a very easy-to-read style.
Following are two short programs, one written in Perl and one in Python. Both take two equal-size lists of numbers and return the pairwise sum of those lists. I think the Python code is more readable than the Perl code; it’s visually cleaner and contains fewer inscrutable symbols: # Perl version. sub pairwise_sum { my($arg1, $arg2) = @_; my @result; for(0 .. $#$arg1) { push(@result, $arg1->[$_] + $arg2->[$_]); } return(\@result); } # Python version. def pairwise_sum(list1, list2): result = [] for i in range(len(list1)): result.append(list1[i] + list2[i]) return result Both pieces of code do the same thing, but the Python code wins in terms of readability. (There are other ways to do this in Perl, of course, some of which are much more concise—but in my opinion harder to read—than the one shown.) 1.2.4 Python is complete—“batteries included” Another advantage of Python is its “batteries included” philosophy when it comes to libraries. The idea is that when you install Python, you should have everything you need to do real work without the need to install additional libraries. This is why the Python standard library comes with modules for handling email, web pages, databases, operating-system calls, GUI development, and more. For example, with Python, you can write a web server to share the files in a directory with just two lines of code: import http.server http.server.test(HandlerClass=http.server.SimpleHTTPRequestHandler)
There’s no need to install libraries to handle network connections and HTTP; it’s already in Python, right out of the box. 1.2.5 Python has a rich ecosystem of third party libraries While Python is “batteries included”, there are still many situations where one needs to go beyond even a well-stocked standard library - a specialized task, a new data format, more complex applications, and so on. Here Python has really come to the forefront over the past decade. In many areas, from web applications and APIs to data handling and visualization, to machine learning and data science and more, Python has one of the richest ecosystems of packages, libraries, and frameworks of any current language. It’s very unlikely that you’ll find yourself in a situation where there are no Python packages to meet your needs. 1.2.6 Python is cross-platform Python is also an excellent cross-platform language. Python runs on many platforms: Windows, Mac, Linux, UNIX, and so on. Because it’s interpreted, the same code can run on any platform that has a Python interpreter, and almost all current platforms have one. There are even versions of Python that run on Java (Jython), .NET (IronPython), and microcontrollers (MicroPython and CircuitPython), giving you even more possible platforms that run Python. 1.2.7 Python is free Python is also free. Python was originally, and continues to be, developed under the open-source model, and it’s freely available. You can download and install practically any version of Python and use it to develop software for commercial or personal applications, and you don’t need to pay a dime. Although attitudes are changing, some people are still leery of free software because of concerns about a lack of support, fearing that they lack the clout of paying customers. But Python is used by many established companies as a key part of their business; Google, Rackspace, Industrial Light & Magic, and Honeywell are just a few examples. These companies and many others know Python for what it is: a very stable, reliable, and well-supported product with
an active and knowledgeable user community. You’ll get an answer to even the most difficult Python question more quickly in various Python internet forums than you will on most tech-support phone lines, and the Python answer will be free and correct. Python and open-source software Not only is Python free of cost, but also, its source code is freely available, and you’re free to modify, improve, and extend it if you want. Because the source code is freely available, you have the ability to go in yourself and change it (or to hire someone to go in and do so for you). You rarely have this option at any reasonable cost with proprietary software. If this is your first foray into the world of open-source software, you should understand that you’re not only free to use and modify Python, but also able (and encouraged) to contribute to it and improve it. Depending on your circumstances, interests, and skills, those contributions might be financial, as in a donation to the Python Software Foundation (PSF), or they may involve participating in one of the special interest groups (SIGs), testing and giving feedback on releases of the Python core or one of the auxiliary modules, or contributing some of what you or your company develops back to the community. The level of contribution (if any) is, of course, up to you; but if you’re able to give back, definitely consider doing so. Something of significant value is being created here, and you have an opportunity to add to it. Python has a lot going for it: expressiveness, readability, rich included libraries, and cross-platform capabilities. Also, it’s open source. What’s the catch? 1.3 What Python is improving Although Python has many advantages, no language can do everything, so Python isn’t the perfect solution for all your needs. While Python is improving in all of the following areas, to decide whether it is the right language for your situation, you also need to consider these areas where Python doesn’t do as well.
1.3.1 Python is getting faster A possible drawback with Python is its speed of execution. It isn’t a fully compiled language. Instead, it’s first compiled to an internal bytecode form, which is then executed by a Python interpreter. There are some tasks, such as string parsing using regular expressions, for which Python has efficient implementations and is as fast as, or faster than, any C program you’re likely to write. Nevertheless, most of the time, using Python results in slower programs than in a language like C. But you should keep this in perspective. Modern computers have so much computing power that for the vast majority of applications, the speed of the program isn’t as important as the speed of development, and Python programs can typically be written much more quickly. In addition, it’s easy to extend Python with modules written in C or C++, which can be used to run the CPU-intensive portions of a program. Python’s core developers are also hard at work in creating new versions of Python that are more efficient, load and run faster, and take better advantage of multiple processor cores. This work has already yielded significant improvements in performance, and the work will continue in the future, so if you have a performance critical application, you may want to consider carefully if Python will do the job, but you don’t need to write it off immediately. 1.3.2 Python doesn’t enforce variable types at compile time Unlike in some languages, Python’s variables don’t work like containers; instead, they’re more like labels that refer to various objects: integers, strings, class instances, whatever. That means that although those objects themselves have types, the variables referring to them aren’t bound to that particular type. It’s possible (if not necessarily desirable) to use the variable x to refer to a string in one line and an integer in another (Note: output of the code is in bold): x = "2" x '2' #A
x = int(x) x 2 #B The fact that Python associates types with objects and not with variables means that the interpreter doesn’t help you catch variable type mismatches. If you intend a variable count to hold an integer, Python won’t complain if you assign the string "two" to it. Traditional coders count this as a disadvantage, because you lose an additional free check on your code. In response to this concern Python has added syntax and tools to allow coders to specify the desired type of the object a variable refers to, as well as function parameters and return values and the like. With these type hints, as they are called, various tools can flag any inconsistencies in the types of objects before runtime. In smaller programs type errors\ usually aren’t hard to find and fix even without type hints, and in any case Python’s testing features makes avoiding type errors manageable. Many Python programmers feel that the flexibility of dynamic typing more than outweighs any advantage mandatory variable typing might offer. 1.3.3 Python is improving mobile support In the past decade the numbers and types of mobile devices have exploded, and smartphones, tablets, phablets, Chromebooks, and more are everywhere, running on a variety of operating systems. Python isn’t a strong player in this space, but various projects are working on the issue, developing toolkits and frameworks that allow writing apps for both IOS and Android platforms. This situation is improving, but at this writing using Python to write and distribute commercial apps is a bit of a pain. 1.3.4 Python is improving support for multiple processors Multiple-core processors are everywhere now, producing significant increases in performance in many situations. However, the standard implementation of Python isn’t designed to use multiple cores, due to a feature called the global interpreter lock (GIL). As mentioned above when talking about speed, Python’s development team is currently working on
ways to make Python work more seamlessly and efficiently with multiple processor cores. We will discuss such features in the advanced features section of this book, and the development of multi-core Python will continue over the next several years. 1.4 Summary Python is a modern, high-level language with dynamic typing and simple, consistent syntax and semantics. Python is multiplatform, highly modular, and suited for both rapid development and large-scale programming. It’s reasonably fast and can be easily extended with C or C++ modules for higher speeds. Python has built-in advanced features such as persistent object storage, advanced hash tables, expandable class syntax, and universal comparison functions. Python includes a wide range of libraries such as numeric processing, image manipulation, user interfaces, and web scripting. It’s supported by a dynamic Python community.
2 Getting started This chapter covers Available Python options Getting started with Colaboratory Accessing the Github repository for this book Writing a simple program and handling errors Using the help() and dir() functions AI tools for generating Python code This chapter gives you a quick survey of the many options for installing and using Python and guides you through getting up and running with Google Colaboratory, a web hosted Python environment. Combined with the code for each chapter, available in a Github repository at https://github.com/nceder/qpb4e, Colaboratory is one of the quickest and easiest ways to get up and running with Python so that you can test out the code examples in the text and work through the labs and exercises throughout the book. 2.1 Paradox of choice - which Python? As Python has matured, particularly over the past ten years, the number of options for running Python has exploded. After a brief survey of the versions, sources, devices, environments, and tools in the Python ecosystem, we’ll look at our recommended solution, Google Colaboratory and how to use it to run the sample code snippets in this book and to write the code for the lab exercises in most of the chapters. 2.1.1 Python versions For many years Python had a somewhat variable release cycle, with new versions of Python being released when the core developers felt there were enough new features to be worth it. From Python 3.1 in 2009 to 3.8 in 2018
new versions were released roughly every 18 months. As Python’s popularity continued to grow, a quicker and more regular cadence for new releases became the goal. So, beginning with version 3.9 the decision was made (recorded in PEP 602 – Annual Release Cycle for Python) to move to an annual release cycle, with a release every October. The current release schedule for Python means that after the October, 2024 release of version 3.13, version 3.14 will come out in October, 2025, and so on. At this writing, Python 3.12 is the most current version, and 3.13 is being readied for release in a few months. Since the features of 3.13 have already been frozen, we have included the new features of 3.13 and we have tested the code on both 3.12 and the beta of 3.13. Choosing a Python version Having a new version of Python come out every year is a good thing for releasing new features, but it’s not always the most convenient thing for anyone who needs to test and deploy a new version of the language. Because of this, versions of Python are officially supported for a total of 5 years - the first 2 years with full releases, and then 3 years with source code only releases of security fixes. While it’s usually preferable to have the latest version, any supported version (3.9 or later as of this writing) should be fine to use with this book. If you have an earlier version, there will be a few new features that you won’t have, but you can still do a lot of work without upgrading. 2.1.2 Sources of Python The classic way to get Python is from the source, downloading and installing a version from the Python Sofware Foundation’s web site at https://www.python.org/downloads/. There you can find installers for several operating systems and platforms, and versions going back to the very beginnings of Python over 30 years ago. It’s possible, however, that the exact version you need or want isn’t on python.org. You can also get a data science oriented distribution of Python from Anaconda at https://www.anaconda.com/download/, or you may be able to use the app
store or package manager of you operating system to install Python. If you are into the technical details, you can also fork the source code repository on Github and download and compile the source yourself. The choice depends on your preferences and your situation, and since the solution we recommend doesn’t require a local install, you can wait to make that decision until you know Python a bit better. 2.1.3 Devices, platforms, and operating systems You can run Python on a wide variety of devices and on many operating systems. While in the early days, a server or desktop computer was the norm, today Python runs on many processors, from embedded devices and single board computers to phones and tablets, to chromebooks, laptops, and desktops, to virtual machines and containers, to server clusters, and so on. While the most common implementation of Python is based on the C language, there are versions that run on Java, in the browser based on WASM, or even in applications like Excel. 2.1.4 Environments and tools There are also a number of ways that you can run and develop code in Python. It’s possible to run the Python interpreter from a command line and interact using either the built in shell or an enhanced shell like ipython and to write code in the text editor of your choice. You can also use education- oriented IDE’s like IDLE (provided with Python), Mu, or Thonny, or you can opt for more advanced Python IDE’s like VSCode, Wingware, or PyCharm. Of course, in all of those categories there are too many other fine options to list. Another option for using and writing Python combines features of the ipython shell with a web interface and is called Jupyter. Jupyter runs on a server and is accessed via browser, and its web interface allows you combine text (formatted using Markdown) with cells for executing code in a “notebook.” The combination has proved to be so useful that Jupyter notebooks are increasingly popular for teaching, data exploration and data science, AI experimentation, and many other uses. While you can run your own Jupyter server locally, it’s even more convenient to use a server hosted in the cloud,
which brings us to our recommendation for this book. 2.2 Colaboratory - Jupyter notebooks in the cloud As mentioned at the beginning of this chapter, for this book I recommend using Jupyter notebooks, specifically the hosted version of Jupyter from Google, Colaboratory. Using Colaboratory means that you don’t need to worry about installing (or updating) Python, and you can take advantage of Jupyter’s friendly interface, which is becoming increasingly popular, particularly for data science. Another advantage of Colaboratory is that you can launch a session with one of the code notebooks from this book’s source repository on Github with a single click, and you can access it on virtually any device that has a modern web browser. For that reason, in this book we’ll present sample code and problem solutions in Jupyter notebooks. Of course, the code will still work in other environments, and we’ll provide text files of the code as well, but unless stated otherwise, you can assume that the code presented is in notebook form. 2.2.1 Getting the source notebooks The simplest way to get started with Colaboratory and this book is by accessing a notebook in the Github repository. If you are not familiar with Github, it’s a very popular online version control service based on the version control tool git. To access the notebooks in the repository you don’t need to know how to use git, nor do you need to have an account on Github, just following the links below will get you started. You can find the Github repository at https://github.com/nceder/qpb4e/tree/main and the notebooks for each chapter are in separate directories inside the code directory. To get started, let’s find and open the notebook for chapter 2 (this chapter). If you look in the Chapter 02 directory, you will find a notebook file called Chapter_02.ipynb (direct link at https://github.com/nceder/qpb4e/blob/main/code/Chapter%2002/Chapter_02.ipynb
Figure 2.1 Github repository, showing Chapter_02 notebook. 2.2.2 Getting started with Colaboratory If you click on the Chapter_02.ipynb file, you can view its contents using Github’s viewer, and at the top of the page you should also see a link to “Open in Colab.” Figure 2.2 Chapter_02.ipynb notebook viewed in Github. If you click that link it will open that notebook in a Colaboratory session
Comments 0
Loading comments...
Reply to Comment
Edit Comment