1. Trang chủ
  2. » Công Nghệ Thông Tin

Begin to code with python rob miles (1)

1,4K 101 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.419
Dung lượng 38,17 MB

Nội dung

Chapter 9 Use classes to store data Chapter 10 Use classes to create active objectsChapter 11 Object-based solution design Chapter 12 Python applications Part 3: Useful Python Digital-on

Trang 2

Rob Miles

Trang 3

www.pearsoned.com/permissions/ No patent liability is assumed with respect to the use of the information contained herein Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions Nor is any liability assumed for damages resulting from the use of the information contained herein.

WARNING AND DISCLAIMER

Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied The information provided is on an “as is” basis The author, the publisher, and Microsoft Corporation shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the programs accompanying it.

SPECIAL SALES

For information about buying this title in bulk quantities, or for special sales opportunities (which may include electronic versions; custom cover designs; and content particular to your business, training goals, marketing focus, or branding interests), please contact our corporate sales department at

Trang 4

Greg Wiegand Senior Acquisitions Editor Laura Norman Development Editor Rick Kughen Managing Editor

Sandra Schroeder Senior Project Editor Tracey Croom Copy Editor

Trang 5

To Mary

Trang 6

Rob Miles has spent more than 30 years teaching programming at the University

of Hull in the United Kingdom He’s a Microsoft MVP, with a passion for

programming, and creating new things If he had any spare time, he’d spend itwriting even more code He loves making programs and then running them tosee what happens He reckons that programming is the most creative thing youcan learn how to do

He believes that programmers really can claim to be building the future

He claims to know a lot of really good jokes, but nobody has ever heard him tellone If you want an insight into the Wacky World™ of Rob Miles, you can readhis blog at www.robmiles.com and follow him on Twitter via @RobMiles

rob@robmiles.com

Trang 7

Chapter 9 Use classes to store data

Chapter 10 Use classes to create active objectsChapter 11 Object-based solution design

Chapter 12 Python applications

Part 3: Useful Python (Digital-only)

The chapter PDF files for this Part are available at

Trang 8

Chapter 13 Python and Graphical User InterfacesChapter 14 Python programs as network clientsChapter 15 Python programs as network serversChapter 16 Create games with Pygame

Trang 9

Introduction Part 1: Programming fundamentals

1 Starting with Python

What is Python?

Python originsPython versionsBuild a place to work with Python

Get the toolsPython for Windows PCStart Python

Thank you!

Trang 10

Programming and problemsProgrammers and peopleComputers as data processors

Machines and computers and usPrograms as data processorsPython as a data processorData and information

Work with Python functions

The ord functionThe chr functionInvestigate data storage using binWhat you have learned

3 Python program structure

Write your first Python program

Run Python programs using IDLEGet program output using the print functionUse Python libraries

The random libraryThe time libraryPython comments

Code samples and commentsRun Python from the desktop

Delay the end of the programAdding some snaps

Adding the Pygame librarySnaps functions

What you have learned

Trang 11

4 Working with variables

Variables in Python

Python namesWorking with text

Marking the start and end of stringsEscape characters in text

Read in text using the input functionWorking with numbers

Convert strings into integer valuesWhole numbers and real numbersReal numbers and floating-point numbersConvert strings into floating-point valuesPerform calculations

Convert between float and intWeather snaps

What you have learned

5 Making decisions in programs

Boolean data

Create Boolean variablesBoolean expressionsComparing valuesBoolean operationsThe if construction

Nesting if conditionsWorking with logicUse decisions to make an application

Design the user interfaceImplement a user interface

Trang 12

What you have learned

6 Repeating actions with loops

The while construction

Repeat a sequence of statements using whileHandling invalid user entry

Detect invalid number entry using exceptionsExceptions and number reading

Handling multiple exceptionsBreak out of loops

Return to the top of a loop with continueCount a repeating loop

The for loop constructionMake a digital clock using snapsWhat you have learned

7 Using functions to simplify programs

