Share E-Book

Python Essentials For Dummies (John C. Shovic Alan Simpson)(Z-Library)

Author

Rating No ratings yet

Log in to rate

Python
Language English

The no-nonsense way to get started coding in the Python programming language Python Essentials For Dummies is a quick reference to all the core concepts in Python, the multifaceted general-purpose language used for everything from building websites to creating apps. This book gets right to the point, with no excess review, wordy explanations, or fluff, making it perfect as a desk reference on the job or as a brush-up as you expand your skills in related areas. Focusing on just the essential topics you need to know to brush up or level up your Python skill, this is the reliable little book you can always turn to for answers. Get a quick and thorough intro to the basic concepts of coding in Python Review what you've already learned or pick up essential new skills Create websites, software, machine learning, and automation for school or work Keep this concise reference book handy for jogging your memory as you code This...

Format PDF
Size 5.1 MB
10
Views
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
(This page has no text content)
Page 2
(This page has no text content)
Page 3
Python® Essentials For Dummies® To view this book's Cheat Sheet, simply go to www.dummies.com and search for “Python Essentials For Dummies Cheat Sheet” in the Search box. Table of Contents Cover Title Page Copyright Introduction About This Book Foolish Assumptions Icons Used in This Book Where to Go from Here Chapter 1: Starting with Python Why Python Is Hot Choosing the Right Python Tools for Success Chapter 2: Using Interactive Mode, Getting Help, and Writing Apps Using Python’s Interactive Mode Creating a Folder for Your Python Code Typing, Editing, and Debugging Python Code Chapter 3: Python Elements and Syntax
Page 4
The Zen of Python Introducing Object-Oriented Programming Discovering Why Indentations Count, Big Time Using Python Modules Chapter 4: Building Your First Python Application Opening the Python App File Typing and Using Python Comments Understanding Python Data Types Working with Python Operators Creating and Using Variables Understanding What Syntax Is and Why It Matters Chapter 5: Working with Numbers, Text, and Dates Calculating Numbers with Functions Still More Math Functions Formatting Numbers Grappling with Weirder Numbers Manipulating Strings Uncovering Dates and Times Chapter 6: Controlling the Action Main Operators for Controlling the Action Making Decisions with if Repeating a Process with for Looping with while Chapter 7: Speeding Along with Lists and Tuples Defining and Using Lists What’s a Tuple and Who Cares? Working with Sets Chapter 8: Wrangling Bigger Chunks of Code Creating a Function Commenting a Function Passing Information to a Function Returning Values from Functions
Page 5
Chapter 9: Sidestepping Errors Understanding Exceptions Handling Errors Gracefully Being Specific about Exceptions Keeping Your App from Crashing Adding an else to the Mix Using try … except … else … finally Raising Your Own Exceptions Chapter 10: Working with External Files Understanding Text and Binary Files Opening and Closing Files Reading a File’s Contents Looping through a File Reading and Copying a Binary File Chapter 11: Juggling JSON Data Organizing JSON Data Understanding Serialization Loading Data from JSON Files Dumping Python Data to JSON Chapter 12: Interacting with the Internet Seeing How the Web Works Chapter 13: Libraries, Packages, and Modules Understanding the Python Standard Library Exploring Python Packages Importing Python Modules Chapter 14: The Ten Most Essential Aspects of Python Being Pythonic Identifying the Importance of Indents Understanding Python Syntax Appreciating the Flexibility of Python Variables Seeing Lists as Your Friend Controlling Your Program
Page 6
Understanding Python Functions Figuring Out Errors Using Other People’s Modules Using the Web and AI When You Have Problems Index About the Authors Connect with Dummies End User License Agreement List of Tables Chapter 4 TABLE 4-1 Python’s Arithmetic Operators TABLE 4-2 Python Comparison Operators TABLE 4-3 Python Boolean Operators Chapter 5 TABLE 5-1 Some Built-In Python Functions for Numbers TABLE 5-2 Some Functions from the Python Math Module TABLE 5-3 Python for Base 2, 8, and 16 Numbers TABLE 5-4 Python Sequence Operators That Work with Strings TABLE 5-5 Built-In Methods for Python 3 Strings TABLE 5-6 Sample Date Format Strings TABLE 5-7 Sample Datetime Format Strings Chapter 6 TABLE 6-1 Python Comparison Operators for Decision-Making TABLE 6-2 Python Logical Operators Chapter 7 TABLE 7-1 Methods for Working with Lists Chapter 11 TABLE 11-1 Python JSON Methods for Serializing and Deserializing JSON Data
Page 7
TABLE 11-2 Python and JSON Data Conversions Chapter 12 TABLE 12-1 Common HTTP Status Codes TABLE 12-2 Packages from the Python urllib Library List of Illustrations Chapter 1 FIGURE 1-1: Obtaining the Python extension in VS Code. FIGURE 1-2: The GitHub Copilot extension in VS Code. FIGURE 1-3: The Accounts and Copilot icons in VS Code. Chapter 2 FIGURE 2-1: The Terminal pane in VS Code. FIGURE 2-2: Python doesn’t know what howdy means. FIGURE 2-3: Keyword help. FIGURE 2-4: The hello.py file contains some Python code and has unsaved changes... FIGURE 2-5: Output from hello.py. FIGURE 2-6: PRINT is typed incorrectly in hello.py. Chapter 3 FIGURE 3-1: The Zen of Python. Chapter 4 FIGURE 4-1: The hello.py file, open for editing in VS Code. FIGURE 4-2: The 19.9 is the output from print(extended_price) in the code. Chapter 5 FIGURE 5-1: Using the sqrt() function from the math module. FIGURE 5-2: A super simple f-string for formatting. Chapter 6 FIGURE 6-1: The result of a simple if when the condition proves true. FIGURE 6-2: Print an initial greeting based on the time of day.
Page 8
FIGURE 6-3: Looping through a list. FIGURE 6-4: Nested loops. FIGURE 6-5: An infinite while loop. FIGURE 6-6: A while loop with continue. Chapter 7 FIGURE 7-1: Seeing whether an item is in a list. FIGURE 7-2: Program fails when trying to find the index of a nonexistent list i... Chapter 8 FIGURE 8-1: Writing, and calling, a simple function named hello(). FIGURE 8-2: A sample function with a couple of comments added. FIGURE 8-3: Passing data to a function via a variable. FIGURE 8-4: The hello function with three parameters. FIGURE 8-5: Calling the hello() function with three parameters, and again with ... FIGURE 8-6: Calling a function with keyword arguments (kwargs). FIGURE 8-7: A function accepting any number of arguments with *args. FIGURE 8-8: Printing a string returned by the alphabetize() function. Chapter 9 FIGURE 9-1: The showfilecontents.py and people.csv files in a folder in VS Code... FIGURE 9-2: The contents of the people.csv file in Excel (top) and a text edito... FIGURE 9-3: The showfilecontents.py file raises an exception. FIGURE 9-4: The showfilecontents.py file catches the error and displays a frien... FIGURE 9-5: The correct error message is displayed. FIGURE 9-6: Code with try, exception handlers, and an else: block for when ther... Chapter 10 FIGURE 10-1: Common text and binary files. FIGURE 10-2: The binarycopy.py file copies any binary file.
Page 9
FIGURE 10-3: Running binarycopy.py added happy_pickle_copy.jpg to the folder. Chapter 11 FIGURE 11-1: Some data in an Excel spreadsheet. FIGURE 11-2: Excel spreadsheet data converted to JSON format. FIGURE 11-3: Some data in a Google Firebase Realtime Database. FIGURE 11-4: Output from showing one value at a time from each dictionary (see ... FIGURE 11-5: Changing the value of one key in each dictionary, and removing an ... Chapter 12 FIGURE 12-1: The client makes a request, and the server sends back a response. FIGURE 12-2: Different parts of URLs. FIGURE 12-3: Inspecting HTTP headers with Google Chrome. FIGURE 12-4: HTTP headers. FIGURE 12-5: Sample page used for web scraping. FIGURE 12-6: Some of the code from the sample page for web scraping. FIGURE 12-7: Web scraping code complete. Chapter 13 FIGURE 13-1: Python’s built-in functions.
Page 10
(This page has no text content)
Page 11
Python® Essentials For Dummies® Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com Copyright © 2024 by John Wiley & Sons, Inc., Hoboken, New Jersey Published simultaneously in Canada 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 Sections 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the Publisher. 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 http://www.wiley.com/go/permissions. Trademarks: Wiley, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written permission. Python is a registered trademark of Python Software Foundation Corporation. 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: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR
Page 12
OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ. For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit https://hub.wiley.com/community/support/dummies. Wiley publishes in a variety of print and electronic formats and by print- on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com. Library of Congress Control Number: 2024934008 ISBN 978-1-394-26347-9 (pbk); ISBN 978-1-394-26348-6 (ebk); ISBN 978-1-394-26349-3 (ebk)
Page 13
Introduction The Python language is becoming more and more popular, and in 2017 it became the most popular language in the world according to IEEE Spectrum. The power of Python is real. Python is the number-one language because it’s easy to learn and use, due partly to its simplified syntax and natural-language flow but also to the amazing user community and the breadth of applications available. About This Book This book is a reference manual to guide you through the process of learning the essentials of Python. If you’re looking to learn a little about a lot of exciting things, this is the book for you. It gives you an introduction to the topics that you’ll need to explore more deeply. This is a hands-on book, with examples and code throughout. You’ll enter the code, run it, and then modify it to do what you want. In this book, we take you through the basics of the Python language in small, easy-to-understand steps. Foolish Assumptions We assume that you know how to use a computer in a basic way. If you can turn on the computer and use a mouse, you’re ready for this book. We assume that you don’t know how to program yet, although you will have some skills in programming after reading this book. Icons Used in This Book What’s a For Dummies book without icons pointing you in the direction of truly helpful information that’s sure to speed you along your way? Here we briefly describe each icon we use in this book.
Page 14
The Tip icon points out helpful information that’s likely to make your job easier. The Remember icon marks a generally interesting and useful fact — something you may want to remember for later use. The Warning icon highlights lurking danger. When we use this icon, we’re telling you to pay attention and proceed with caution. Where to Go from Here You can start the book anywhere, but here are a couple of hints. If you’re brand-new to Python, start with Chapter 1. If you already have some Python experience and you want to learn how to work with bigger chunks of code, head to Chapter 8. For anything else, turn to the Table of Contents or the Index and you’ll find what you need.
Page 15
Chapter 1 Starting with Python IN THIS CHAPTER Discovering why Python is hot Finding the tools for success Writing Python in VS Code Because you’re reading this chapter, you probably realize that Python is a great language to know if you’re looking for a good job in programming, or if you want to expand your existing programming skills into exciting cutting-edge technologies such as artificial intelligence (AI), machine learning (ML), data science, or robotics, or even if you’re just building apps in general. So we’re not going to try to sell you on Python. It sells itself. Our approach leans heavily toward the hands-on. A common failure in many programming tutorials is that they already assume you’re a professional programmer in some language, and they skip over things they assume you already know. This book is different in that we don’t assume that you’re already programming in Python or some other language. We do assume that you can use a computer and understand basics such as files and folders. We also assume you’re not up for settling down in an easy chair in front of the fireplace to read page after page of theoretical stuff about Python, like some kind of boring novel. You don’t have that much free time to kill. So we’re going to get right into it and focus on doing, hands-on, because that’s the only way most of us learn. We’ve never seen anyone read a book about Python and then sit at a computer and write Python like a pro. Human brains don’t work that way. We learn through practice and repetition, and that requires being hands-on.
Page 16
Why Python Is Hot We promised we weren’t going to spend a bunch of time trying to sell you on Python, and that’s not our intent here. But we would like to talk briefly about why it’s so hot. Here are the main reasons cited for Python’s current popularity: Python is relatively easy to learn. Everything you need to learn (and do) in Python is free. Python offers more ready-made tools for current hot technologies such as data science, machine learning, artificial intelligence, and robotics than most other languages. Choosing the Right Python There are different versions of Python out roaming the world, prompting many a beginner to wonder things such as Why are there different versions? How are they different? Which one should I learn? All good questions, and we’ll start with the first. A version is kind of like a car year. You can go out and buy a 1968 Ford Mustang, a 1990 Ford Mustang, a 2019 Ford Mustang, or a 2020 Ford Mustang. They’re all Ford Mustangs. The only difference is that the one with the highest year number is the most current Ford Mustang. That Mustang is different from the older models in that it has some improvements based on experience with earlier models, as well as features current with the times. Programming languages (and most other software products) work the same way. But as a rule, we don’t ascribe year numbers to them because they’re not released on a yearly basis. They’re released whenever they’re
Page 17
released. The principle is the same, though. The version with the highest number is the newest, most recent model, sporting improvements based on experience with earlier versions, as well as features relevant to the current times. In this book, we focus on versions of Python that are current in late 2023 from Python 3.11 and higher. Don’t worry about version differences after the first and second digits. Version 3.11.1 is similar enough to version 3.11.2 that version differences aren’t important, especially to a beginner. Most of what’s in Python is the same across all recent versions. So you need not worry about investing time in learning a version that is or will soon be obsolete. Tools for Success Now we need to start getting your computer set up so that you can learn, and do, Python hands-on. For one, you’ll need a good Python interpreter and editor. The editor lets you type the code, and the interpreter lets you run that code. When you run (or execute) code, you’re telling the computer to “do whatever my code tells you to do.” The term code refers to anything written in a programming language to provide instructions to a computer. The term coding is often used to describe the act of writing code. A code editor is an app that lets you type code, in much the same way an app such as Microsoft Word or Apple Pages helps you type regular, plain-English text. Just as there are many brands of toothpaste, soap, and shampoo in the world, there are many brands of code editors that work well with Python. There isn’t a right one or a wrong one, a good one or a bad one, a best one or a worst one. Just a lot of different products that basically do the same thing but vary slightly in their approach and what that editor’s creators think is good. If you’ve already started learning Python and are happy with whatever you’ve been using, you’re welcome to continue using that and ignore our suggestions. If you’re just getting started with this stuff, we suggest you use VS Code, because it’s an excellent, free learning environment.
Page 18
Installing Python and VS Code The editor we recommend and will be using in this book is called Visual Studio Code, officially. But most often, it is spoken or written as VS Code. The main reasons why it’s our favorite follow: It is an excellent editor for learning coding. It is an excellent editor for writing code professionally and is used by millions of professional programmers and developers. It’s relatively easy to learn and use. It works pretty much the same on Windows, Mac, and Linux. It’s free. It integrates beautifully with GitHub Copilot, so you can use modern, generative AI to speed both learning and actual coding. To use VS Code as your editor for learning and doing Python, you need to download and install Python, VS Code, and a VS Code extension. With luck, you already have some experience working with apps, so this won’t be difficult. You will have to follow onscreen instructions as you go along. If faced with any choices you’re not sure about along the way, you can just choose the default (suggested) option. Here are the steps to download and install Python and VS Code: 1. Use any web browser to browse to www.python.org. 2. Click Download and, if asked to select a version, choose the suggested stable version. 3. Open the folder to which you downloaded Python and double- click the icon for the file you downloaded to install Python. You can just follow the onscreen instructions, and accept any suggested defaults, during the installation process. 4. Browse to https://code.visualstudio.com/ and download the current version of VS Code for your operating system.
Page 19
5. Open the folder to which you downloaded Visual Studio code, double-click the icon for the downloaded file, and follow the onscreen instructions to install VS Code. After VS Code is installed, you should be able to start it like any other app in your system. In Windows, click Start and look around on the Start menu for Visual Studio Code icon. On a Mac, you should be able to find it in your Applications folder, or Launchpad. Installing the Python extension To use VS Code for Python coding, you need to install the VS Code Python extension for Python. When you open VS Code, you will see some icons listed down the left side of the window. Placing the mouse cursor over any icon reveals its name. Click the Extensions icon, shown in Figure 1-1, and then enter Python in the Search box at the top of the Extensions panel. Click the Install button with the Python extension from Microsoft (see Figure 1-1). FIGURE 1-1: Obtaining the Python extension in VS Code.
Page 20
When you’ve finished installing the Python extension, you might notice that both Python and Pylance were added as extensions to VS Code. Don’t worry; that’s normal. Pylance just gives you some additional capabilities that make it easier to learn and write Python code within the VS Code editor. To ensure that the extension is activated, exit VS Code and then restart it. Letting AI write your Python code Modern generative AI is perfectly capable of writing Python code for you. It’s not as simple as commanding it to “Write a Python app that will make me a billionaire,” however. It doesn’t work that way — yet. Unfortunately. You need to break things down into smaller chunks, and probably use accurate tech terminology, too. In other words, you still have to learn enough Python to be able to write your AI prompts accurately. Virtually all of these prompts — no matter which AI service you use — will start with “Write python code for …” because AI can do a lot of things. If you don’t tell it, specifically, that you want it to write Python code, you might get no code, HTML, JavaScript, or whatever. So just make sure you understand that, first and foremost. As we write this in late 2023, generative AI is still fairly new and evolving rapidly. We can’t make any promises in terms of pricing or availability. Those things are likely to change often over the coming years, and competing businesses jockey for position and market share. But as of this writing, you can prompt the following AI services to write Python code: ChatGPT (https://chat.openai.com) Claude (https://claude.ai) Google Bard (https://bard.google.com) Microsoft Copilot (https://copilot.microsoft.com) Most of these tools are free (right now), but again, we can’t make any promises about the future.
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List