Python Basics: A Practical Introduction To Python 3

3y ago
1.8K Views
421 Downloads
1.48 MB
98 Pages
Last View : 4d ago
Last Download : 1m ago
Upload by : Eli Jorgenson
Transcription

Python Basics: A Practical Introductionto Python 3Real Python

Python Basics: A Practical Introduction to Python 3Revised and Updated 4th EditionDavid Amos, Dan Bader, Joanna Jablonski, Fletcher HeislerCopyright Real Python (realpython.com), 2012–2020For online information and ordering of this and other books by RealPython, please visit realpython.com. For more information, pleasecontact us at info@realpython.com.ISBN: 9781775093329 (paperback)ISBN: 9781775093336 (electronic)Cover design by Aldren SantosAdditional editing and proofreading by Jacob Schmitt“Python” and the Python logos are trademarks or registered trademarks of the Python Software Foundation, used by Real Python withpermission from the Foundation.Thank you for downloading this ebook. This ebook is licensed for yourpersonal enjoyment only. This ebook may not be resold or given awayto other people. If you would like to share this book with another person, please purchase an additional copy for each recipient. If you’rereading this book and did not purchase it, or if it was not purchased foryour use only, then please return to realpython.com/pybasics-bookand purchase your own copy. Thank you for respecting the hard workbehind this book.

This is a sample from “Python Basics: A PracticalIntroduction to Python 3”With the full version of the book you get a complete Python curriculumto go all the way from beginner to intermediate-level. Every step alongthe way is explained and illustrated with short & clear code samples.Coding exercises within each chapter and our interactive quizzes helpfast-track your progress and ensure you always know what to focus onnext.Become a fluent Pythonista and gain programming knowledge youcan apply in the real-world, today:If you enjoyed the sample chapters you can purchase a fullversion of the book at realpython.com/pybasics-book

What Pythonistas Say About Python Basics: A Practical Introduction to Python 3“I love [the book]! The wording is casual, easy to understand, andmakes the information ow well. I never feel lost in the material, andit’s not too dense so it’s easy for me to review older chapters over andover.I’ve looked at over 10 di erent Python tutorials/books/online courses,and I’ve probably learned the most from Real Python!”— Thomas Wong“Three years later and I still return to my Real Python books when Ineed a quick refresher on usage of vital Python commands.”— Rob Fowler“I oundered for a long time trying to teach myself. I slogged throughdozens of incomplete online tutorials. I snoozed through hours of boring screencasts. I gave up on countless crufty books from big-timepublishers. And then I found Real Python.The easy-to-follow, step-by-step instructions break the big conceptsdown into bite-sized chunks written in plain English. The authorsnever forget their audience and are consistently thorough and detailedin their explanations. I’m up and running now, but I constantly referto the material for guidance.”— Jared Nielsen

“I love the book because at the end of each particular lesson there arereal world and interesting challenges. I just built a savings estimatorthat actually re ects my savings account – neat!”— Drew Prescott“As a practice of what you taught I started building simple scripts forpeople on my team to help them in their everyday duties. When mymanagers noticed that, I was o ered a new position as a developer.I know there is heaps of things to learn and there will be huge challenges, but I nally started doing what I really came to like.Once again: MANY THANKS!”— Kamil“What I found great about the Real Python courses compared to othersis how they explain things in the simplest way possible.A lot of courses, in any discipline really, require the learning of a lot ofjargon when in fact what is being taught could be taught quickly andsuccinctly without too much of it. The courses do a very good job ofkeeping the examples interesting.”— Stephen Grady“After reading the rst Real Python course I wrote a script to automatea mundane task at work. What used to take me three to ve hours nowtakes less than ten minutes!”— Brandon Youngdale