What makes a function?

Give information to functions using parametersReturn values from function calls

Build reusable functions

Create a text input functionAdd help information to functionsCreate a number input functionConvert our functions into a Python moduleUse the IDLE debugger

What you have learned

Trang 13

8 Storing collections of data

Lists and tracking sales

Limitations of individual variablesLists in Python

Read in a listDisplay a list using a for loopRefactor programs into functions

Create placeholder functionsCreate a user menu

Sort using bubble sort

Initialize a list with test dataSort a list from high to lowSort a list from low to highFind the highest and lowest sales valuesEvaluate total and average sales

Complete the programStore data in a file

Write into a fileWrite the sales figuresRead from a file

Read the sales figuresDeal with file errorsStore tables of data

Use loops to work with tablesUse lists as lookup tables

TuplesWhat you have learned

Part 2: Advanced programming

Trang 14

9 Use classes to store data

Make a tiny contacts app

Make a prototypeStore contact details in separate listsUse a class to store contact detailsUse the Contact class in the Tiny Contactsprogram

Edit contactsSave contacts in a file using pickleLoad contacts from a file using pickleAdd save and load to Tiny ContactsSet up class instances

Dictionaries

Create a dictionaryDictionary managementReturn a dictionary from a functionUse a dictionary to store contactsWhat you have learned

10 Use classes to create active objects

Create a Time Tracker

Add a data attribute to a classCreate a cohesive objectCreate method attributes for a classAdd validation to methods

Protect a data attribute against damageProtected methods

Create class propertiesEvolve class design

Manage class versions

Trang 15

Python string formattingSession tracking in Time Tracker

The Python map functionThe Python join methodMake music with Snaps

Implement application behaviorsObjects as components

Create a FashionShop component

Create a user interface componentDesign with classes

Python sets

Sets and tagsSets versus class hierarchiesWhat you have learned

12 Python applications

Advanced functions

References to functionsUse lambda expressionsIterator functions and the yield statement

Trang 16

Python modulesAdd a readme function to BTCInputRun a module as a program

Detect whether a module is executed as a programCreate a Python package

Import modules from packagesProgram testing

The Python assert statementThe Python unittest moduleCreate tests

View program documentationWhat you have learned

Create a program file

Trang 17

Create a graphical applicationLay out a grid

Create an event handler functionCreate a mainloop

Handle errors in a graphical user interfaceDisplay a message box

Draw on a CanvasTkinter eventsCreate a drawing programEnter multi-line text

Group display elements in framesCreate an editable StockItem using a GUICreate a Listbox selector

An application with a graphical user interfaceWhat you have learned

14 Python programs as network clients

Computer networkingConsume the web from Python

Read a webpageUse web-based dataWhat you have learned

15 Python programs as network servers

Create a web server in Python

A tiny socket-based serverPython web server

Trang 18

16 Create games with Pygame

Getting started with pygameDraw images with pygame

Image file typesLoad an image into a gameMake an image moveGet user input from pygameCreate game sprites

Add a player spriteControl the player spriteAdd a Cracker spriteAdd lots of sprite instancesCatch the crackers

Add a killer tomatoComplete the game

Add a start screenEnd the gameScore the gameWhat you have learned

Index

Trang 19

Programming is the most creative thing you can learn how to do Why? If youlearn to paint, you can create pictures If you learn to play the violin, you canmake music But if you learn to program, you can create entirely new

experiences (and you can make pictures and music too, if you wish) Once

you’ve started on the programming path, there’s no limit to where you can go.There are always new devices, technologies, and marketplaces where you canuse your programming skills

Think of this book as your first step on a journey to programming enlightenment.The best journeys are undertaken with a destination in mind, and the destination

of this journey is “usefulness.” By the end of this book, you will have the skillsand knowledge to write useful programs

However, before we begin, a small word of warning Just as a guide would want

to tell you about the lions, tigers, and crocodiles that you might encounter on asafari, I must tell you that our journey might not be all smooth going

