Teach Yourself VISUALLY Python - Guy Hart-Davis - E-Book

Teach Yourself VISUALLY Python E-Book

Guy Hart-Davis

0,0
19,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

A simple, straightforward, and hands-on roadmap to the world of computer programming with Python Teach Yourself VISUALLY: Python is your personal guide to getting you started in programming. As one of the world's most popular--and most accessible--coding languages, Python is your gateway into the wide and wonderful world of computer science. This hands-on guide walks you through Python step by clearly illustrated step, from writing your very first Python code in a terminal window or the VS Code app through to creating your own lists, dictionaries, and custom classes. In the book, you'll learn to: * Install Python and the tools you need to work with it on Windows, macOS, and Linux * Work with files and folders, manipulate text, and create powerful functions that do exactly what you want * Write clean code that makes decisions effectively, repeats actions as needed, and handles any errors that occur A must-have resource for aspiring programmers starting from the very beginning, Teach Yourself VISUALLY: Python is also an indispensable handbook for programmers making a transition from another language.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 401

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Teach Yourself VISUALLY™ Python®

Copyright © 2022 by John Wiley & Sons, Inc. All rights reserved.

Published by John Wiley & Sons, Inc., Hoboken, New Jersey.

Published simultaneously in Canada and the United Kingdom.

978-1-119-86025-9

978-1-119-86026-6 (ebk.)

978-1-119-86027-3 (ebk.)

No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 750-4470, or on the web at www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at www.wiley.com/go/permission.

Trademarks: Wiley, the Wiley logo, Visual, the Visual logo, Teach Yourself VISUALLY, Read Less - Learn More and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates. Python is a registered trademark of Python Software Foundation. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.

Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best efforts in preparing this book, they make no representations or warranties with respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose. No warranty may be created or extended by sales representatives or written sales materials. The advice and strategies contained herein may not be suitable for your situation. You should consult with a professional where appropriate. Neither the publisher nor author shall be liable for any loss of profit or any other commercial damages, including but not limited to special, incidental, consequential, or other damages. Further, readers should be aware that websites listed in this work may have changed or disappeared between when this work was written and when it is read. Neither the publisher nor authors shall be liable for any loss of profit or any other commercial damages, including but not limited to special, incidental, consequential, or other damages.

For general information on our other products and services or for technical support, please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.

If you believe you’ve found a mistake in this book, please bring it to our attention by emailing our reader support team at [email protected] with the subject line “Possible Book Errata Submission.”

Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic formats. For more information about Wiley products, visit our web site at www.wiley.com.

Library of Congress Control Number: 2022937470

Cover images: © Misha Shutkevych/Getty Images; Screenshot Courtesy of Guy Hart-Davis and Ted Hart-Davis

Cover design: Wiley

About the Authors

Guy Hart-Davis is the author of more than 175 computer books, including Teach Yourself VISUALLY MacBook Pro and MacBook Air; Teach Yourself VISUALLY iPhone 12, 12 Pro, and 12 Pro Max; Teach Yourself VISUALLY iPad; Teach Yourself VISUALLY Google Workspace; Teach Yourself VISUALLY Chromebook; and Teach Yourself VISUALLY Word 2019.

Ted Hart-Davis is the coauthor of Samsung Galaxy Note 10 Photography and is a programmer, photographer, and folk musician. He is a maintainer and administrator of the historic Minecraft server MinecraftOnline.com and studies cybersecurity and forensics at Edinburgh Napier University.

Authors’ Acknowledgments

Our thanks go to the many people who turned this manuscript into the highly graphical book you are holding. In particular, we thank Devon Lewis for asking us to write the book; Lynn Northrup for keeping us on track; Kim Wimpsett for skillfully editing the text; Doug Holland for reviewing the book for technical accuracy and contributing helpful suggestions; Straive for laying out the book; and Debbye Butler for proofreading the pages.

How to Use This Book

Who This Book Is For

This book is for the reader who has never used this particular technology or software application. It is also for readers who want to expand their knowledge.

The Conventions in This Book

Steps

This book uses a step-by-step format to guide you easily through each task. Numbered steps are actions you must do; bulleted steps clarify a point, step, or optional feature; and indented steps give you the result.

Notes

Notes give additional information — special conditions that may occur during an operation, a situation that you want to avoid, or a cross-reference to a related area of the book.

Icons and Buttons

Icons and buttons show you exactly what you need to click to perform a step.

Tips

Tips offer additional information, including warnings and shortcuts.

Bold

Bold type shows command names, options, and text or numbers you must type.

Italics

Italic type introduces and defines a new term.