“Honestly, throughout this whole process what I found was just melooking really hard for things that could maybe be added or improved,but this tutorial is amazing! You do a wonderful job of explaining andteaching Python in a way that people like me, a complete novice, couldreally grasp.The ow of the lessons works perfectly throughout. The exercises trulyhelped along the way and you feel very accomplished when you nishup the book. I think you have a gift for making Python seem moreattainable to people outside the programming world.This is something I never thought I would be doing or learning andwith a little push from you I am learning it and I can see that it will benothing but bene cial to me in the future!”— Shea Klusewicz“The authors of the courses have NOT forgotten what it is like to bea beginner – something that many authors do – and assume nothing about their readers, which makes the courses fantastic reads. Thecourses are also accompanied by some great videos as well as plentyof references for extra learning, homework assignments and examplecode that you can experiment with and extend.I really liked that there was always full code examples and each lineof code had good comments so you can see what is doing what.I now have a number of books on Python and the Real Python onesare the only ones I have actually nished cover to cover, and theyare hands down the best on the market. If like me, you’re not a programmer (I work in online marketing) you’ll nd these courses to belike a mentor due to the clear, u -free explanations! Highly recommended!”— Craig Addyman

About the AuthorsAt Real Python you’ll learn real-world programming skills from a community of professional Pythonistas from all around the world.The realpython.com website launched in 2012 and currently helpsmore than three million Python developers each month with freeprogramming tutorials and in-depth learning resources.Everyone who worked on this book is a practitioner with several yearsof professional experience in the software industry. Here are the members of the Real Python tutorial team who worked on Python Basics:David Amos is the content technical lead for Real Python. After leaving academia in 2015, David worked in various technical positions asa programmer and data scientist. In 2019, David joined Real Pythonfull time to pursue his passion for education. He lead the charge onrewriting and updating the Python Basics curriculum to Python 3.Dan Bader is the owner and editor in chief of Real Python and themain developer of the realpython.com learning platform. Dan hasbeen writing code for more than twenty years and holds a master’sdegree in computer science. He’s the author of Python Tricks, a bestselling programming book for intermediate Python developers.Joanna Jablonski is the executive editor of Real Python. She likesnatural languages just as much as she likes programming languages.Her love for puzzles, patterns, and pesky little details led her to followa career in translation. It was only a matter of time before she wouldfall in love with a new language: Python! She joined Real Python in2018 and has been helping Pythonistas level up ever since.Fletcher Heisler is the founder of Hunter2, where he teaches developers how to hack and secure modern web apps. As one of thefounding members of Real Python, Fletcher wrote the first version ofthe Python curriculum this book is based on in 2012.

ContentsContents8Foreword1234Introduction1.1 Why This Book? . . . . . . . . . . . . .1.2 About Real Python . . . . . . . . . . .1.3 How to Use This Book . . . . . . . . . .1.4 Bonus Material and Learning ResourcesSetting Up Python2.1 A Note on Python Versions2.2 Windows . . . . . . . . .2.3 macOS . . . . . . . . . . .2.4 Ubuntu Linux . . . . . . .13.Your First Python Program3.1 Write a Python Program . . . . . . . . .3.2 Mess Things Up . . . . . . . . . . . . . .3.3 Create a Variable . . . . . . . . . . . . .3.4 Inspect Values in the Interactive Window3.5 Leave Yourself Helpful Notes . . . . . . .3.6 Summary and Additional Resources . . .Strings and String Methods4.1 What Is a String? . . . . . . . . . . . . . . . . . . .4.2 Concatenation, Indexing, and Slicing . . . . . . . . .82021232425293031343742434750555860626369