Programmers must learn to think slightly differently about problem solving,because a computer just doesn’t work the same way humans do Humans can docomplex things rather slowly Computers can do simple things very quickly It isthe programmer’s job to harness the simple abilities of the machine to solvecomplicated problems This is what you’ll learn to do

The key to success as a programmer is much the same as for many other

endeavors To become a world-renowned violin player, you will have to practice

a lot The same is true for programming You must spend a lot of time working

on your programs to acquire code-writing skills However, the good news is thatjust as a violin player really enjoys making the instrument sing, making a

computer do exactly what you want turns out to be a very rewarding experience

It gets even more enjoyable when you see other people using programs that

you’ve written and finding them useful and fun to use

How this book fits together

Trang 20

to do, and we finish by looking at professional software construction

Part 1: Programming fundamentals

The first part gets you started It points you to where you’ll install and use theprogramming tools that you’ll need to begin coding, and it introduces you to thefundamental elements of the Python programming language You’ll come togrips with writing your first programs and learn all the fundamental code

constructions that underpin all programs You’ll also find out where Python fits

in the great scheme of programming languages, and what this means for you as aprogrammer

Part 2: Advanced programming

Part 2 describes the features of the Python programming language used to createand structure more complex applications It shows you how to break large

programs into smaller elements and how you can create custom data types thatreflect the specific problem being solved You’ll also discover how to design,test, and document your Python applications

Part 3: Useful Python

Once you’ve learned how to make your own programs, the next step is to learnhow to use code written by other people An important advantage of Python isthe wealth of software libraries available for users of the language In Part 3,you’ll explore a number of these libraries and find out how you can use them tocreate applications with graphical user interfaces, how Python programs can act

as clients and servers in network applications, and, finally, create engaging

games

The third part of the book is provided as a downloadable document that you canhave open on your desktop as you experiment with the demonstration programsand create applications of your own The chapter PDF files for this Part are

available at https://aka.ms/BeginCodePython/downloads

Trang 21

In each chapter, I will tell you a bit more about programming I’ll show you how

to do something, and then I’ll invite you to make something of your own byusing what you’ve learned You’ll never be more than a page or so away fromdoing something or making something unique and personal After that, it’s up toyou to make something amazing!

You can read the book straight through if you like, but you’ll learn much more ifyou slow down and work with the practical parts along the way Like learning to

ride a bicycle, you’ll learn by doing You must put in the time and practice to

learn how to do it But this book will give you the knowledge and confidence totry your hand at programming, and it will also be around to help you if yourprogramming doesn’t turn out as you expected Here are some elements in thebook that will help you learn by doing:

MAKE SOMETHING HAPPEN

Yes, the best way to learn things is by doing, so you’ll find “Make SomethingHappen” elements throughout the text These elements offer ways for you topractice your programming skills Each starts with an example and then

suggest improvements

Trang 22

If you don’t already know that programs can fail, you’ll learn this hardlesson soon after you begin writing your first program To help you dealwith this in advance, I’ve included “What Could Go Wrong?” elements,which anticipate problems you might have and provide solutions to

those problems For example, when I introduce something new, I’ll

sometimes spend some time considering how it can fail and what youneed to worry about when you use the new feature

PROGRAMMER’S POINT

I’ve spent a lot of time teaching programming But I’ve also written many programs and sold a few

to paying customers I’ve learned some things the hard way that I really wish I’d known at the start The aim of “Programmer’s Points” is to give you this information up front so that you can start taking a professional view of software development as you learn how to do it.

“Programmer’s Points” cover a wide range of issues, from programming to people to philosophy I strongly advise you to read and absorb these points carefully—they can save you a lot of time in the future!

Software and hardware

You’ll need a computer and some software to work with the programs in thisbook I’m afraid I can’t provide you with a computer, but in the first chapteryou’ll find out where you can get the Python tools and an application calledVisual Studio Code that you’ll learn to use when we start creating larger