Teach Yourself VISUALLY™ Python®

Table of Contents

Cover

Title Page

Copyright

Chapter 1: Getting Ready to Work with Python

Understanding What Python Is and Does

Choose the Right Version of Python

Install Python on Windows

Install Python on the Mac

Install Python on Linux If Necessary

Learn About Development Tools for Python

Download and Install Visual Studio Code

Get Started with Visual Studio Code and Apply a Theme

Install Visual Studio Code Extensions for Python

Configure Visual Studio Code for Working with Python

Chapter 2: Writing and Running Your First Python Code

Understanding the

main()

Function

Create and Save a New Script in Visual Studio Code

Write and Run Code in Visual Studio Code

Execute Python Commands in a Terminal Window

Run a Python Script in a Terminal Window

Understanding Comments in Python

Add Comments to Your Code

Grasp Importing Modules and Objects

Import Modules and Use Their Methods

Chapter 3: Getting Started with Variables

Understanding Variables and Their Usage

Understanding Python’s Data Types

Work with Integers

Work with Floating-Point Values

Work with Boolean Values

Work with Tuples

Work with Sets

Start Working with Strings

Start Working with Lists

Start Working with Dictionaries

Convert Data from One Type to Another

Chapter 4: Working with Files and Directories

Understanding Working with Files and Directories

Load the

os

Module and List Files and Directories

Navigate Among Directories

Create and Delete Directories

Rename, Move, and Copy Files and Directories

Get Information About the User and System

Split a File Path into Its Components

Understanding Python’s

open()

Function

Understanding Python’s Ways of Closing Files

Open a File If It Exists; If Not, Create It

Check an Open File’s Status and Close It

Write Data to a File

Open a File for Both Reading and Writing

Append Data to a File

Read a Text File

Chapter 5: Working with Python’s Operators

Meet the Arithmetic Operators

Work with the Arithmetic Operators

Meet the Assignment Operators

Work with the Assignment Operators

Meet the Comparison Operators

Work with the Comparison Operators

Meet the Logical Operators

Work with the Logical Operators

Meet the Identity Operators

Work with the Identity Operators

Meet the Membership Operators

Work with the Membership Operators

Meet the Bitwise Operators

Work with the Bitwise Operators

Chapter 6: Making Decisions with

if

Statements

Learn the Essentials of

if

Statements

Understanding the

if

Statement

Create an

if

Statement

Understanding the

if… else

Statement

Create an

if… else

Statement

Understanding the

if… elif

Statement

Create an

if… elif

Statement

Understanding the

if… elif… else

Statement

Create an

if… elif… else

Statement

Understanding Nested

if

Statements

Create Nested

if

Statements

Chapter 7: Repeating Actions with Loops

Understanding Python’s Loops

Understanding How

for

Loops Work

Create

for

Loops

Understanding How

while

Loops Work

Create

while

Loops

Understanding

break

Statements in Loops

Using a

break

Statement to Exit a Loop Early

Understanding

continue

Statements in Loops

Using a

continue

Statement in a Loop

Understanding

else

Statements in Loops

Using an

else

Statement in a Loop

Understanding Loop Nesting

Nest Loops to Create Complex Repetition

Chapter 8: Working with Functions

Understanding Functions and Their Syntax

Understanding Function Parameters and Returns

Using Python’s Built-In Functions

Create a Function with Parameters and a Return

Create a Function with a Parameter But No Return

Create a Function with No Parameters But a Return

Create a Function with No Parameters and No Return

Create a Function That Returns Multiple Values

Create a Function with Optional Parameters

Chapter 9: Working with Text

Learn the Essentials of Strings

Create Single-Line Strings

Create Multiline Strings

Meet Python’s String Methods

Return Information About a String

Transform and Clean Up a String

Return Part of a String via Slicing

Concatenate and Repeat Strings

Search for One String Inside Another String

Check and Change String Capitalization

Meet Python’s Tools for Building Strings

Build Strings with the Interpolation Operator

Build Strings with the

.format

Method

Build Strings with f-Strings

Build Strings with Template Strings

Chapter 10: Handling Errors

Understanding the Various Types of Errors

Identify Common Python Errors

Meet the

try… except

Block

Cause Errors and Trap Exceptions

Raise an Exception Manually

Add an

else

Block or a

finally

Block

Create Nested

try… except

Blocks

Create Custom Exceptions

Chapter 11: Working with Lists and Dictionaries

Understanding Lists and Their Use

Create a List

Meet Python’s List Methods

Add Items to a List

Remove Items from a List

Locate Items and Access Data in a List

Sort the Items in a List

Understanding Dictionaries and Their Use

