Explore 1.5M+ audiobooks & ebooks free for days

From $11.99/month after trial. Cancel anytime.

Python Crash Course, 3rd Edition: A Hands-On, Project-Based Introduction to Programming
Python Crash Course, 3rd Edition: A Hands-On, Project-Based Introduction to Programming
Python Crash Course, 3rd Edition: A Hands-On, Project-Based Introduction to Programming
Ebook1,446 pages13 hours

Python Crash Course, 3rd Edition: A Hands-On, Project-Based Introduction to Programming

Rating: 4 out of 5 stars

4/5

()

Read preview

About this ebook

Python Crash Course is the world’s bestselling programming book, with over 1,500,000 copies sold to date!

Python Crash Course is the world’s best-selling guide to the Python programming language. This fast-paced, thorough introduction will have you writing programs, solving problems, and developing functioning applications in no time.

You’ll start by learning basic programming concepts, such as variables, lists, classes, and loops, and practice writing clean code with exercises for each topic. You’ll also learn how to make your programs interactive and test your code safely before adding it to a project. You’ll put your new knowledge into practice by creating a Space Invaders–inspired arcade game, building a set of data visualizations with Python’s handy libraries, and deploying a simple application online.

As you work through the book, you’ll learn how to:
  • Use powerful Python libraries and tools, including pytest, Pygame, Matplotlib, Plotly, and Django
  • Make increasingly complex 2D games that respond to keypresses and mouse clicks
  • Generate interactive data visualizations using a variety of datasets
  • Build apps that allow users to create accounts and manage their own data, and deploy your apps online 
  • Troubleshoot coding errors and solve common programming problems

New to this edition: This third edition is completely revised to reflect the latest in Python code. New and updated coverage includes VS Code for text editing, the pathlib module for file handling, pytest for testing your code, as well as the latest features of Matplotlib, Plotly, and Django.

If you’ve been thinking about digging into programming, Python Crash Course will provide you with the skills to write real programs fast. Why wait any longer? Start your engines and code!

Covers Python 3.x
LanguageEnglish
PublisherNo Starch Press
Release dateJan 10, 2023
ISBN9781718502710
Python Crash Course, 3rd Edition: A Hands-On, Project-Based Introduction to Programming

Related to Python Crash Course, 3rd Edition

Related ebooks

Programming For You

View More

Reviews for Python Crash Course, 3rd Edition

Rating: 4.078947294736842 out of 5 stars
4/5