applications

Using a PC or laptop

You can use Windows, macOS, or Linux to create and run the Python programs

in the text Your PC doesn’t have to be particularly powerful, but these are theminimum specifications I’d recommend:

Trang 23

In every chapter in this book, I’ll demonstrate and explain programs that teachyou how to begin to program—and that you can then use to create programs ofyour own You can download this book’s sample code from the following page:

https://aka.ms/BeginCodePython/downloads

Follow the instructions you’ll find in Chapter 1 to install the sample programsand code

Acknowledgments

I would like to thank Laura Norman for giving me a chance to write this book,Dan Foster and Rick Kughen for putting up with my prose and knocking it intoshape, John Ray for astute and constructive technical insights, and Tracey

Croom and Becky Winter for making it all look so nice I’d also like to say

Trang 24

If you discover an error not already listed, please submit it to us at the samepage

If you need additional support, email Microsoft Press Book Support at

mspinput@microsoft.com

Please note that product support for Microsoft software and hardware is notoffered through the previous addresses For help with Microsoft software orhardware, go to http://support.microsoft.com

Obtaining MTA qualification

The Microsoft Certified Professional program lets you obtain recognition foryour skills Passing the exam 98-381, “Introduction to Programming UsingPython” gives you a Microsoft Technology Associate (MTA) level qualification

in Python programming You can find out more about this examination at

https://www.microsoft.com/en-us/learning/exam-98-381.aspx

To help you get the best out of this text, if you’re thinking of using it as part of aprogram of study to prepare for this exam, I’ve put together a mapping of examtopics to book elements that you may find helpful (Note that these mappings arebased on the exam specification as of October 2017.) I’ve also created an

appendix, which puts some of the elements described in the book into the

context of the exam, and you can find this in the same place as the sample code

Trang 25

https://aka.ms/BeginCodePython/downloads

Qualification structure

The qualification is broken down into a number of topic areas, each of whichcomprises a percentage of the total qualification We can go through each topicarea and identify the elements of this book that apply The tables below map skillitems to sections in chapters of this book

25%)