Create a Dictionary and Return Values

Meet Python’s Dictionary Methods

Create a Dictionary from an Existing Iterable

Add Key/Value Pairs to a Dictionary

Remove Key/Value Pairs from a Dictionary

Return Keys and Values from a Dictionary

Chapter 12: Working with Classes

Understanding Classes and Instances

Create a Class and Instantiate Instances

Understanding Class and Instance Attributes

Set Class and Instance Attributes

Grasp Class, Instance, and Static Methods

Create an Instance Method

Create a Class Method

Create a Static Method

Review the Class’s Code

Index

End User License Agreement

List of Tables

Chapter 3

Table 3-1 Python’s Functions for Converting Data

Chapter 4

Table 4-1: Python’s Environment Variables

Table 4-2: Modes of Python’s

open()

Function

Chapter 5

Table 5-1: Python’s Arithmetic Operators

Table 5-2: Python’s Assignment Operators

Table 5-3: Python’s Comparison Operators

Table 5-4: Python’s Logical Operators

Table 5-5: Python’s Identity Operators

Table 5-6: Python’s Membership Operators

Table 5-7: Python’s Bitwise Operators

Table 5-8: Python’s Bitwise Operators

Chapter 8

Table 8-1: Python’s Built-In Functions

Chapter 9

Table 9-1: Methods for Checking and Changing Case

Table 9-2: Methods for Returning Information About Strings

Table 9-3: Methods for Finding and Replacing in Strings

Table 9-4: Methods for Laying Out String Data

Table 9-5: Methods for Transforming String Data

Chapter 10

Table 10-1: Common Errors in Python

Chapter 11

Table 11-1: Attributes of Lists, Tuples, and Sets

Table 11-2: Methods for Working with Lists

Table 11-3: Methods for Working with Dictionaries

Guide

Cover

Table of Contents

Title Page

Begin Reading

Index

Pages

ii

iii

v

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

CHAPTER 1

Getting Ready to Work with Python

In this chapter, you learn what Python is and get ready to work with it. You choose the version of Python that suits your needs and then install that version if your computer does not already have it. You also install and configure your main tool for working with Python, a powerful code editor/integrated development environment called Visual Studio Code.

Understanding What Python Is and Does

Choose the Right Version of Python

Install Python on Windows

Install Python on the Mac

Install Python on Linux If Necessary

Learn About Development Tools for Python

Download and Install Visual Studio Code

Get Started with Visual Studio Code and Apply a Theme

Install Visual Studio Code Extensions for Python

Configure Visual Studio Code for Working with Python

Understanding What Python Is and Does

Python is a programming language that is used both widely and for many different purposes. Python enables you to write applications that work on many different computing platforms, including Microsoft Windows, Apple’s macOS, and Linux. Python is especially useful for automating routine tasks, thus enabling yourself and your colleagues to get more work done in less time.

A Dutch programmer named Guido van Rossum began work on Python in the late 1980s, eventually releasing the first version as Python 0.9.0 in 1991. Since 2001, Python has been run by a U.S.-based nonprofit organization called the Python Software Foundation.

Understanding What Python Is

A programming language is a type of computer language that is used to implement algorithms, which are instructions for performing particular actions — in other words, to make the computer do what the programmer wants it to do.

Python is a general-purpose programming language rather than a domain-specific programming language. As you might guess, a general-purpose programming language is a programming language designed for general programming use rather than for use in a specific area of computing. By contrast, a domain-specific programming language is a programming language designed for use in a specific area of computing. For example, Wolfram Mathematica is a programming language designed for symbolic mathematics; it is not designed for, and is not suitable for, general programming use, so it is domain specific.

Understanding Cross-Platform Programming

Python enables you to write applications that work on many different computing platforms. A computing platform means the hardware and operating system that together constitute a functional computer.

This book covers three widely used computing platforms:

PC hardware running Microsoft’s Windows operating system. This book uses Windows 10 and Windows 11 for examples.Apple Macintosh hardware running Apple’s macOS operating system. This book uses macOS version 12, also known as macOS Monterey, for examples.PC hardware running the Linux operating system. Linux comes in many different versions, called distributions. This book uses the popular Ubuntu distribution for Linux examples.

Python fully supports the Windows, Mac, and Linux platforms, but it also supports many other platforms. These platforms range from those for personal devices, such as Apple’s iOS operating system and iPhones, all the way up to “big-iron” platforms for minicomputers and mainframes, such as IBM’s AIX and HP’s HP-UX. Python versions for some platforms come from third-party vendors.

Understanding Who Uses Python

Many different types of programmers use Python. Here are two examples:

Web developers use Python to create web services that provide custom information in response to requests they receive. For example, when you visit a web forum, Python may be generating some or all parts of the page that the server sends to your browser.Scientists, mathematicians, and engineers across many fields use Python to perform data analysis, because Python provides powerful and convenient tools for processing and applying complex equations to statistical data.

Know Where You Can Get Python

You can download Python for free from the Python Software Foundation’s website, www.python.org. However, you may not need to download Python, because it may already be installed on your computer.

Windows typically does not include Python; see the section “Install Python on Windows,” later in this chapter, for instructions on installing Python.

macOS includes Python 2. See the section “Install Python on the Mac,” later in this chapter, for instructions on seeing which version a Mac contains and updating Python if necessary.

Many Linux distributions include one or more versions of Python. As of this writing, more distributions include Python 2 than include Python 3, but some distributions include both versions; see the following section, “Choose the Right Version of Python.” See the section “Install Python on Linux If Necessary,” later in this chapter, for instructions on checking the version and updating if necessary.

To find versions of Python for iOS or iPadOS, open the App Store app on the iPhone or iPad and search for python. Pythonista is a popular app, but there are plenty of other choices. Similarly, to find versions of Python for Android, open the Play Store app on your Android device and search for python.

Choose the Right Version of Python

As of this writing, two major versions of Python are in use: Python 2 and Python 3. Before you download and install Python on your computer, you should determine which version of Python will be best for your needs. This will most likely be Python 3, because Python 2 is out of date and the Python Software Foundation no longer supports it.

This section explains what you need to know about Python 2 and Python 3. It also explains the two types of Python builds that are available — stable builds and development builds — and advises you which build type to get.

Understanding Python 2 and Python 3

Two major versions of Python are currently in wide use: Python 2, released in 2000, and Python 3, released in 2008.

Each version uses a sequence-based numbering scheme for intermediate releases. For example, “Python 2.7.1” means Python 2, the seventh minor version, and the first update to that minor version. Similarly, “Python 3.10.0” means Python 3, the tenth minor version, and the initial release of that minor version.

The Python Software Foundation officially discontinued, or “sunset,” Python 2 on January 1, 2020. Sunsetting means that the Python Software Foundation will not develop Python 2 any further, even if researchers discover serious security issues in it. Because Python 2 has been sunset, the Python Software Foundation recommends that all users upgrade to Python 3 as soon as possible. The final version of Python 2 was 2.7.18.

With most software, such as business productivity apps or multimedia apps, upgrading to a newer version is a straightforward and painless procedure: You upgrade to the new version, and everything still works, even if the user interface has changed and the new version of the app provides extra features.

Python 3 offers compelling new features that Python 2 does not have; even better, Python 3 typically runs faster than Python 2. However, Python 3 is not fully compatible with Python 2, and some Python 2 code may not run successfully in Python 3. This is why many companies and organizations still have not upgraded from Python 2 to Python 3. The more Python 2 code a company or organization has built up, the more time, effort, and expense it will take to upgrade to Python 3.

Which Version of Python Do You Need?

You almost certainly need Python 3 unless your workplace uses Python 2 and is not migrating to Python 3. For example, your employer may have developed substantial amounts of Python 2 code that is not fully compatible with Python 3 and may therefore be sticking with Python 2.

If you are planning to start developing code from scratch, you should definitely choose Python 3 rather than Python 2.

You can install both Python 2 and Python 3 alongside each other and use each version when you need it.

macOS and many Linux distributions include Python 2 because they require Python 2 to run some software packages included with the operating system or distribution. Because of this requirement, you should not uninstall Python 2, even if you do not need it. Instead, simply leave Python 2 alone, install Python 3, and use Python 3 for development.

Windows does not need Python 2, so normally, you should install Python 2 on Windows only if you need it.

What Are the Two Build Types of Python?

Python.org makes available two types of builds of Python, stable builds and development builds:

Stable build. A stable build is a build that has been fully tested and approved for distribution.

Development build. A development build is an experimental build used for testing and compatibility. Development testers provide feedback on changes and new features before they are finalized and added to stable builds.

You may also see Python builds described as “release candidates.” A release candidate is a near-final development build made available — usually to a wide audience — for final testing. A release candidate is stable in theory but not always so in practice.

Which Build Type Should You Get?

You will almost always want to get a stable build of Python rather than a development build. Normally, you will want to get the latest stable build of Python so that you have access to the latest features. However, if your company, organization, or school is using an older stable build of Python, it will likely want you to use that build for compatibility.

When Will Python 4 Be Released?