19 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Python Crash Course, 3rd Edition - Eric Matthes

    Praise for Python Crash Course

    "It has been interesting to see No Starch Press producing future classics that should be alongside the more traditional programming books. Python Crash Course is one of those books."

    —Greg Laden, ScienceBlogs

    Deals with some rather complex projects and lays them out in a consistent, logical, and pleasant manner that draws the reader into the subject.

    Full Circle Magazine

    Well presented with good explanations of the code snippets. The book works with you, one small step at a time, building more complex code, explaining what’s going on all the way.

    —FlickThrough Reviews

    "Learning Python with Python Crash Course was an extremely positive experience! A great choice if you’re new to Python."

    —Mikke Goes Coding

    Does what it says on the tin, and does it really well. . . . Presents a large number of useful exercises as well as three challenging and entertaining projects.

    —RealPython.com

    "A fast-paced but comprehensive introduction to programming with Python, Python Crash Course is another superb book to add to your library and help you finally master Python."

    —TutorialEdge.net

    A brilliant option for complete beginners without any coding experience. If you’re looking for a solid, uncomplicated intro to this very deep language, I have to recommend this book.

    —WhatPixel.com

    Contains literally everything you need to know about Python and even more.

    —FireBearStudio.com

    "While Python Crash Course uses Python to teach you to code, it also teaches clean programming skills that apply to most other languages."

    —Great Lakes Geek

    Python Crash Course

    3RD EDITION

    A Hands-On, Project-Based Introduction to Programming

    by Eric Matthes

    San Francisco

    PYTHON CRASH COURSE, 3RD EDITION. Copyright © 2023 by Eric Matthes.

    All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.

    Fourth printing

    27 26 25 24 23     4 5 6 7 8

    ISBN-13: 978-1-7185-0270-3 (print)

    ISBN-13: 978-1-7185-0271-0 (ebook)

    NSP

    Publisher: William Pollock

    Managing Editor: Jill Franklin

    Production Editor: Jennifer Kepler

    Developmental Editor: Eva Morrow

    Cover Illustrator: Josh Ellingson

    Interior Design: Octopod Studios

    Technical Reviewer: Kenneth Love

    Copyeditor: Doug McNair

    Compositor: Jeff Lytle, Happenstance Type-O-Rama

    Proofreader: Scout Festa

    The Library of Congress has catalogued the first edition as follows:

    Matthes, Eric, 1972-

      Python crash course : a hands-on, project-based introduction to programming / by Eric Matthes.

           pages cm

      Includes index.

      Summary: A project-based introduction to programming in Python, with exercises. Covers general programming concepts, Python fundamentals, and problem solving. Includes three projects - how to create a simple video game, use data visualization techniques to make graphs and charts, and build an interactive web application-- Provided by publisher.

      ISBN 978-1-59327-603-4 -- ISBN 1-59327-603-6

      1. Python (Computer program language) I. Title.

      QA76.73.P98M38 2015

      005.13'3--dc23

                         2015018135

    For customer service inquiries, please contact [email protected]. For information on distribution, bulk sales, corporate sales, or translations: [email protected]. For permission to translate this work: [email protected]. To report counterfeit copies or piracy: [email protected].

    No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.

    The information in this book is distributed on an As Is basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.

    For my father, who always made time to answer my questions about programming, and for Ever, who is just beginning to ask me his questions

    About the Author

    Eric Matthes was a high school math and science teacher for 25 years, and he taught introductory Python classes whenever he could find a way to fit them into the curriculum. Eric is a full-time writer and programmer now, and he is involved in a number of open source projects. His projects have a diverse range of goals, from helping predict landslide activity in mountainous regions to simplifying the process of deploying Django projects. When he’s not writing or programming, he enjoys climbing mountains and spending time with his family.

    About the Technical Reviewer

    Kenneth Love lives in the Pacific Northwest with their family and cats. Kenneth is a longtime Python programmer, open source contributor, teacher, and conference speaker.

    Preface to the Third Edition

    The response to the first and second editions of Python Crash Course has been overwhelmingly positive. More than one million copies are in print, including translations in over 10 languages. I’ve received letters and emails from readers as young as 10, as well as from retirees who want to learn to program in their free time. Python Crash Course is being used in middle schools and high schools, and also in college classes. Students who are assigned more advanced textbooks are using Python Crash Course as a companion text for their classes and finding it a worthwhile supplement. People are using it to enhance their skills on the job, change careers, and start working on their own side projects. In short, people are using the book for the full range of purposes I had hoped they would, and much more.

    The opportunity to write a third edition of Python Crash Course has been thoroughly enjoyable. Although Python is a mature language, it continues to evolve as every language does. My main goal in revising the book is to keep it a well-curated introductory Python course. By reading this book, you’ll learn everything you need to start working on your own projects, and you’ll build a solid foundation for all of your future learning as well. I’ve updated some sections to reflect newer, simpler ways of doing things in Python. I’ve also clarified some sections where certain details of the language were not presented as accurately as they could have been. All the projects have been completely updated using popular, well-maintained libraries that you can confidently use to build your own projects.

    The following is a summary of specific changes that have been made in the third edition:

    Chapter 1 now features the text editor VS Code, which is popular among beginner and professional programmers and works well on all operating systems.

    Chapter 2 includes the new methods removeprefix() and removesuffix(), which are helpful when working with files and URLs. This chapter also features Python’s newly improved error messages, which provide much more specific information to help you troubleshoot your code when something goes wrong.

    Chapter 10 uses the pathlib module for working with files. This is a much simpler approach to reading from and writing to files.

    Chapter 11 uses pytest to write automated tests for the code you write. The pytest library has become the industry standard tool for writing tests in Python. It’s friendly enough to use for your first tests, and if you pursue a career as a Python programmer, you’ll use it in professional settings as well.

    The Alien Invasion project in Chapters 12−14 includes a setting to control the frame rate, which makes the game run more consistently across different operating systems. A simpler approach is used to build the fleet of aliens, and the overall organization of the project has been cleaned up as well.

    The data visualization projects in Chapters 15–17 use the most recent features of Matplotlib and Plotly. The Matplotlib visualizations feature updated style settings. The random walk project has a small improvement that increases the accuracy of the plots, which means you’ll see a wider variety of patterns emerge each time you generate a new walk. All the projects featuring Plotly now use the Plotly Express module, which lets you generate your initial visualizations with just a few lines of code. You can easily explore a variety of visualizations before committing to one kind of plot, and then focus on refining individual elements of that plot.

    The Learning Log project in Chapters 18−20 is built using the latest version of Django and styled using the latest version of Bootstrap. Some parts of the project have been renamed to make it easier to follow the overall organization of the project. The project is now deployed to Platform.sh, a modern hosting service for Django projects. The deployment process is controlled by YAML configuration files, which give you a great deal of control over how your project is deployed. This approach is consistent with how professional programmers deploy modern Django projects.

    Appendix A has been fully updated to recommend current best practices for installing Python on all major operating systems. Appendix B includes detailed instructions for setting up VS Code, and brief descriptions of most of the major text editors and IDEs in current use. Appendix C directs readers to several of the most popular online resources for getting help. Appendix D continues to offer a mini crash course in using Git for version control. Appendix E is brand new for the third edition. Even with a good set of instructions for deploying the apps you create, there are many things that can go wrong. This appendix offers a detailed troubleshooting guide that you can use when the deployment process doesn’t work on the first try.

    The index has been thoroughly updated to allow you to use Python Crash Course as a reference for all of your future Python projects.

    Thank you for reading Python Crash Course! If you have any feedback or questions, please feel free to get in touch; I am @ehmatthes on Twitter.

    Acknowledgments

    This book would not have been possible without the wonderful and extremely professional staff at No Starch Press. Bill Pollock invited me to write an introductory book, and I deeply appreciate that original offer. Liz Chadwick has worked on all three editions, and the book is better because of her ongoing involvement. Eva Morrow brought fresh eyes to this new edition, and her insights have improved the book as well. I appreciate Doug McNair’s guidance in using proper grammar, without becoming overly formal. Jennifer Kepler has supervised the production work, which turns my many files into a polished final product.

    There are many people at No Starch Press who have helped make this book a success but whom I haven’t had the chance to work with directly. No Starch has a fantastic marketing team, who go beyond just selling books; they make sure readers find the books that are likely to work well for them and help them reach their goals. No Starch also has a strong foreign-rights department. Python Crash Course has reached readers around the world, in many languages, due to the diligence of this team. To all of these people whom I haven’t worked with individually, thank you for helping Python Crash Course find its audience.

    I’d like to thank Kenneth Love, the technical reviewer for all three editions of Python Crash Course. I met Kenneth at PyCon one year, and their enthusiasm for the language and the Python community has been a constant source of professional inspiration ever since. Kenneth, as always, went beyond simple fact-checking and reviewed the book with the goal of helping newer programmers develop a solid understanding of the Python language and programming in general. They also kept an eye out for areas that worked well enough in previous editions but could be improved upon, given the opportunity for a full rewrite. That said, any inaccuracies that remain are completely my own.

    I’d also like to express my appreciation to all the readers who have shared their experience of working through Python Crash Course. Learning the basics of programming can change your perspective on the world, and sometimes this has a profound impact on people. It’s deeply humbling to hear these stories, and I appreciate everyone who has shared their experiences so openly.

    I’d like to thank my father for introducing me to programming at a young age and for not being afraid that I’d break his equipment. I’d like to thank my wife, Erin, for supporting and encouraging me through the writing of this book, and through all the work that goes into maintaining it through multiple editions. I’d also like to thank my son, Ever, whose curiosity continues to inspire me.

    Introduction

    Every programmer has a story about how they learned to write their first program. I started programming as a child, when my father was working for Digital Equipment Corporation, one of the pioneering companies of the modern computing era. I wrote my first program on a kit computer that my dad had assembled in our basement. The computer consisted of nothing more than a bare motherboard connected to a keyboard without a case, and its monitor was a bare cathode ray tube. My initial program was a simple number guessing game, which looked something like this:

    I'm thinking of a number! Try to guess the number I'm thinking of: 25

     

    Too low! Guess again:

    50

     

    Too high! Guess again:

    42

     

    That's it! Would you like to play again? (yes/no)

    no

     

    Thanks for playing!

    I’ll always remember how satisfied I felt, watching my family play a game that I created and that worked as I intended it to.

    That early experience had a lasting impact. There’s real satisfaction in building something with a purpose, that solves a problem. The software I write now meets more significant needs than my childhood efforts did, but the sense of satisfaction I get from creating a program that works is still largely the same.

    Who Is This Book For?

    The goal of this book is to bring you up to speed with Python as quickly as possible so you can build programs that work—games, data visualizations, and web applications—while developing a foundation in programming that will serve you well for the rest of your life. Python Crash Course is written for people of any age who have never programmed in Python or have never programmed at all. This book is for those who want to learn the basics of programming quickly so they can focus on interesting projects, and those who like to test their understanding of new concepts by solving meaningful problems. Python Crash Course is also perfect for teachers at all levels who want to offer their students a project-based introduction to programming. If you’re taking a college class and want a friendlier introduction to Python than the text you’ve been assigned, this book can make your class easier as well. If you’re looking to change careers, Python Crash Course can help you make the transition into a more satisfying career track. It has worked well for a wide variety of readers, with a broad range of goals.

    What Can You Expect to Learn?

    The purpose of this book is to make you a good programmer in general and a good Python programmer in particular. You’ll learn efficiently and adopt good habits as you gain a solid foundation in general programming concepts. After working your way through Python Crash Course, you should be ready to move on to more advanced Python techniques, and your next programming language will be even easier to grasp.

    In Part I of this book, you’ll learn basic programming concepts you need to know to write Python programs. These concepts are the same as those you’d learn when starting out in almost any programming language. You’ll learn about different kinds of data and the ways you can store data in your programs. You’ll build collections of data, such as lists and dictionaries, and you’ll work through those collections in efficient ways. You’ll learn to use while loops and if statements to test for certain conditions, so you can run specific sections of code while those conditions are true and run other sections when they’re not—a technique that helps you automate many processes.

    You’ll learn to accept input from users to make your programs interactive, and to keep your programs running as long as the user wants. You’ll explore how to write functions that make parts of your program reusable, so you only have to write blocks of code that perform certain actions once, while using that code as many times as you need. You’ll then extend this concept to more complicated behavior with classes, making fairly simple programs respond to a variety of situations. You’ll learn to write programs that handle common errors gracefully. After working through each of these basic concepts, you’ll write a number of increasingly complex programs using what you’ve learned. Finally, you’ll take your first step toward intermediate programming by learning how to write tests for your code, so you can develop your programs further without worrying about introducing bugs. All the information in Part I will prepare you for taking on larger, more complex projects.

    In Part II, you’ll apply what you learned in Part I to three projects. You can do any or all of these projects, in whichever order works best for you. In the first project, in Chapters 12–14, you’ll create a Space Invaders–style shooting game called Alien Invasion, which includes several increasingly difficult levels of game play. After you’ve completed this project, you should be well on your way to being able to develop your own 2D games. Even if you don’t aspire to become a game programmer, working through this project is an enjoyable way to tie together much of what you’ll learn in Part I.

    The second project, in Chapters 15–17, introduces you to data visualization. Data scientists use a variety of visualization techniques to help make sense of the vast amount of information available to them. You’ll work with datasets that you generate through code, datasets that you download from online sources, and datasets your programs download automatically. After you’ve completed this project, you’ll be able to write programs that sift through large datasets and make visual representations of many different kinds of information.

    In the third project, in Chapters 18–20, you’ll build a small web application called Learning Log. This project allows you to keep an organized journal of information you’ve learned about a specific topic. You’ll be able to keep separate logs for different topics and allow others to create an account and start their own journals. You’ll also learn how to deploy your project so anyone can access it online, from anywhere in the world.

    Online Resources

    No Starch Press has more information about this book available online at https://nostarch.com/python-crash-course-3rd-edition.

    I also maintain an extensive set of supplementary resources at https://ehmatthes.github.io/pcc_3e. These resources include the following:

    Setup instructions The setup instructions online are identical to what’s in the book, but they include active links you can click for all the different steps. If you’re having any setup issues, refer to this resource.

    Updates Python, like all languages, is constantly evolving. I maintain a thorough set of updates, so if anything isn’t working, check here to see whether instructions have changed.

    Solutions to exercises You should spend significant time on your own attempting the exercises in the Try It Yourself sections. However, if you’re stuck and can’t make any progress, solutions to most of the exercises are online.

    Cheat sheets A full set of downloadable cheat sheets for quick reference to major concepts is also online.

    Why Python?

    Every year, I consider whether to continue using Python or move on to a different language, perhaps one that’s newer to the programming world. But I continue to focus on Python for many reasons. Python is an incredibly efficient language: your programs will do more in fewer lines of code than many other languages would require. Python’s syntax will also help you write clean code. Your code will be easier to read, easier to debug, and easier to extend and build upon, compared to other languages.

    People use Python for many purposes: to make games, build web applications, solve business problems, and develop internal tools at all kinds of interesting companies. Python is also used heavily in scientific fields, for academic research and applied work.

    One of the most important reasons I continue to use Python is because of the Python community, which includes an incredibly diverse and welcoming group of people. Community is essential to programmers because programming isn’t a solitary pursuit. Most of us, even the most experienced programmers, need to ask advice from others who have already solved similar problems. Having a well-connected and supportive community is critical to helping you solve problems, and the Python community is fully supportive of people who are learning Python as their first programming language or coming to Python with a background in other languages.

    Python is a great language to learn, so let’s get started!

    Part I

    Basics

    Part I of this book teaches you the basic concepts you’ll need to write Python programs. Many of these concepts are common to all programming languages, so they’ll be useful throughout your life as a programmer.

    In Chapter 1 you’ll install Python on your computer and run your first program, which prints the message Hello world! to the screen.

    In Chapter 2 you’ll learn to assign information to variables and work with text and numerical values.

    Chapters 3 and 4 introduce lists. Lists can store as much information as you want in one place, allowing you to work with that data efficiently. You’ll be able to work with hundreds, thousands, and even millions of values in just a few lines of code.

    In Chapter 5 you’ll use if statements to write code that responds one way if certain conditions are true, and responds in a different way if those conditions are not true.

    Chapter 6 shows you how to use Python’s dictionaries, which let you make connections between different pieces of information. Like lists, dictionaries can contain as much information as you need to store.

    In Chapter 7 you’ll learn how to accept input from users to make your programs interactive. You’ll also learn about while loops, which run blocks of code repeatedly as long as certain conditions remain true.

    In Chapter 8 you’ll write functions, which are named blocks of code that perform a specific task and can be run whenever you need them.

    Chapter 9 introduces classes, which allow you to model real-world objects. You’ll write code that represents dogs, cats, people, cars, rockets, and more.

    Chapter 10 shows you how to work with files and handle errors so your programs won’t crash unexpectedly. You’ll store data before your program closes and read the data back in when the program runs again. You’ll learn about Python’s exceptions, which allow you to anticipate errors and make your programs handle those errors gracefully.

    In Chapter 11 you’ll learn to write tests for your code, to check that your programs work the way you intend them to. As a result, you’ll be able to expand your programs without worrying about introducing new bugs. Testing your code is one of the first skills that will help you transition from beginner to intermediate programmer.

    1

    Getting Started

    In this chapter, you’ll run your first Python program, hello_world.py. First, you’ll need to check whether a recent version of Python is installed on your computer; if it isn’t, you’ll install it. You’ll also install a text editor to work with your Python programs. Text editors recognize Python code and highlight sections as you write, making it easy to understand your code’s structure.

    Setting Up Your Programming Environment

    Python differs slightly on different operating systems, so you’ll need to keep a few considerations in mind. In the following sections, we’ll make sure Python is set up correctly on your system.

    Python Versions

    Every programming language evolves as new ideas and technologies emerge, and the developers of Python have continually made the language more versatile and powerful. As of this writing, the latest version is Python 3.11, but everything in this book should run on Python 3.9 or later. In this section, we’ll find out if Python is already installed on your system and whether you need to install a newer version. Appendix A contains additional details about installing the latest version of Python on each major operating system as well.

    Running Snippets of Python Code

    You can run Python’s interpreter in a terminal window, allowing you to try bits of Python code without having to save and run an entire program.

    Throughout this book, you’ll see code snippets that look like this:

    >>> print(Hello Python interpreter!)

     

    Hello Python interpreter!

    The three angle brackets (>>>) prompt, which we’ll refer to as a Python prompt, indicates that you should be using the terminal window. The bold text is the code you should type in and then execute by pressing ENTER. Most of the examples in this book are small, self-contained programs that you’ll run from your text editor rather than the terminal, because you’ll write most of your code in the text editor. But sometimes, basic concepts will be shown in a series of snippets run through a Python terminal session to demonstrate particular concepts more efficiently. When you see three angle brackets in a code listing, you’re looking at code and output from a terminal session. We’ll try coding in the interpreter on your system in a moment.

    We’ll also use a text editor to create a simple program called Hello World! that has become a staple of learning to program. There’s a long-held tradition in the programming world that printing the message Hello world! to the screen as your first program in a new language will bring you good luck. Such a simple program serves a very real purpose. If it runs correctly on your system, then any Python program you write should work as well.

    About the VS Code Editor

    VS Code is a powerful, professional-quality text editor that’s free and beginner-friendly. VS Code is great for both simple and complex projects, so if you become comfortable using it while learning Python, you can continue using it as you progress to larger and more complicated projects. VS Code can be installed on all modern operating systems, and it supports most programming languages, including Python.

    Appendix B provides information on other text editors. If you’re curious about the other options, you might want to skim that appendix at this point. If you want to begin programming quickly, you can use VS Code to start. Then you can consider other editors, once you’ve gained some experience as a programmer. In this chapter, I’ll walk you through installing VS Code on your operating system.

    Note

    If you already have a text editor installed and you know how to configure it to run Python programs, you are welcome to use that editor instead.

    Python on Different Operating Systems

    Python is a cross-platform programming language, which means it runs on all the major operating systems. Any Python program you write should run on any modern computer that has Python installed. However, the methods for setting up Python on different operating systems vary slightly.

    In this section, you’ll learn how to set up Python on your system. You’ll first check whether a recent version of Python is installed on your system, and install it if it’s not. Then you’ll install VS Code. These are the only two steps that are different for each operating system.

    In the sections that follow, you’ll run hello_world.py and troubleshoot anything that doesn’t work. I’ll walk you through this process for each operating system, so you’ll have a Python programming environment that you can rely on.

    Python on Windows

    Windows doesn’t usually come with Python, so you’ll probably need to install it and then install VS Code.

    Installing Python

    First, check whether Python is installed on your system. Open a command window by entering command into the Start menu and clicking the Command Prompt app. In the terminal window, enter python in lowercase. If you get a Python prompt (>>>) in response, Python is installed on your system. If you see an error message telling you that python is not a recognized command, or if the Microsoft store opens, Python isn’t installed. Close the Microsoft store if it opens; it’s better to download an official installer than to use Microsoft’s version.

    If Python is not installed on your system, or if you see a version earlier than Python 3.9, you need to download a Python installer for Windows. Go to https://python.org and hover over the Downloads link. You should see a button for downloading the latest version of Python. Click the button, which should automatically start downloading the correct installer for your system. After you’ve downloaded the file, run the installer. Make sure you select the option Add Python to PATH, which will make it easier to configure your system correctly. Figure 1-1 shows this option selected.

    Figure 1-1: Make sure you select the checkbox labeled Add Python to PATH.

    Running Python in a Terminal Session

    Open a new command window and enter python in lowercase. You should see a Python prompt (>>>), which means Windows has found the version of Python you just installed.

    C:\> python

     

    Python 3.

    x.x

    (main, Jun . . . , 13:29:14) [MSC v.1932 64 bit (AMD64)] on win32

    Type help, copyright, credits or license for more information.

    >>>

    Note

    If you don’t see this output or something similar, see the more detailed setup instructions in Appendix A.

    Enter the following line in your Python session:

    >>> print(Hello Python interpreter!)

     

    Hello Python interpreter!

    >>>

    You should see the output Hello Python interpreter! Anytime you want to run a snippet of Python code, open a command window and start a Python terminal session. To close the terminal session, press CTRL-Z and then press ENTER, or enter the command exit().

    Installing VS Code

    You can download an installer for VS Code at https://code.visualstudio.com. Click the Download for Windows button and run the installer. Skip the following sections about macOS and Linux, and follow the steps in Running a Hello World Program on page 9.

    Python on macOS

    Python is not installed by default on the latest versions of macOS, so you’ll need to install it if you haven’t already done so. In this section, you’ll install the latest version of Python, and then install VS Code and make sure it’s configured correctly.

    Note

    Python 2 was included on older versions of macOS, but it’s an outdated version that you shouldn’t use.

    Checking Whether Python 3 Is Installed

    Open a terminal window by going to ApplicationsUtilitiesTerminal. You can also press ⌘-spacebar, type terminal, and then press ENTER. To see if you have a recent enough version of Python installed, enter python3. You’ll most likely see a message about installing the command line developer tools. It’s better to install these tools after installing Python, so if this message appears, cancel the pop-up window.

    If the output shows you have Python 3.9 or a later version installed, you can skip the next section and go to Running Python in a Terminal Session. If you see any version earlier than Python 3.9, follow the instructions in the next section to install the latest version.

    Note that on macOS, whenever you see the python command in this book, you need to use the python3 command instead to make sure you’re using Python 3. On most macOS systems, the python command either points to an outdated version of Python that should only be used by internal system tools, or it points to nothing and generates an error message.

    Installing the Latest Version of Python

    You can find a Python installer for your system at https://python.org. Hover over the Download link, and you should see a button for downloading the latest version of Python. Click the button, which should automatically start downloading the correct installer for your system. After the file downloads, run the installer.

    After the installer runs, a Finder window should appear. Double-click the Install Certificates.command file. Running this file will allow you to more easily install additional libraries that you’ll need for real-world projects, including the projects in the second half of this book.

    Running Python in a Terminal Session

    You can now try running snippets of Python code by opening a new terminal window and typing python3:

    $ python3

     

    Python 3.

    x.x

    (v3.11.0:eb0004c271, Jun . . . , 10:03:01)

    [Clang 13.0.0 (clang-1300.0.29.30)] on darwin

    Type help, copyright, credits or license for more information.

    >>>

    This command starts a Python terminal session. You should see a Python prompt (>>>), which means macOS has found the version of Python you just installed.

    Enter the following line in the terminal session:

    >>> print(Hello Python interpreter!)

     

    Hello Python interpreter!

    >>>

    You should see the message Hello Python interpreter!, which should print directly in the current terminal window. You can close the Python interpreter by pressing CTRL-D or by entering the command exit().

    Note

    On newer macOS systems, you’ll see a percent sign (%) as a terminal prompt instead of a dollar sign ($).

    Installing VS Code

    To install the VS Code editor, you need to download the installer at https://code.visualstudio.com. Click the Download button, and then open a Finder window and go to the Downloads folder. Drag the Visual Studio Code installer to your Applications folder, then double-click the installer to run it.

    Skip over the following section about Python on Linux, and follow the steps in Running a Hello World Program on page 9.

    Python on Linux

    Linux systems are designed for programming, so Python is already installed on most Linux computers. The people who write and maintain Linux expect you to do your own programming at some point, and encourage you to do so. For this reason, there’s very little to install and only a few settings to change to start programming.

    Checking Your Version of Python

    Open a terminal window by running the Terminal application on your system (in Ubuntu, you can press CTRL-ALT-T). To find out which version of Python is installed, enter python3 with a lowercase p. When Python is installed, this command starts the Python interpreter. You should see output indicating which version of Python is installed. You should also see a Python prompt (>>>) where you can start entering Python commands:

    $ python3

     

    Python 3.10.4 (main, Apr  . . . , 09:04:19) [GCC 11.2.0] on linux

    Type help, copyright, credits or license for more information.

    >>>

    This output indicates that Python 3.10.4 is currently the default version of Python installed on this computer. When you’ve seen this output, press CTRL-D or enter exit() to leave the Python prompt and return to a terminal prompt. Whenever you see the python command in this book, enter python3 instead.

    You’ll need Python 3.9 or later to run the code in this book. If the Python version installed on your system is earlier than Python 3.9, or if you want to update to the latest version currently available, refer to the instructions in Appendix A.

    Running Python in a Terminal Session

    You can try running snippets of Python code by opening a terminal and entering python3, as you did when checking your version. Do this again, and when you have Python running, enter the following line in the terminal session:

    >>> print(Hello Python interpreter!)

     

    Hello Python interpreter!

    >>>

    The message should print directly in the current terminal window. Remember that you can close the Python interpreter by pressing CTRL-D or by entering the command exit().

    Installing VS Code

    On Ubuntu Linux, you can install VS Code from the Ubuntu Software Center. Click the Ubuntu Software icon in your menu and search for vscode. Click the app called Visual Studio Code (sometimes called code), and then click Install. Once it’s installed, search your system for VS Code and launch the app.

    Running a Hello World Program

    With a recent version of Python and VS Code installed, you’re almost ready to run your first Python program written in a text editor. But before doing so, you need to install the Python extension for VS Code.

    Installing the Python Extension for VS Code

    VS Code works with many different programming languages; to get the most out of it as a Python programmer, you’ll need to install the Python extension. This extension adds support for writing, editing, and running Python programs.

    To install the Python extension, click the Manage icon, which looks like a gear in the lower-left corner of the VS Code app. In the menu that appears, click Extensions. Enter python in the search box and click the Python extension. (If you see more than one extension named Python, choose the one supplied by Microsoft.) Click Install and install any additional tools that your system needs to complete the installation. If you see a message that you need to install Python, and you’ve already done so, you can ignore this message.

    Note

    If you’re using macOS and a pop-up asks you to install the command line developer tools, click Install. You may see a message that it will take an excessively long time to install, but it should only take about 10 or 20 minutes on a reasonable internet connection.

    Running hello_world.py

    Before you write your first program, make a folder called python_work on your desktop for your projects. It’s best to use lowercase letters and underscores for spaces in file and folder names, because Python uses these naming conventions. You can make this folder somewhere other than the desktop, but it will be easier to follow some later steps if you save the python_work folder directly on your desktop.

    Open VS Code, and close the Get Started tab if it’s still open. Make a new file by clicking FileNew File or pressing CTRL-N (⌘-N on macOS). Save the file as hello_world.py in your python_work folder. The extension .py tells VS Code that your file is written in Python, and tells it how to run the program and highlight the text in a helpful way.

    After you’ve saved your file, enter the following line in the editor:

    hello_world.py

    print(Hello Python world!)

    To run your program, select RunRun Without Debugging or press CTRL-F5. A terminal screen should appear at the bottom of the VS Code window, showing your program’s output:

    Hello Python world!

    You’ll likely see some additional output showing the Python interpreter that was used to run your program. If you want to simplify the information that’s displayed so you only see your program’s output, see Appendix B. You can also find helpful suggestions about how to use VS Code more efficiently in Appendix B.

    If you don’t see this output, something might have gone wrong in the program. Check every character on the line you entered. Did you accidentally capitalize print? Did you forget one or both of the quotation marks or parentheses? Programming languages expect very specific syntax, and if you don’t provide that, you’ll get errors. If you can’t get the program to run, see the suggestions in the next section.

    Troubleshooting

    If you can’t get hello_world.py to run, here are a few remedies you can try that are also good general solutions for any programming problem:

    When a program contains a significant error, Python displays a traceback, which is an error report. Python looks through the file and tries to identify the problem. Check the traceback; it might give you a clue as to what issue is preventing the program from running.

    Step away from your computer, take a short break, and then try again. Remember that syntax is very important in programming, so something as simple as mismatched quotation marks or mismatched parentheses can prevent a program from running properly. Reread the relevant parts of this chapter, look over your code, and try to find the mistake.

    Start over again. You probably don’t need to uninstall any software, but it might make sense to delete your hello_world.py file and re-create it from scratch.

    Ask someone else to follow the steps in this chapter, on your computer or a different one, and watch what they do carefully. You might have missed one small step that someone else happens to catch.

    See the additional installation instructions in Appendix A; some of the details included in the Appendix may help you solve your issue.

    Find someone who knows Python and ask them to help you get set up. If you ask around, you might find that you unexpectedly know someone who uses Python.

    The setup instructions in this chapter are also available through this book’s companion website at https://ehmatthes.github.io/pcc_3e. The online version of these instructions might work better because you can simply cut and paste code and click links to the resources you need.

    Ask for help online. Appendix C provides a number of resources, such as forums and live chat sites, where you can ask for solutions from people who’ve already worked through the issue you’re currently facing.

    Never worry that you’re bothering experienced programmers. Every programmer has been stuck at some point, and most programmers are happy to help you set up your system correctly. As long as you can state clearly what you’re trying to do, what you’ve already tried, and the results you’re getting, there’s a good chance someone will be able to help you. As mentioned in the introduction, the Python community is very friendly and welcoming to beginners.

    Python should run well on any modern computer. Early setup issues can be frustrating, but they’re well worth sorting out. Once you get hello_world.py running, you can start to learn Python, and your programming work will become more interesting and satisfying.

    Running Python Programs from a Terminal

    You’ll run most of your programs directly in your text editor. However, sometimes it’s useful to run programs from a terminal instead. For example, you might want to run an existing program without opening it for editing.

    You can do this on any system with Python installed if you know how to access the directory where the program file is stored. To try this, make sure you’ve saved the hello_world.py file in the python_work folder on your desktop.

    On Windows

    You can use the terminal command cd, for change directory, to navigate through your filesystem in a command window. The command dir, for directory, shows you all the files that exist in the current directory.

    Open a new terminal window and enter the following commands to run hello_world.py:

    C:\> cd Desktop\python_work

     

    C:\Desktop\python_work>

    dir

     

    hello_world.py

    C:\Desktop\python_work>

    python hello_world.py

     

    Hello Python world!

    First, use the cd command to navigate to the python_work folder, which is in the Desktop folder. Next, use the dir command to make sure hello_world.py is in this folder. Then run the file using the command python hello_world.py.

    Most of your programs will run fine directly from your editor. However, as your work becomes more complex, you’ll want to run some of your programs from a terminal.

    On macOS and Linux

    Running a Python program from a terminal session is the same on Linux and macOS. You can use the terminal command cd, for change directory, to navigate through your filesystem in a terminal session. The command ls, for list, shows you all the nonhidden files that exist in the current directory.

    Open a new terminal window and enter the following commands to run hello_world.py:

    ~$ cd Desktop/python_work/

     

    ~/Desktop/python_work$

    ls

     

    hello_world.py

    ~/Desktop/python_work$

    python3 hello_world.py

     

    Hello Python world!

    First, use the cd command to navigate to the python_work folder, which is in the Desktop folder. Next, use the ls command to make sure hello_world.py is in this folder. Then run the file using the command python3 hello_world.py.

    Most of your programs will run fine directly from your editor. But as your work becomes more complex, you’ll want to run some of your programs from a terminal.

    Try It Yourself

    The exercises in this chapter are exploratory in nature. Starting in Chapter 2, the challenges you’ll solve will be based on what you’ve learned.

    1-1. python.org: Explore the Python home page (https://python.org) to find topics that interest you. As you become familiar with Python, different parts of the site will be more useful to you.

    1-2. Hello World Typos: Open the hello_world.py file you just created. Make a typo somewhere in the line and run the program again. Can you make a typo that generates an error? Can you make sense of the error message? Can you make a typo that doesn’t generate an error? Why do you think it didn’t make an error?

    1-3. Infinite Skills: If you had infinite programming skills, what would you build? You’re about to learn how to program. If you have an end goal in mind, you’ll have an immediate use for your new skills; now is a great time to write brief descriptions of what you want to create. It’s a good habit to keep an ideas notebook that you can refer to whenever you want to start a new project. Take a few minutes now to describe three programs you want to create.

    Summary

    In this chapter, you learned a bit about Python in general, and you installed Python on your system if it wasn’t already there. You also installed a text editor to make it easier to write Python code. You ran snippets of Python code in a terminal session, and you ran your first program, hello_world.py. You probably learned a bit about troubleshooting as well.

    In the next chapter, you’ll learn about the different kinds of data you can work with in your Python programs, and you’ll start to use variables as well.

    2

    Variables and Simple Data Types

    In this chapter you’ll learn about the different kinds of data you can work with in your Python programs. You’ll also learn how to use variables to represent data in your programs.

    What Really Happens When You Run hello_world.py

    Let’s take a closer look at what Python does when you run hello_world.py. As it turns out, Python does a fair amount of work, even when it runs a simple program:

    hello_world.py

    print(Hello Python world!)

    When you run this code, you should see the following output:

    Hello Python world!

    When you run the file hello_world.py, the ending .py indicates that the file is a Python program. Your editor then runs the file through the Python interpreter, which reads through the program and determines what each word in the program means. For example, when the interpreter sees the word print followed by parentheses, it prints to the screen whatever is inside the parentheses.

    As you write your programs, your editor highlights different parts of your program in different ways. For example, it recognizes that print() is the name of a function and displays that word in one color. It recognizes that Hello Python world! is not Python code, and displays that phrase in a different color. This feature is called syntax highlighting and is quite useful as you start to write your own programs.

    Variables

    Let’s try using a variable in hello_world.py. Add a new line at the beginning of the file, and modify the second line:

    hello_world.py

    message = Hello Python world!

    print(message)

    Run this program to see what happens. You should see the same output you saw previously:

    Hello Python world!

    We’ve added a variable named message. Every variable is connected to a value, which is the information associated with that variable. In this case the value is the Hello Python world! text.

    Adding a variable makes a little more work for the Python interpreter. When it processes the first line, it associates the variable message with the Hello Python world! text. When it reaches the second line, it prints the value associated with message to the screen.

    Let’s expand on this program by modifying hello_world.py to print a second message. Add a blank line to hello_world.py, and then add two new lines of code:

    message = Hello Python world! print(message)

     

     

    message = Hello Python Crash Course world!

    print(message)

    Now when you run hello_world.py, you should see two lines of output:

    Hello Python world!

    Hello Python Crash Course world!

    You can change the value of a variable in your program at any time, and Python will always keep track of its current value.

    Naming and Using Variables

    When you’re using variables in Python, you need to adhere to a few rules and guidelines. Breaking some of these rules will cause errors; other guidelines just help you write code that’s easier to read and understand. Be sure to keep the following rules in mind when working with variables:

    Variable names can contain only letters, numbers, and underscores. They can start with a letter or an underscore, but not with a number. For instance, you can call a variable message_1 but not 1_message.

    Spaces are not allowed in variable names, but underscores can be used to separate words in variable names. For example, greeting_message works but greeting message will cause errors.

    Avoid using Python keywords and function names as variable names. For example, do not use the word print as a variable name; Python has reserved it for a particular programmatic purpose. (See Python Keywords and Built-in Functions on page 466.)

    Variable names should be short but descriptive. For example, name is better than n, student_name is better than s_n, and name_length is better than length_of_persons_name.

    Be careful when using the lowercase letter l and the uppercase letter O because they could be confused with the numbers 1 and 0.

    It can take some practice to learn how to create good variable names, especially as your programs become more interesting and complicated. As you write more programs and start to read through other people’s code, you’ll get better at coming up with meaningful names.

    Note

    The Python variables you’re using at this point should be lowercase. You won’t get errors if you use uppercase letters, but uppercase letters in variable names have special meanings that we’ll discuss in later chapters.

    Avoiding Name Errors When Using Variables

    Every programmer makes mistakes, and most make mistakes every day. Although good programmers might create errors, they also know how to respond to those errors efficiently. Let’s look at an error you’re likely to make early on and learn how to fix it.

    We’ll write some code that generates an error on purpose. Enter the following code, including the misspelled word mesage, which is shown in bold:

    message = Hello Python Crash Course reader!

    print(

    mesage)

    When an error occurs in your program, the Python interpreter does its best to help you figure out where the problem is. The interpreter provides a traceback when a program cannot run successfully. A traceback is a record of where the interpreter ran into trouble when trying to execute your code. Here’s an example of the traceback that Python provides after you’ve accidentally misspelled a variable’s name:

    Traceback (most recent call last): ❶  File hello_world.py, line 2, in

        print(mesage)

              ^^^^^^

    ❸ NameError: name 'mesage' is not defined. Did you mean: 'message'?

    The output reports that

    Enjoying the preview?
    Page 1 of 1