Contents56784.34.44.54.64.74.84.94.10Manipulate Strings With Methods . . . . . .Interact With User Input . . . . . . . . . . .Challenge: Pick Apart Your User’s Input . . .Working With Strings and Numbers . . . . .Streamline Your Print Statements . . . . . .Find a String in a String . . . . . . . . . . . .Challenge: Turn Your User Into a L33t H4x0rSummary and Additional Resources . . . . .Numbers and Math5.1 Integers and Floating-Point Numbers . . . . .5.2 Arithmetic Operators and Expressions . . . . .5.3 Challenge: Perform Calculations on User Input5.4 Make Python Lie to You . . . . . . . . . . . . .5.5 Math Functions and Number Methods . . . . .5.6 Print Numbers in Style . . . . . . . . . . . . .5.7 Complex Numbers . . . . . . . . . . . . . . .5.8 Summary and Additional Resources . . . . . .Functions and Loops6.1 What Is a Function, Really? . . . . .6.2 Write Your Own Functions . . . . .6.3 Challenge: Convert Temperatures .6.4 Run in Circles . . . . . . . . . . . .6.5 Challenge: Track Your Investments .6.6 Understand Scope in Python . . . .6.7 Summary and Additional Resources. 79. 85. 88. 88. 94. 96. 99. 57162Finding and Fixing Code Bugs1647.1 Use the Debug Control Window . . . . . . . . . . . 1657.2 Squash Some Bugs . . . . . . . . . . . . . . . . . . 1717.3 Summary and Additional Resources . . . . . . . . . 179Conditional Logic and Control Flow1818.1 Compare Values . . . . . . . . . . . . . . . . . . . . 1828.2 Add Some Logic . . . . . . . . . . . . . . . . . . . . 1868.3 Control the Flow of Your Program . . . . . . . . . . 1949

Contents98.48.58.68.78.88.98.10Challenge: Find the Factors of a Number . .Break Out of the Pattern . . . . . . . . . .Recover From Errors . . . . . . . . . . . .Simulate Events and Calculate ProbabilitiesChallenge: Simulate a Coin Toss ExperimentChallenge: Simulate an Election . . . . . .Summary and Additional Resources . . . .Tuples, Lists, and Dictionaries9.1 Tuples Are Immutable Sequences . . . . . . . .9.2 Lists Are Mutable Sequences . . . . . . . . . .9.3 Nesting, Copying, and Sorting Tuples and Lists9.4 Challenge: List of lists . . . . . . . . . . . . . .9.5 Challenge: Wax Poetic . . . . . . . . . . . . .9.6 Store Relationships in Dictionaries . . . . . . .9.7 Challenge: Capital City Loop . . . . . . . . . .9.8 How to Pick a Data Structure . . . . . . . . . .9.9 Challenge: Cats With Hats . . . . . . . . . . .9.10 Summary and Additional Resources . . . . . .10 Object-Oriented Programming (OOP)10.1 Define a Class . . . . . . . . . . . . .10.2 Instantiate an Object . . . . . . . . .10.3 Inherit From Other Classes . . . . . .10.4 Challenge: Model a Farm . . . . . . .10.5 Summary and Additional Resources .11 Modules and Packages11.1 Working With Modules . . . . . . . . . . . . . . . .11.2 Working With Packages . . . . . . . . . . . . . . . .11.3 Summary and Additional Resources . . . . . . . . .12 File Input and Output12.1 Files and the File System . . . . . . . . . . . . . .12.2 Working With File Paths in Python . . . . . . . . .12.3 Common File System Operations . . . . . . . . . .12.4 Challenge: Move All Image Files to a New 32433335010

Contents12.512.612.712.8Reading and Writing Files . . . . .Read and Write CSV Data . . . . . .Challenge: Create a High Scores ListSummary and Additional Resources.35136637737813 Installing Packages With pip37913.1 Installing Third-Party Packages With pip . . . . . . . 38013.2 The Pitfalls of Third-Party Packages . . . . . . . . . 39013.3 Summary and Additional Resources . . . . . . . . . 39214 Creating and Modifying PDF Files14.1 Extracting Text From a PDF . . . .14.2 Extracting Pages From a PDF . . . .14.3 Challenge: PdfFileSplitter Class . .14.4 Concatenating and Merging PDFs .14.5 Rotating and Cropping PDF Pages .14.6 Encrypting and Decrypting PDFs . .14.7 Challenge: Unscramble a PDF . . .14.8 Creating a PDF File From Scratch .14.9 Summary and Additional Resources.39439540240941041742843343344016 Interacting With the Web16.1 Scrape and Parse Text From Websites .16.2 Use an HTML Parser to Scrape Websites16.3 Interact With HTML Forms . . . . . . .16.4 Interact With Websites in Real Time . .16.5 Summary and Additional Resources . .458459469475481485.15 Working With Databases44215.1 An Introduction to SQLite . . . . . . . . . . . . . . 44315.2 Libraries for Working With Other SQL Databases . . 45515.3 Summary and Additional Resources . . . . . . . . . 45617 Scienti c Computing and Graphing17.1 Use NumPy for Matrix Manipulation . . . . . . . . .17.2 Use Matplotlib for Plotting Graphs . . . . . . . . . .17.3 Summary and Additional Resources . . . . . . . . .48748849952211