The Python Software Foundation has not announced a release date for Python 4. In fact, Guido van Rossum has cast doubt on whether there will ever be Python 4, given how difficult and protracted the move from Python 2 to Python 3 turned out to be. Instead, the Python Software Foundation is continuing to develop Python 3.

As of this writing, the current stable version of Python is 3.10.4. Future versions of Python 3 are likely to use numbering such as 3.11.x, 3.12.x, and so on.

Install Python on Windows

Windows has no version of Python installed by default, so you will need to install Python unless you have already installed it or an administrator has installed it for you.

You can install Python either by using the Microsoft Store app or by downloading and running the Python installer from the Python Software Foundation. Microsoft recommends using the Microsoft Store app, but we recommend downloading the Python installer, because this enables you to make the latest version of Python available to the Visual Studio Code editor app, which you will meet later in this chapter.

Install Python on Windows

Download and Install Python on Windows

Open a browser window and go to the Python Software Foundation website, www.python.org.

Hold the pointer over Downloads.

A pop-up window appears.

The web page selects the Windows tab, because it detects your computer is running Windows.

Click the Python button under the Download for Windows heading.

This button shows the Python version, such as Python 3.10.0 in the example.

The browser downloads the file.

Open the downloaded file from the browser. For example, in Chrome, click Actions ( changes to ) to open the pop-up menu, and then click Open to open the file.

Note: In Microsoft Edge, click Downloads () to display the Downloads panel, locate the Python file you downloaded, and then click Open file beneath its name.

The Python Setup Wizard opens and displays the Install Python screen.

Select Install launcher for all users () to install the Python launcher for all users of this computer. This is usually helpful.

Note: If an earlier version of Python is installed on the PC, the Upgrade Now button appears. See the subsection “Upgrade Python on Windows,” later in this section.

Select Add Python to PATH () to add the location of the Python executable file to your Windows PATH statement. Doing so enables Windows to find Python and is usually helpful.

You can click Install Now to install Python and all its components for yourself, not for other users.

Click Customize installation.

The Optional Features screen appears.

Deselect the check box for any feature you do not want to install. For example, deselect tcl/tk and IDLE () if you do not want to install the IDLE development environment.

Click Next.

TIP

Which apps does the Python installation include?

The Python installation installs an app called Python — for example, Python 3.10 — and an app called IDLE, an integrated development environment for Python. The IDLE app’s name includes the version of Python, such as IDLE (Python 3.10).

You can use the IDLE integrated development environment to create and test Python code, but we recommend you use Visual Studio Code instead, because it provides more features and is widely used. See the section “Download and Install Visual Studio Code,” later in this chapter, for information on getting Visual Studio Code.

When installing Python, you can choose to install the Python launcher component for just yourself or for all users. Separately, you can choose to install the main Python app and other components either for just yourself or for all users of your computer. You can also add the Python program location to your Windows PATH, which enables Windows to find Python without you having to specify the path explicitly.

After installing Python, you can update it to the latest version by downloading the latest installer from the Python Software Foundation website, running the installer, and clicking Upgrade.

The Advanced Options screen appears.

Note: By default, the Python Setup Wizard installs Python and the components you choose only for you, not for all users of your computer.

The default install location is within the AppData folder in your user account. This location is available only to you.

Click Install for all users ( changes to ).

The install location changes to a Python folder within your computer’s Program Files folder. This location is available to all users.

You can click Browse and select a different install location if necessary. Normally, the default location works well.

Click Install.

Note: If the User Account Control dialog box opens, prompting you to decide whether to allow the Python Setup Wizard to make changes to your computer, click Yes.

The Python Setup Wizard installs the components you chose.

The Setup Was Successful screen appears.

If you want to disable the path length limit, click Disable path length limit, and then click Yes in the User Account Control dialog box that appears.

Click Close.

The Python Setup Wizard closes.

Upgrade Python on Windows

Follow steps 1 to 4 in the previous subsection to download the Windows installer for the latest version of Python from the Python Software Foundation website, www.python.org, and open the installer file.

The Python Setup Wizard screen appears.

Click Upgrade Now to upgrade Python but retain all your settings.

If you want to change your settings, click Customize installation, and then make your choices on the Options screen and the Advanced Options screen.

TIP

What is the path length limit, and should I disable it?

The Windows path is a text variable that tells Windows where to find important items. For example, PATH=C:\Windows;C:\Program Files tells Windows where to find the Windows folder and the Program Files folder. Selecting Add Python to PATH () adds Python’s folder to the path, so Windows can find Python without you having to specify the folder.