Perform operations using data types and operators (20-To prepare for this topic, you should pay special attention to Chapter 4, whichdescribes the essentials of data processing in Python programs as well as howtext and numeric data is stored and manipulated Chapter 5 introduces the

Boolean variable type and explains how logical values are manipulated Chapter

8 describes how to store collections of data, and Chapter 9 explains the creationand storage of data structures Chapter 11 gives details of sets in Python

Chapter 4:

Working withtext

Chapter 4:

Working withnumbersChapter 5:

Trang 26

Chapter 5:

Booleanexpressions

Chapter 4:

Convert betweenfloat and int

Chapter 4: Realnumbers andfloating-pointnumbers

Chapter 8: Listsand trackingsales

Chapter 9: Use aclass to storecontact details

Chapter 9:

Contact objectsand referencesChapter 11: Setsand tags

Trang 27

Booleanexpressions

Control flow with decisions and loops (25-30%)

To prepare for this topic, you should pay special attention to Chapter 5, whichdescribes the if construction, and Chapter 6, which moves on to describe thewhile and for loop constructions that are used to implement looping inPython programs

if; elif; else; nested and compound conditional

expressions

Chapter 5: The ifconstruction

Construct and analyze code segments that perform

iteration

Chapter 6: Thewhile

construction

Chapter 6: Thefor loop

constructionChapter 6: Thewhile

Trang 28

loops that include compound conditional expressions

construction

Chapter 6: Thefor loop

construction

Chapter 8: Sortusing bubble sortPerform input and output operations (20-25%)

The use of console input and output functions is demonstrated throughout thebook, starting with the very first programs described in Chapters 3 and 4

Chapter 8 introduces the use of file storage in Python programs, and Chapter 9expands on this to show how data structures can be saved into files by the use ofthe Python pickle library Chapter 10 contains details of the string formattingfacilities available to Python programs

Chapter 9: Savecontacts in afile using pickle

Chapter 4: Read

in text using theinput function

Trang 29

The importance of well-structured and documented code is highlighted

throughout the text Chapter 3 introduces Python comments, and Chapter 5

contains a discussion highlighting the importance of good code layout Chapter 7introduces Python functions in the context of improving program structure anddescribes how to add documentation to functions to make programs self-

Chapter 5:Indented textcan causehuge problems

Chapter 7:Add helpinformation tofunctions

Chapter 12:View programdocumentation

Construct and analyze code segments that include

function definitions: call signatures; default values;

return; def; pass

Chapter 7:What makes afunction?

Trang 30

Chapter 3 contains coverage of syntax errors in Python code In Chapter 4, thedescription of data processing includes descriptions of runtime errors In

Chapters 6 and 7, the causes and effects of logic errors are discussed in the

context of an application development Chapters 6 and 10 contain descriptions ofhow Python programs can raise and manage exceptions, and Chapter 12 contains

Chapter 4: Typing errorsand testing

Chapter 5: Equality andfloating-point values

Chapter 6: When goodloops go bad

Chapter 7: Investigateprograms with thedebugger

Chapter 12: Programtesting

Analyze and construct code segments that

handle exceptions: try; except; else; finally;

raise

Chapter 6: Detect invalidnumber entry usingexceptions

Chapter 10: Raise anexception to indicate anerror

Trang 31

Many Python modules are used throughout the text, starting with the random andtime modules The functions from the random library are used in Chapter 13 tocreate random artwork, and functions from the time library are used in a time-tracking application used in Chapter 16

Perform basic operations using built-in modules:

math; datetime; io; sys; os; os.path; random

Chapter 3: Therandom library

Chapter 3: The timelibrary

Solve complex computing problems by using

built-in modules: math; datetime; random

Chapter 10: Sessiontracking in TimeTracker

Chapter 16: Makingart

Free e-books from Microsoft Press

books from Microsoft Press cover a wide range of topics These e-books areavailable in PDF, EPUB, and Mobi for Kindle formats, ready for you to

From technical overviews to in-depth information on specific topics, the free e-download at: https://aka.ms/mspressfree

Check back often to see what’s new!

We want to hear from you

At Microsoft Press, your satisfaction is our top priority, and your feedback is ourmost valuable asset Please tell us what you think of this book at:

https://aka.ms/tellpress

Trang 32

Stay in touch

Let’s keep the conversation going! We’re on Twitter:

http://twitter.com/MicrosoftPress

Trang 33

Part 1 Programming fundamentals

Trang 34

things for you.The aim of Part 1 is to introduce you to fundamental elements of the Python

programming language used by all programs

Trang 35

What you will learn

We’ll start with a discussion about Python, the programming language you’relearning Then you’ll discover what kind of computer you need to writeprograms and how to find and install the tools you’ll use to build your code.You’ll also have your first of many interactions with the Python Shell anddiscover that programming-language designers do have a sense of humor

What is Python?

Build a place to work with Python

Start Python

Trang 36

Step1: Take a hot bath

Step2: Drink your medicine

A programming language forces us to write instructions in this way Python isone of many programming languages invented to provide humans with a way oftelling the computer what to do

In my programming career, I’ve learned many different languages over the

years, and I confidently expect to need to learn even more in the future None ofthem are perfect, and I see each of them as a tool that I would use in a particular

Trang 37

Some people get very excited when talking about the “best” programming

language I’m quite happy to discuss what makes the best programming

languages, just as I’m happy to tell you all about my favorite type of car, but Idon’t see this as something to get worked up about I love Python for its powerand expressiveness I love the C# programming language for the way it pushes

me to produce well-structured solutions I love the C++ programming languagefor the way it gives me absolute control of hardware underneath my program.And so on Python does have things about it that make me want to tear my hairout in frustration, but that’s true of the other languages, too And all

programming languages have aspects about them that I love And I love using all

of them

Python origins

You might think that programming languages are a bit like space rockets in thatthey are designed by white-coated scientists with mega-brains who get

everything right the first time and always produce perfect solutions However,this is not the case Programming languages have been developed over the yearsfor all kinds of reasons, including reasons as simple as “It seemed like a goodidea at the time.”

Guido van Rossum, the original developer of Python, had no idea just what hewas starting when, in late 1989, he decided to spend a few weeks on a hobbyprogramming project that he could work on while his office at work was closedduring Christmas He named this language “Python,” not because of a liking forsnakes, but because he was an enthusiastic fan of the British TV comedy show

Monty Python’s Flying Circus However, the language was picked up by

programmers the world over who loved its elegance and power Python is nowone of the most popular programming languages in use today

Python versions

One of the first things you’ll discover about Python is that many versions of thelanguage are available From a programmer’s point of view, this is not terriblyhelpful Programs you write for one version of Python are not guaranteed towork with another version Python lets you use parts of other people’s programs

Trang 38

version Over the years, the different versions of the language have resolved intotwo distinct strands of development, which simplifies things somewhat

Essentially the choice of which version of Python you’ll use boils down to a

choice of version 2.7 or version 3.n (where n is a number that keeps increasing).

Version 2.7 (the old stalwart) is great because a lot of existing softwareuses version 2.7 If you’re looking for a library of Python code to perform

The good news is that the fundamentals of program creation are the same forboth versions of Python—and indeed for just about all programming languages.Once you’ve learned how to write Python programs, you’ll be able to transferthis skill into many other languages, including C++, C#, Visual Basic, and

JavaScript

Just as you can drive just about any vehicle once you learn the fundamentals ofdriving, you can transfer your Python programming skills to other programminglanguages When driving a new car, you just need to locate the various switchesand controls before setting off on your journey The same holds true with

programming

Build a place to work with Python

If you were a truck driver who spends many hours in the cab hauling goodsacross the country, you’d want a truck with a comfortable seat, an unobstructedview of the road, and controls that are easy to find and use It would also help ifyour truck had enough power to climb hills at a reasonable speed and was easy

to handle on twisting mountainside roads

Trang 39

writing programs, you should have a decent place to work Find somewhere toset up a PC, keyboard, and monitor Pull up a chair that you don’t mind spendingquite a few hours sitting in

You don’t need a particularly fancy computer for writing programs, but your PCwill need a reasonable amount of memory and processor performance to handlethe tools we’ll use I suggest using a device with at least an Intel i5 or equivalentprocessor, 4 GB of memory, and 256 GB of hard drive space You can use

smaller computers, but they can make the development process somewhat

frustrating because they will take a while to update your program after you makechanges to it

provide The good news is that you need to perform this installation only oncefor each computer you want to use

All the tools we’ll use are free to download and install I find it astonishing andwonderful that such powerful software is available for free for anyone to use.The Python distribution makes it easy for you to get started writing programs,and the Visual Studio Code editor is a great environment for creating large

applications

The tools and how you obtain them are slightly different for the different devicesthat you might be using You can download the latest, up-to-date, instructionshere:

www.begintocodewithpython.com/tools/

Trang 40

If you have a Windows PC, you can download and install Python from the

Python website You’ll download the installer from the Python download siteand then run it to install Python on your Windows PC I used the Microsoft Edgebrowser If you use a different browser, you’ll see slightly different screens, so

my advice would be to perform the following steps using Edge

Be sure that you are using the official download site (the one given below) andallow the installer to run when asked by Windows

www.python.org/downloads/

Figure 1-1 shows the download page for Python

Figure 1-1 Python download page

The web page has determined that I am using a Windows PC and has offered metwo versions to download On the download page, you’ll want to download

version 3.6.1 of Python, so click this button to start the download.

The browser will ask what you want to do with the file If you’re using

Ngày đăng: 12/04/2019, 00:25

TỪ KHÓA LIÊN QUAN

w