Contents18 Graphical User Interfaces18.1 Add GUI Elements With EasyGUI . . . . . .18.2 Example App: PDF Page Rotator . . . . . . .18.3 Challenge: PDF Page Extraction Application .18.4 Introduction to Tkinter . . . . . . . . . . . .18.5 Working With Widgets . . . . . . . . . . . .18.6 Controlling Layout With Geometry

WhatPythonistasSayAboutPython Basics: A Practical In- troductiontoPython3 “I love [the book]! The wording is casual, easy to understand, and makestheinformation @owwell. Ineverfeellostinthematerial,and

Related Documents:

Python Basics.ipynb* Python Basics.toc* Python Basics.log* Python Basics_files/ Python Basics.out* Python_Basics_fig1.pdf* Python Basics.pdf* Python_Basics_fig1.png* Python Basics.synctex.gz* Python_Basics_figs.graffle/ If you are reading the present document in pdf format, you should consider downloading the notebook version so you can follow .

Python Programming for the Absolute Beginner Second Edition. CONTENTS CHAPTER 1 GETTING STARTED: THE GAME OVER PROGRAM 1 Examining the Game Over Program 2 Introducing Python 3 Python Is Easy to Use 3 Python Is Powerful 3 Python Is Object Oriented 4 Python Is a "Glue" Language 4 Python Runs Everywhere 4 Python Has a Strong Community 4 Python Is Free and Open Source 5 Setting Up Python on .

Python 2 versus Python 3 - the great debate Installing Python Setting up the Python interpreter About virtualenv Your first virtual environment Your friend, the console How you can run a Python program Running Python scripts Running the Python interactive shell Running Python as a service Running Python as a GUI application How is Python code .

Python is readable 5 Python is complete—"batteries included" 6 Python is cross-platform 6 Python is free 6 1.3 What Python doesn't do as well 7 Python is not the fastest language 7 Python doesn't have the most libraries 8 Python doesn't check variable types at compile time 8 1.4 Why learn Python 3? 8 1.5 Summary 9

site "Python 2.x is legacy, Python 3.x is the present and future of the language". In addition, "Python 3 eliminates many quirks that can unnecessarily trip up beginning programmers". However, note that Python 2 is currently still rather widely used. Python 2 and 3 are about 90% similar. Hence if you learn Python 3, you will likely

There are currently two versions of Python in use; Python 2 and Python 3. Python 3 is not backward compatible with Python 2. A lot of the imported modules were only available in Python 2 for quite some time, leading to a slow adoption of Python 3. However, this not really an issue anymore. Support for Python 2 will end in 2020.

Launch Eclipse Install Python plug-in for Eclipse Add a Python Interpreter Create a Python Project Create a Python Program Run a Python Program Debug a Python Program 0 Introduction This tutorial is for students who want to develop Python projects using Eclipse. E

Introduction to basic Python Contents 1. Installing Python 2. How to run Python code 3. How to write Python code 4. How to troubleshoot Python code 5. Where to go to learn more Python is an astronomer's secret weapon. With Python, the process of visualizing, processing, and interacting with data is made extremely simple.