The PATH variable has a length limit of 260 characters for backward compatibility with older versions of Windows. However, this limit may cause errors when compiling and running Python code that uses long paths. Normally, you should click Disable path length limit on the Setup Was Successful screen to disable the path length limit.

Install Python on the Mac

Whether it has an Intel CPU or an Apple Silicon CPU, your Mac almost certainly has a version of Python installed — but it is most likely to have only Python 2. If so, you will want to install Python 3, probably the latest stable version of it.

In this section, you use the Terminal app in macOS to check whether Python is installed and, if so, which version. Then, if needed, you can download and install a newer version of Python.

Install Python on the Mac

Check Which Version of Python Is Installed on Your Mac

Click Launchpad ().

Launchpad opens.

Start typing terminal.

Launchpad narrows the selection to the apps that include what you have typed.

Click Terminal ().

A Terminal window opens.

Type python3 and press .

Note: If Terminal displays the version of Python, as shown in the final screen of this section, go to step 8. Python 3 is already installed on your Mac.

A dialog box opens, prompting you to install the command-line developer tools.

Click Install.

The Downloading Software dialog box opens, showing a progress readout.

When the installation completes, a The Software Was Installed dialog box opens.

Click Done.

The dialog box closes.

The Terminal window becomes active again.

Type python3 and press .

The version of Python appears.

Type quit() or press  + .

The Python app quits.

Press  + .

The Terminal app quits, and the Terminal window closes.

TIP

How can I update the version of Python on my Mac?

The easiest way to update the version of Python on your Mac is to download the latest Python installer file for macOS from the Python Software Foundation website, www.python.org; run the installer; and click Upgrade Now.

On a Mac that you administer yourself, another option is to install the Homebrew package manager, which you can download for free from the Homebrew website, https://brew.sh. After installing Homebrew, you can quickly update Python by opening the Terminal app and running the appropriate command.

Install Python on Linux If Necessary

Many Linux distributions include a version of Python, so you may not need to install Python on Linux. In this section, you check whether Python is already installed on your Linux box and install it if it is not. If Python is already installed but is out of date, you update it to the latest version available for your Linux distribution.

This section uses Ubuntu Linux as the example and provides brief notes on other widely used Linux distributions. You need to have the permission to run commands as superuser — as the root user — using the sudo command.

Install Python on Linux If Necessary

Verify That Python Is Installed on Linux

Open a Terminal window. For example, on Ubuntu:

Click Show Applications ().

The Activities screen appears.

Type terminal.

Matching search results appear.

Click Terminal ( or similar).

A Terminal window opens.

Type python3 and press .

If Terminal displays details of the Python version, such as Python 3.9.5, Python is installed.

You can quit Python by typing quit() and pressing . Alternatively, press  + .

Note: If you see a message saying that Python was not found, you need to install Python. In the Terminal window, type sudo apt install python3 and press . If Terminal prompts you for your password, type it and press . Linux then downloads and installs Python.

Update Python on Linux

Open a Terminal window. For example, on Ubuntu, click Show Applications (), type terminal, and then click Terminal ().

Type the sudo apt update command and press .

Linux prompts you for your password.

Type your password and press .

Linux downloads the latest list of software packages available.

Terminal displays information about available upgrades.

Type the sudo apt upgrade command and press .

Note: If Terminal displays information about the amount of additional disk space that will be used and prompts you to decide whether to continue, type y and press .

Linux downloads and installs the updates.

When the upgrade finishes, the prompt reappears.

You can then type python3 and press to see the Python version that has been installed.

TIP

How do I install Python on other Linux distributions?

Generally, you would install Python from your distribution’s application repository.

Here are the commands for other popular distributions:

Fedora: sudo dnf install python3Arch: sudo pacman -S python3SUSE: sudo rpm install python3Other Debian-based distributions: sudo apt install python3

Learn About Development Tools for Python

Python code consists of plain text with structured layout, so you can create the code in any app that can output plain text. For example, you can create Python code in the Notepad text editor on Windows or in the TextEdit text editor on macOS.

But unless you like doing things the hard way, you will be better off using an app that is designed for creating code and that provides features to help you create code that is both correct and correctly formatted. This app can be either a code editor or an integrated development environment, IDE for short.

What Is a Code Editor?

A code editor is an app that is designed and built to make the writing of programming code easier, faster, and more efficient. While you can write code using any text editor or word processor, these apps do not provide the programming-specific features that a code editor gives you.

A code editor typically includes features such as the following:

Syntax evaluation and highlighting. As you program, the editor determines the code’s different elements and highlights them in different colors and font styles (A) to help you identify them visually.Automatic completion of code. When you start typing a keyword or another known element, the code editor displays suggestions for completing it. By accepting these suggestions, you can work faster.Multifile interface. Whereas most word processors keep each document in a separate window, many code editors use a tabbed interface (B) that enables you to open multiple files in the same window and switch quickly from one file to another by clicking the appropriate tab. Many text editors likewise use a tabbed interface.Line numbers. The code editor automatically displays line numbers (C) so that you can easily navigate through your code.

What Is an Integrated Development Environment?

An integrated development environment, or IDE, is an application designed for developing code. The development environment is integrated because you can both write the code in the environment and run the code to make sure it works correctly.

An IDE typically provides similar features to those in a code editor, such as syntax evaluation and highlighting, automatic code completion, and the ability to switch easily among multiple files. To these features the IDE adds tools for testing and debugging your code.

For example, the figure shows the PyCharm IDE. In the upper-left corner is the Project pane (D), which enables you to navigate among the files in your current project; gives you access to external libraries, repositories containing code you can add; and provides a scratch window for quick work and notes, and consoles for running code outside the IDE. In the upper-right corner is the Code pane (E), where you write your code. And across the bottom is the Run window (F), in which the output from your running code appears.

Should I Use a Code Editor, an IDE, or Both?

Which coding tools you use for Python is very much a personal preference. That said, you will almost certainly want to use an IDE for debugging your Python code. The question then becomes whether you want to use a code editor as well as an IDE.

You may want to use both a code editor and an IDE for different aspects of your work developing code in Python. Experiment with different tools to discover which tool or combination of tools works best for you.

When it comes to development tools for Python, there are a lot of choices. Many Python-capable code editors and IDEs are available, offering various combinations of features likely to appeal to different developers. Most of these code editors and IDEs work for multiple — or many — programming languages, but you can find IDEs built to work only with Python.

This section introduces you to some of the code editors and IDEs you may want to explore, including Visual Studio Code, the coding tool we recommend you use for working with Python.

Which IDEs Can I Use for Creating Python Code?

You can use a bewildering variety of IDEs for creating Python code. Some IDEs are designed for use only with Python, whereas other IDEs are designed for use with various programming languages. Some IDEs are much fuller featured than others and provide more help as you work. Extra help may be welcome while you are starting to use Python but may become annoying as you gain more experience.

Here are three examples of IDEs for Python:

IDLE. IDLE is a minimalist IDE that is included in the Python packages you can download from the Python Software Foundation website, www.python.org. IDLE, shown in the figure, uses multiple separate windows for the Editor (G), the Shell (H), and features such as Debug Control (I) rather than displaying multiple panes inside a single window.PyCharm. PyCharm (www.jetbrains.com/pycharm) is a full-featured IDE that comes in two editions. Normally, you would want the Community Edition, which is free and works only with Python. The other edition, Professional, is a paid version that has a free trial and works with HTML, JavaScript, and SQL, as well as Python. Thonny. Thonny (https://thonny.org) is a lightweight IDE designed to help beginners come to grips with Python coding. Thonny offers three modes for different levels of experience: Simple Mode for beginners, Regular Mode for those who need greater control, and Expert Mode for advanced users. The accompanying figure shows Regular Mode.

Which Code Editors Can I Use for Python?

You have a wide choice of code editors suitable for programming Python. Here are three examples of code editors well worth your consideration:

Sublime Text. Sublime Text, shown in the “What Is a Code Editor?” subsection earlier in this section, is a powerful text editor with a minimalist interface that provides as much space as possible for displaying your code files. Sublime Text supports more than 40 other programming languages as well as Python. You can download an evaluation version of the app from the Sublime Text website, www.sublimetext.com; the app then costs $99 for a 3-year subscription.Atom. Atom, shown on this page, is a highly customizable code editor that makes working with multiple files easy. As of this writing, Atom seems to place greater demands on the computer running it than the other code editors listed here; as a result, Atom tends to run more slowly. Atom is free to download from the Atom website, https://atom.io.Visual Studio Code. Visual Studio Code is a powerful code editor developed by Microsoft. It is separate from Microsoft’s Visual Studio IDE and runs on Windows, macOS, and Linux. See the following section for more information.

Which Code Editor or IDE Does This Book Recommend for Python?

This book recommends that you use Visual Studio Code as your main coding tool for working with Python, at least while using this book. Visual Studio Code is free, provides powerful coding features, and is widely used for various programming languages from C +  +  and C# to PHP and PowerShell.

While Visual Studio Code is generally described as a code editor, it also provides full-scale debugging features, so it is effectively also an IDE.

The following section, “Download and Install Visual Studio Code,” shows you how to get the app on your Windows PC, Mac, or Linux box. Subsequent sections show you how to set Visual Studio Code’s look by applying a theme, install Python-related extensions to provide extra functionality, and configure some essential settings.

Download and Install Visual Studio Code

In this section, you download and install the Visual Studio Code app. Visual Studio Code is the code editor and IDE we recommend you use for creating Python code. Visual Studio Code runs on Windows, macOS, and Linux; this section shows Windows and provides notes and tips on the differences in macOS and Linux.

On Windows, you can add an Open with Code command to the context menus for files and for directories. This command enables you to easily open a file or a folder in Visual Studio Code from File Explorer, which is usually helpful.

Download and Install Visual Studio Code

Open your web browser and go to https://code.visualstudio.com.

The home page of the Visual Studio Code website appears.

Click the Download link for your computer’s operating system.

The Download button shows the operating system your computer is using.

To download Visual Studio Code for another operating system, click the drop-down arrow (), and then click Download () in the Stable column for the operating system.

The Documentation for Visual Studio Code screen appears, and the download starts.

Launch the Setup Wizard. For example, in the Chrome browser, click ( changes to ), and then click Open on the pop-up menu.

The Setup Wizard’s License Agreement screen appears.

Read the license agreement.

If you want to continue, click I accept the agreement ( changes to ).

Click Next.

Click Next on the Select Destination Location screen.

Click Next on the Select Start Menu Folder screen.

The Select Additional Tasks screen appears.

Select Create a desktop icon () if you want a Visual Studio Code icon on your desktop.

Select Add “Open with Code” action to Windows Explorer file context menu (), as needed.

Select Add “Open with Code” action to Windows Explorer directory context menu (), as needed.

Select Register Code as an editor for supported file types () to associate Visual Studio Code with the file types it supports.

Select Add to PATH () to add Visual Studio Code to your Windows path. This helps Windows locate Visual Studio Code.

Click Next.

The Ready to Install screen appears.

Verify that the summary shows the choices you intended to make.

If you need to make changes, click Back until you reach the appropriate screen.

Click Install.

The Setup Wizard installs Visual Studio Code.

The Completing the Visual Studio Code Setup Wizard screen appears.

Note: If you want to use Visual Studio Code immediately, select Launch Visual Studio Code () on the Completing the Visual Studio Code Setup Wizard screen.

Click Finish.

The Setup Wizard closes.

Visual Studio Code opens.

You can now configure Visual Studio Code, as explained in the section “Configure Visual Studio Code for Working with Python,” later in this chapter.

TIPS

How do I install Visual Studio Code on macOS?

Download the latest Mac Universal Stable Build from https://code.visualstudio.com. Double-click the downloaded zip file to extract its contents, the Visual Studio Code app. Drag this app to the Applications folder. You can then delete the downloaded zip file.

How do I install Visual Studio Code on Linux?

Go to https://code.visualstudio.com and download the appropriate installer package for your distribution — for example, the Debian installer package or the Red Hat Package Manager installer package. Open the file and follow the prompts.

Get Started with Visual Studio Code and Apply a Theme

The first time you run Visual Studio Code, the app displays the Get Started with Visual Studio Code screen, which walks you through some initial configuration steps. You can return to the Get Started with Visual Studio Code screen later if you like; alternatively, you can use the app’s other means of accessing its settings to configure the app to work the way you prefer.

The first change you will likely want to make is to the theme, which controls the overall look of Visual Studio Code. The app includes various dark themes and various light themes; third-party themes are also available.

Get Started with Visual Studio Code and Apply a Theme

Launch Visual Studio Code

Launch Visual Studio Code in one of the standard ways for your computer’s operating system.

For example, on Windows, click Start () to open the Start menu, and then click Visual Studio Code ().

The Get Started with Visual Studio Code screen appears.

The list on the left contains headings for several initial configuration steps.

Click Choose the look you want.

Controls under the heading section appear.

A preview appears.

Click Browse Color Themes.

The Theme drop-down list opens.

The highlight shows the current theme.

The Light Themes section at the top contains themes based on light colors.

The Dark Themes section contains themes based on dark colors.

Press or to move the highlight to the theme you want to preview.

Visual Studio Code displays a preview of the theme.

Click the theme you want to apply.

Note: You can also press to apply the currently selected theme.

The Get Started screen appears fully again.

Click the next heading whose settings you want to explore.

The settings for the heading appear, and you can work with them.

When you finish working through the list, you can click Mark Done () to tell Visual Studio Code you finish using this list.

TIPS

How do I go back to the Getting Started screen?

Click Help to open the Help menu, and then click Getting Started. On the screen that appears, click Get Started with Visual Studio Code