id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
9,400 | in this exampleif filename txt does not existan input/output exception called ioerror is generated on the other handif the file does existthere may be certain things that we want to do with it we can put those in the else block try/finally and with/as there is one more block you can use called finally things in the finally block are things that must be executed whether or not an exception occurs so even if an exception occurs and your program crashesthe statements in the finally block will be executed one such thing is closing file if you just put the file closing after the try block and not in the finally blockthe program would crash before getting to close the file open'filename txt '' ' 'hi trysome code that could potentially fail goes here finallyf close(the finally block can be used along with except and else blocks this sort of thing with files is common enough that it is has its own syntaxs 'hi with open'filename txt 'as fprint(sfile=fthis is an example of something called context manager context managers and try/finally are mostly used in more complicated applicationslike network programming more with exceptions there is lot more that can be done with exceptions see the python documentation [ for all the different types of exceptions in factnot all exceptions come from errors there is even statement called raise that you can use to raise your own exceptions this is useful if you are writing your own classes to be used in other programs and you want to send messageslike error messagesto people who are using your class |
9,401 | exceptions |
9,402 | published byjohn wiley sonsinc river streethobokennj - www wiley com copyright ( by john wiley sonsinc hobokennew jersey media and software compilation copyright ( by john wiley sonsinc all rights reserved published simultaneously in canada no part of this publication may be reproducedstored in retrieval system or transmitted in any form or by any meanselectronicmechanicalphotocopyingrecordingscanning or otherwiseexcept as permitted under sections or of the united states copyright actwithout the prior written permission of the publisher requests to the publisher for permission should be addressed to the permissions departmentjohn wiley sonsinc river streethobokennj ( - fax ( - or online at trademarkswileyfor dummiesthe dummies man logodummies commaking everything easierand related trade dress are trademarks or registered trademarks of john wiley sonsinc and may not be used without written permission python is registered trademark of python software foundation corporation all other trademarks are the property of their respective owners john wiley sonsinc is not associated with any product or vendor mentioned in this book limit of liability/disclaimer of warrantythe 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 warrantiesincluding without limitation warranties of fitness for 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 legalaccountingor other professional services if professional assistance is requiredthe services of 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 citation and/or 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 furtherreaders 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 servicesplease contact our customer care department within the at outside the at or fax for technical supportplease visit www wiley com/techsupport wiley publishes in 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 -books or in print-on-demand if this book refers to media such as cd or dvd that is not included in the version you purchasedyou may download this material at www wiley com library of congress control number isbn - - (pbk)isbn - - (ebk)isbn epdf - - (ebkmanufactured in the united states of america |
9,403 | introduction part igetting started with python talking to your computer getting your own copy of python interacting with python writing your first application part iitalking the talk storing and modifying information managing information making decisions performing repetitive tasks dealing with errors part iiiperforming common tasks interacting with modules working with strings managing lists collecting all sorts of data creating and using classes part ivperforming advanced tasks storing data in files sending an -mail part vthe part of tens ten amazing programming resources ten ways to make living with py thon ten interesting tools ten libraries you need to know about index |
9,404 | introduction about this book foolish assumptions icons used in this book beyond the book where to go from here part igetting started with python talking to your computer understanding why you want to talk to your computer knowing that an application is form of communication thinking about procedures you use daily writing procedures down seeing applications as being like any other procedure understanding that computers take things literally defining what an application is understanding that computers use special language helping humans speak to the computer understanding why python is so cool unearthing the reasons for using python deciding how you can personally benefit from python discovering which organizations use python finding useful python applications comparing python to other languages getting your own copy of python downloading the version you need installing python working with windows working with the mac working with linux accessing python on your machine using windows using the mac using linux testing your installation |
9,405 | beginning programming with python for dummies interacting with python opening the command line starting python using the command line to your advantage using python environment variables to your advantage typing command telling the computer what to do telling the computer you're done seeing the result using help getting into help mode asking for help leaving help mode obtaining help directly closing the command line writing your first application understanding the integrated development environment (idle starting idle using standard commands understanding color coding getting gui help configuring idle creating the application opening new window typing the command saving the file running the application understanding the use of indentation adding comments understanding comments using comments to leave yourself reminders using comments to keep code from executing loading and running existing applications using the command line or terminal window using the edit window using the python shell window or python command line closing idle part iitalking the talk storing and modifying information storing information seeing variables as storage boxes using the right box to store the data |
9,406 | defining the essential python data types putting information into variables understanding the numeric types understanding boolean values understanding strings working with dates and times managing information controlling how python views data making comparisons understanding how computers make comparisons working with operators defining the operators understanding operator precedence creating and using functions viewing functions as code packages understanding code reusability defining function accessing functions sending information to functions returning information from functions comparing function output getting user input making decisions making simple decisions using the if statement understanding the if statement using the if statement in an application choosing alternatives using the if else statement understanding the if else statement using the if else statement in an application using the if elif statement in an application using nested decision statements using multiple if or if else statements combining other types of decisions performing repetitive tasks processing data using the for statement understanding the for statement creating basic for loop controlling execution with the break statement controlling execution with the continue statement controlling execution with the pass clause controlling execution with the else statement ix |
9,407 | beginning programming with python for dummies processing data using the while statement understanding the while statement using the while statement in an application nesting loop statements dealing with errors knowing why python doesn' understand you considering the sources of errors classifying when errors occur distinguishing error types catching exceptions basic exception handling handling more specific to less specific exceptions nested exception handling raising exceptions raising exceptions during exceptional conditions passing error information to the caller creating and using custom exceptions using the finally clause part iiiperforming common tasks interacting with modules creating code groupings importing modules using the import statement using the from import statement finding modules on disk viewing the module content using the python module documentation opening the pydoc application using the quick-access links typing search term viewing the results working with strings understanding that strings are different defining character using numbers using characters to create strings creating stings with special characters selecting individual characters slicing and dicing strings locating value in string formatting strings |
9,408 | managing lists organizing information in an application defining organization using lists understanding how computers view lists creating lists accessing lists looping through lists modifying lists searching lists sorting lists working with the counter object collecting all sorts of data understanding collections working with tuples working with dictionaries creating and using dictionary replacing the switch statement with dictionary creating stacks using lists working with queues working with deques creating and using classes understanding the class as packaging method considering the parts of class creating the class definition considering the built-in class attributes working with methods working with constructors working with variables using methods with variable argument lists overloading operators creating class using the class in an application extending classes to make new classes building the child class testing the class in an application part ivperforming advanced tasks storing data in files understanding how permanent storage works creating content for permanent storage creating file xi |
9,409 | beginning programming with python for dummies reading file content updating file content deleting file sending an -mail understanding what happens when you send -mail viewing -mail as you do letter defining the parts of the envelope defining the parts of the letter creating the -mail message working with text message working with an html message seeing the -mail output part vthe part of tens ten amazing programming resources working with the python documentation online using the learnpython org tutorial performing web programming using python getting additional libraries creating applications faster using an ide checking your syntax with greater ease using xml to your advantage getting past the common python newbie errors understanding unicode making your python application fast ten ways to make living with py thon working in qa becoming the it staff for smaller organization performing specialty scripting for applications administering network teaching programming skills helping people decide on location performing data mining interacting with embedded systems carrying out scientific tasks performing real-time analysis of data |
9,410 | ten interesting tools tracking bugs with roundup issue tracker creating virtual environment using virtualenv installing your application using pyinstaller building developer documentation using pdoc developing application code using komodo edit debugging your application using pydbgr entering an interactive environment using ipython testing python applications using pyunit tidying your code using isort providing version control using mercurial ten libraries you need to know about developing secure environment using pycrypto interacting with databases using sqlalchemy seeing the world using google maps adding graphical user interface using tkinter providing nice tabular data presentation using prettytable enhancing your application with sound using pyaudio manipulating images using pyqtgraph locating your information using irlib creating an interoperable java environment using jpype accessing local network resources using twisted matrix accessing internet resources using libraries index xiii |
9,411 | beginning programming with python for dummies |
9,412 | uickwhich programming language will get you up and running writing applications on every popular platform aroundgive upyesit' python the amazing thing about python is that you really can write an application on one platform and use it on every other platform that you need to support unlike the other programming languages that promised to provide platform independencepython really does make that independence possible in this casethe promise is as good as the result you get python emphasizes code readability and concise syntax that lets you write applications using fewer lines of code than other programming languages require in additionbecause of the way python worksyou find it used in all sorts of fields that are filled with nonprogrammers some people view python as scripted languagebut it really is so much more provides you with just an inkling of the occupations that rely on python to make things work about this book beginning programming with python for dummies is all about getting up and running with python quickly you want to learn the language fast so that you can become productive in using it to perform your real jobwhich could be anything unlike most books on the topicthis one starts you right at the beginning by showing you what makes python different from other languages and how it can help you perform useful work in job other than programming as resultyou gain an understanding of what you need to do from the startusing hands-on examples and spending good deal of time performing actually useful tasks you even get help with installing python on your particular system when you have good installation on whatever platform you're usingyou start with the basics and work your way up by the time you finish working through the examples in this bookyou'll be writing simple programs and |
9,413 | beginning programming with python for dummies performing tasks such as sending an -mail using python noyou won' be an expertbut you will be able to use python to meet specific needs in the job environment to make absorbing the concepts even easierthis book uses the following conventionstext that you're meant to type just as it appears in the book is bold the exception is when you're working through step listbecause each step is boldthe text to type is not bold when you see words in italics as part of typing sequenceyou need to replace that value with something that works for you for exampleif you see "type your name and press enter,you need to replace your name with your actual name web addresses and programming code appear in monofont if you're reading digital version of this book on device connected to the internetnote that you can click the web address to visit that websitelike thiswww dummies com when you need to type command sequencesyou see them separated by special arrowlike thisfilenew file in this caseyou go to the file menu first and then select the new file entry on that menu the result is that you see new file created foolish assumptions you might find it difficult to believe that 've assumed anything about you -after alli haven' even met you yetalthough most assumptions are indeed foolishi made these assumptions to provide starting point for the book it' important that you're familiar with the platform you want to use because the book doesn' provide any guidance in this regard does provide python installation instructions for various platforms in order to provide you with maximum information about pythonthis book doesn' discuss any platform-specific issues you really do need to know how to install applicationsuse applicationsand generally work with your chosen platform before you begin working with this book this book also assumes that you can find things on the internet sprinkled throughout are numerous references to online material that will enhance your learning experience howeverthese added sources are useful only if you actually find and use them |
9,414 | icons used in this book as you read this bookyou see icons in the margins that indicate material of interest (or notas the case may bethis section briefly describes each icon in this book tips are nice because they help you save time or perform some task without lot of extra work the tips in this book are time-saving techniques or pointers to resources that you should try in order to get the maximum benefit from python don' want to sound like an angry parent or some kind of maniacbut you should avoid doing anything marked with warning icon otherwiseyou could find that your program only serves to confuse userswho will then refuse to work with it whenever you see this iconthink advanced tip or technique you might find these tidbits of useful information just too boring for wordsor they could contain the solution you need to get program running skip these bits of information whenever you like if you don' get anything else out of particular or sectionremember the material marked by this icon this text usually contains an essential process or bit of information that you must know to write python programs successfully beyond the book this book isn' the end of your python programming experience -it' really just the beginning provide online content to make this book more flexible and better able to meet your needs that wayas receive -mail from youi can do things like address questions and tell you how updates to either python or its associated libraries affect book content in factyou gain access to all these cool additionscheat sheetyou remember using crib notes in school to make better mark on testdon' youyou dowella cheat sheet is sort of like that it provides you with some special notes about tasks that you can do with python that not every other developer knows you can find the cheat sheet for this book at inningprogrammingwithpython it contains really neat information like the top ten mistakes developers make when working with python and some of the python syntax that gives most developers problems |
9,415 | beginning programming with python for dummies dummies com online articlesa lot of readers were skipping past the parts pages in the bookso decided to remedy that you now have really good reason to read the parts pagesand that' online content every parts page has an article associated with it that provides additional interesting information that wouldn' fit in the book you can find the articles for this book at nningprogrammingwithpython updatessometimes changes happen for examplei might not have seen an upcoming change when looked into my crystal ball during the writing of this book in the pastthat simply meant the book would become outdated and less usefulbut you can now find updates to the book at gwithpython in addition to these updatescheck out the blog posts with answers to reader questions and demonstrations of useful book-related techniques at companion filesheywho really wants to type all the code in the bookmost readers would prefer to spend their time actually working through coding examplesrather than typing fortunately for youthe source code is available for downloadso all you need to do is read the book to learn python coding techniques each of the book examples even tells you precisely which example project to use you can find these files at www dummies com/extras/beginningprogrammingwithpython where to go from here it' time to start your programming with python adventureif you're complete programming noviceyou should start with and progress through the book at pace that allows you to absorb as much of the material as possible if you're novice who' in an absolute rush to get going with python as quickly as possibleyou could skip to with the understanding that you may find some topics bit confusing later skipping to is possible if you already have python installedbut be sure to at least skim so that you know what assumptions were made when writing this book readers who have some exposure to python can save time by moving directly to you can always go back to earlier as necessary when you have questions howeverit' important that you understand how each example works before moving to the next one every example has important lessons for youand you could miss vital content if you start skipping too much information |
9,416 | getting started with python visit www dummies com for great dummies content online |
9,417 | discover what programming is all about and why you need python to do it get your own copy of python and install it on your system work with the interactive environment that python provides create your first application using python understand the benefits of adding comments to your application |
9,418 | talking to your computer in this talking to your computer creating programs to talk to your computer understanding what program does and why you want to create it considering why you want to use python as your programming language aving conversation with your computer might sound like the script of science fiction movie after allthe members of the enterprise on star trek regularly talked with their computer in factthe computer often talked back howeverwith the rise of apple' siri (siri/and other interactive softwareperhaps you really don' find conversation so unbelievable asking the computer for information is one thingbut providing it with instructions is quite another this considers why you want to instruct your computer about anything and what benefit you gain from it you also discover the need for special language when performing this kind of communication and why you want to use python to accomplish it howeverthe main thing to get out of this is that programming is simply kind of communication that is akin to other forms of communication you already have with your computer understanding why you want to talk to your computer talking to machine may seem quite odd at firstbut it' necessary because computer can' read your mind -yet even if the computer did read your mindit would still be communicating with you nothing can occur without an exchange of information between the machine and you activities such as |
9,419 | part igetting started with python reading your -mail writing about your vacation finding the greatest gift in the world are all examples of communication that occurs between computer and you that the computer further communicates with other machines or people to address requests that you make simply extends the basic idea that communication is necessary to produce any result in most casesthe communication takes place in manner that is nearly invisible to you unless you really think about it for examplewhen you visit chat room onlineyou might think that you're communicating with another person howeveryou're communicating with your computeryour computer is communicating with the other person' computer through the chat room (whatever it consists of)and the other person' computer is communicating with that person figure - gives you an idea of what is actually taking place figure - commu nication with your computer may be invisible unless you really think about it notice the cloud in the center of figure - the cloud could contain anythingbut you know that it at least contains other computers running other applications these computers make it possible for your friend and you to chat nowthink about how easy the whole process seems when you're using the chat application even though all these things are going on in the backgroundit seems as if you're simply chatting with your friend and the process itself is invisible |
9,420 | knowing that an application is form of communication computer communication occurs through the use of applications you use one application to answer your -mailanother to purchase goodsand still another to create presentation an application (sometimes called an appprovides the means to express human ideas to the computer in manner the computer can understand and defines the tools needed to shape the data used for the communication in specific ways data used to express the content of presentation is different from data used to purchase present for your mother the way you viewuseand understand the data is different for each taskso you must use different applications to interact with the data in manner that both the computer and you can understand it' possible to obtain applications to meet just about any general need you can conceive of today in factyou probably have access to applications for which you haven' even thought about purpose yet programmers have been busy creating millions of applications of all types for many years nowso it may be hard to understand what you can accomplish by creating some new method for talking with your computer through an application the answer comes down to thinking about the data and how you want to interact with it some data simply isn' common enough to have attracted the attention of programmeror you may need the data in format that no application currently supportsso you don' have any way to tell the computer about it unless you create custom application to do it the following sections describe applications from the perspective of working with unique data in manner that is special in some way for exampleyou might have access to video library database but no method to access it in way that makes sense to you the data is unique and your access needs are specialso you may want to create an application that addresses both the data and your needs thinking about procedures you use daily procedure is simply set of steps you follow to perform task for examplewhen making toastyou might use procedure like this get the bread and butter from the refrigerator open the bread bag and take out two pieces of toast remove the cover from the toaster |
9,421 | part igetting started with python place each piece of bread in its own slot push the toaster lever down to start toasting the bread wait for the toasting process to complete remove toast from the toaster place toast on plate butter the toast your procedure might vary from the one presented herebut it' unlikely that you' butter the toast before placing it in the toaster of courseyou do actually have to remove the bread from the wrapper before you toast it (placing the breadwrapper and allinto the toaster would likely produce undesirable resultsmost people never actually think about the procedure for making toast howeveryou use procedure like this one even though you don' think about it computers can' perform tasks without procedure you must tell the computer which steps to performthe order in which to perform themand any exceptions to the rule that could cause failure all this information (and moreappears within an application in shortan application is simply written procedure that you use to tell the computer what to dowhen to do itand how to do it because you've been using procedures all your lifeall you really need to do is apply the knowledge you already possess to what computer needs to know about specific tasks writing procedures down when was in grade schoolour teacher asked us to write paper about making toast after we turned in our papersshe brought in toaster and some loaves of bread each paper was read and demonstrated none of our procedures worked as expectedbut they all produced humorous results in my casei forgot to tell the teacher to remove the bread from the wrapperso she dutifully tried to stuff the piece of breadwrapper and allinto the toaster the lesson stuck with me writing about procedures can be quite hard because we know precisely want we want to dobut often we leave steps out -we assume that the other person also knows precisely what we want to do many experiences in life revolve around procedures think about the checklist used by pilots before plane takes off without good procedurethe plane could crash learning to write great procedure takes timebut it' doable you may have to try several times before you get procedure that |
9,422 | works completelybut eventually you can create one writing procedures down isn' really sufficientthough -you also need to test the procedure by using someone who isn' familiar with the task involved when working with computersthe computer is your perfect test subject seeing applications as being like any other procedure computer acts like the grade school teacher in my example in the previous section when you write an applicationyou're writing procedure that defines series of steps that the computer should perform to accomplish whatever task you have in mind if you leave out stepthe results won' be what you expected the computer won' know what you mean or that you intended for it to perform certain tasks automatically the only thing the computer knows is that you have provided it with specific procedure and it needs to perform that procedure understanding that computers take things literally people eventually get used to the procedures you create they automatically compensate for deficiencies in your procedure or make notes about things that you left out in other wordspeople compensate for problems with the procedures that you write when you begin writing computer programsyou'll get frustrated because computers perform tasks precisely and read your instructions literally for exampleif you tell the computer that certain value should equal the computer will look for value of exactly human might see and know that the value is good enoughbut computer doesn' see things that way it sees value of and decides that it doesn' equal exactly in shortcomputers are inflexibleunintuitiveand unimaginative when you write procedure for computerthe computer will do precisely as you ask absolutely every time and never modify your procedure or decide that you really meant for it to do something else |
9,423 | part igetting started with python defining what an application is as previously mentionedapplications provide the means to define express human ideas in manner that computer can understand to accomplish this goalthe application relies on one or more procedures that tell the computer how to perform the tasks related to the manipulation of data and its presentation what you see onscreen is the text from your word processorbut to see that informationthe computer requires procedures for retrieving the data from diskputting it into form you can understandand then presenting it to you the following sections define the specifics of an application in more detail understanding that computers use special language human language is complex and difficult to understand even applications such as siri have serious limits in understanding what you're saying over the yearscomputers have gained the capability to input human speech as data and to understand certain spoken words as commandsbut computers still don' quite understand human speech to any significant degree the difficulty of human speech is exemplified in the way lawyers work when you read legaleseit appears as gibberish of sorts howeverthe goal is to state ideas and concepts in way that isn' open to interpretation lawyers seldom succeed in meeting their objective precisely because human speech is imprecise given what you know from previous sections of this computers could never rely on human speech to understand the procedures you write computers always take things literallyso you' end up with completely unpredictable results if you were to use human language to write applications that' why humans use special languagescalled programming languagesto communicate with computers these special languages make it possible to write procedures that are both specific and completely understandable by both humans and computers computers don' actually speak any language they use binary codes to flip switches internally and to perform math calculations computers don' even understand letters -they understand only numbers special application turns the computer-specific language you use to write procedure into binary codes for the purposes of this bookyou really don' need to worry too much about the low-level specifics of how computers work at the binary level howeverit' interesting to know that computers speak math and numbersnot really language at all |
9,424 | helping humans speak to the computer it' important to keep the purpose of an application in mind as you write it an application is there to help humans speak to the computer in certain way every application works with some type of data that is inputstoredmanipulatedand output so that the humans using the application obtain desired result whether the application is game or spreadsheetthe basic idea is the same computers work with data provided by humans to obtain desired result when you create an applicationyou're providing new method for humans to speak to the computer the new approach you create will make it possible for other humans to view data in new ways the communication between human and computer should be easy enough that the application actually disappears from view think about the kinds of applications you've used in the past the best applications are the ones that let you focus on whatever data you're interacting with for examplea game application is considered immersive only if you can focus on the planet you're trying to save or the ship you're trying to flyrather than the application that lets you do these things one of the best ways to start thinking about how you want to create an application is to look at the way other people create applications writing down what you like and dislike about other applications is useful way to start discovering how you want your applications to look and work here are some questions you can ask yourself as you work with the applicationswhat do find distracting about the applicationwhich features were easy to usewhich features were hard to usehow did the application make it easy to interact with my datahow would make the data easier to work withwhat do hope to achieve with my application that this application doesn' provideprofessional developers ask many other questions as part of creating an applicationbut these are good starter questions because they begin to help you think about applications as means to help humans speak with computers if you've ever found yourself frustrated by an application you usedyou already know how other people will feel if you don' ask the appropriate questions when you create your application communication is the most important element of any application you create |
9,425 | part igetting started with python you can also start to think about the ways in which you work start writing procedures for the things you do it' good idea to take the process one step at time and write everything you can think of about that step when you get finishedask someone else to try your procedure to see how it actually works you might be surprised to learn that even with lot of effortyou can easily forget to include steps the world' worst application usually begins with programmer who doesn' know what the application is supposed to dowhy it' specialwhat need it addressesor whom it is for when you decide to create an applicationmake sure that you know why you're creating it and what you hope to achieve just having plan in place really helps make programming fun you can work on your new application and see your goals accomplished one at time until you have completed application to use and show off to your friends (all of whom will think you're really cool for creating itunderstanding why python is so cool many programming languages are available today in facta student can spend an entire semester in college studying computer languages and still not hear about them all ( did just that during my college days you' think that programmers would be happy with all these programming languages and just choose one to talk to the computerbut they keep inventing more programmers keep creating new languages for good reason each language has something special to offer -something it does exceptionally well in additionas computer technology evolvesso do the programming languages in order to keep up because creating an application is all about efficient communicationmany programmers know multiple programming languages so that they can choose just the right language for particular task one language might work better to obtain data from databaseand another might create user interface elements especially well as with every other programming languagepython does some things exceptionally welland you need to know what they are before you begin using it you might be amazed by the really cool things you can do with python knowing programming language' strengths and weaknesses helps you use it better as well as avoid frustration by not using the language for things it doesn' do well the following sections help you make these sorts of decisions about python |
9,426 | unearthing the reasons for using python most programming languages are created with specific goals in mind these goals help define the language characteristics and determine what you can do with the language there really isn' any way to create programming language that does everything because people have competing goals and needs when creating applications when it comes to pythonthe main objective was to create programming language that would make programmers efficient and productive with that in mindhere are the reasons that you want to use python when creating an applicationless application development timepython code is usually - times shorter than comparable code written in languages like / +and javawhich means that you spend less time writing your application and more time using it ease of readinga programming language is like any other language -you need to be able to read it to understand what it does python code tends to be easier to read than the code written in other languageswhich means you spend less time interpreting it and more time making essential changes reduced learning timethe creators of python wanted to make programming language with fewer odd rules that make the language hard to learn after allprogrammers want to create applicationsnot learn obscure and difficult languages it' important to realize thatalthough python is popular languageit' not the most popular language out there in factit currently ranks eighth on sites such as tiobe (paperinfo/tpci/index html)an organization that tracks usage statistics (among other thingsif you're looking for language solely for the purpose of obtaining jobpython is good choicebut / ++javac#or visual basic would be better choices make sure you choose language you like and one that will address your application development needsbut also choose on the basis of what you intend to accomplish python was the language of the year in both and and has ranked as high as the fourth most popular language in february soreallyit' good choice if you're looking for jobbut not necessarily the best choice howeverit may surprise you to know that many colleges now use python to teach codingand it has become the most popular language in that venue check out my blog post at johnmuellerbooks com//python-as- -learning-tool for details |
9,427 | part igetting started with python deciding how you can personally benefit from python ultimatelyyou can use any programming language to write any sort of application you want if you use the wrong programming language for the jobthe process will be slowerror pronebug riddenand you'll absolutely hate it -but you can get the job done of coursemost of us would rather avoid horribly painful experiencesso it' important to know what sorts of applications people typically use python to create here' list of the most common uses for python (although people do use it for other purposes)creating rough application examplesdevelopers often need to create prototypea rough example of an applicationbefore getting the resources to create the actual application python emphasizes productivityso you can use it to create prototypes of an application quickly scripting browser-based applicationseven though javascript is probably the most popular language used for browser-based application scriptingpython is close second python offers functionality that javascript doesn' provide (see the comparison at glyphobet net/essay/ for detailsand its high efficiency makes it possible to create browser-based applications faster ( real plus in today' fast-paced worlddesigning mathematicscientificand engineering applicationsinterestingly enoughpython provides access to some really cool libraries that make it easier to create mathscientificand engineering applications the two most popular libraries are numpy (org/and scipy (reduce the time you spend writing specialized code to perform common mathscientificand engineering tasks working with xmlthe extensible markup language (xmlis the basis of most data storage needs on the internet and many desktop applications today unlike most languageswhere xml is just sort of bolted onpython makes it first-class citizen if you need to work with web servicethe main method for exchanging information on the internet (or any other xml-intensive application)python is great choice interacting with databasesbusiness relies heavily on databases python isn' quite query languagelike the structure query language (sqlor language integrated query (linq)but it does do great job of interacting with databases it makes creating connections and manipulating data relatively painless |
9,428 | developing user interfacespython isn' like some languages like cwhere you have built-in designer and can drag and drop items from toolbox onto the user interface howeverit does have an extensive array of graphical user interface (guiframeworks -extensions that make graphics lot easier to create (see org/moin/guiprogramming for detailssome of these frameworks do come with designers that make the user interface creation process easier the point is that python isn' devoted to just one method of creating user interface -you can use the method that best suits your needs discovering which organizations use python python really is quite good at the tasks that it was designed to perform in factthat' why lot of large organizations use python to perform at least some application-creation (developmenttasks you want programming language that has good support from these large organizations because these organizations tend to spend money to make the language better here' list of the large organizations that use python the mostalice educational software carnegie mellon university (www cmu edu/corporate/news/ /features/alice shtml)educational applications fermilab go com google industrial light magic (programming need lawrence livermore national library (scientific applications national space and aeronautics administration (nasa(nasa gov/)scientific applications new york stock exchange (applications objectdomain (html)computer aided software engineering (casetools redhat ( |
9,429 | part igetting started with python yahooyoutube zope digital creations (application these are just few of the many organizations that use python extensively you can find more complete list of organizations at org/about/successthe number of success stories has become so large that even this list probably isn' complete and the people supporting it have had to create categories to better organize it finding useful python applications you might have an application written in python sitting on your machine right now and not even know it python is used in vast array of applications on the market today the applications range from utilities that run at the console to full-fledged cad/cam suites some applications run on mobile deviceswhile others run on the large services employed by enterprises in shortthere is no limit to what you can do with pythonbut it really does help to see what others have done you can find number of places online that list applications written in pythonbut the best place to look is python org/moin/applications as python programmeryou'll also want to know that python development tools are available to make your life easier development tool provides some level of automation in writing the procedures needed to tell the computer what to do having more development tools means that you have to perform less work in order to obtain working application developers love to share their lists of favorite toolsbut you can find great list of tools broken into categories at of coursethis describes number of tools as wellsuch as numpy and scipy (two scientific librariesthe remainder of the book lists few other toolsmake sure that you copy down your favorite tools for later comparing python to other languages comparing one language to another is somewhat dangerous because the selection of language is just as much matter of taste and personal preference as it is any sort of quantifiable scientific fact so before ' attacked by the rabid protectors of the languages that followit' important to realize |
9,430 | that also use number of languages and find at least some level of overlap among them all there is no best language in the worldsimply the language that works best for particular application with this idea in mindthe following sections provide an overview comparison of python to other languages (you can find comparisons to other languages at org/moin/languagecomparisons ca lot of people claim that microsoft simply copied java to create cthat saidcdoes have some advantages (and disadvantageswhen compared to java the main (undisputedintent behind cis to create better kind of / +language -one that is easier to learn and use howeverwe're here to talk about cand python when compared to #python has these advantagessignificantly easier to learn smaller (more concisecode supported fully as open source better multiplatform support easily allows use of multiple development environments easier to extend using java and / +enhanced scientific and engineering support java for yearsprogrammers looked for language that they could use to write an application just once and have it run anywhere java is designed to work well on any platform it relies on some tricks that you'll discover later in the book to accomplish this magic for nowall you really need to know is that java was so successful at running well everywhere that other languages have sought to emulate it (with varying levels of successeven sopython has some important advantages over javaas shown in the following listsignificantly easier to learn smaller (more concisecode enhanced variables (storage boxes in computer memorythat can hold different kinds of data based on the application' needs while running (dynamic typingfaster development times |
9,431 | part igetting started with python perl perl was originally an acronym for practical extraction and report language todaypeople simply call it perl and let it go at that howeverperl still shows its roots in that it excels at obtaining data from database and presenting it in report format of courseperl has been extended to do lot more than that -you can use it to write all sorts of applications ( 've even used it for web service application in comparison with pythonyou'll find that python has these advantages over perlsimpler to learn easier to read enhanced protection for data better java integration fewer platform-specific biases |
9,432 | getting your own copy of python in this obtaining copy of python for your system performing the python installation finding and using python on your system ensuring your installation works as planned reating applications requires that you have another applicationunless you really want to get low level and write applications in machine code - decidedly difficult experience that even true programmers avoid if at all possible if you want to write an application using the python programming languageyou need the applications required to do so these applications help you work with python by creating python codeproviding help information as you need itand letting you run the code you write this helps you obtain copy of the python applicationinstall it on your hard drivelocate the installed applications so that you can use themand test your installation so that you can see how it works downloading the version you need every platform (combination of computer hardware and operating system softwarehas special rules that it follows when running applications the python application hides these details from you you type code that runs on any platform that python supportsand the python applications translate that code into something the platform can understand howeverin order for the translation to take placeyou must have version of python that works on your particular platform python supports these platformsadvanced ibm unix (aixamiga research os (aros |
9,433 | part igetting started with python application system (as/ beos hewlett-packard unix (hp-uxlinux mac os (comes pre-installed with the osmicrosoft disk operating system (ms-dosmorphos operating system (os/ operating system (os/ and /os palmos playstation psion qnx risc os (originally acornseries solaris virtual memory system (vmswindows -bit (xp and laterwindows -bit windows ce/pocket pc wowthat' lot of different platformsthis book is tested with the windowsmac os xand linux platforms howeverthe examples could very well work with these other platformstoobecause the examples don' rely on any platform-specific code let me know if it works on your non-windowsmacor linux platform at john@johnmuellerbooks com the current version of python at the time of this writing is 'll talk about any python updates on my blog at answers to your python book-specific questions theretoo to get the right version for your platformyou need to go to python org/download/releases/the download section is initially hidden from viewso you need to scroll halfway down the page you see page similar to the one shown in figure - the main part of the page contains links for windowsmac os xand linux downloads these links provide |
9,434 | you with the default setup that is used in this book the platform-specific links on the left side of the page show you alternative python configurations that you can use when the need arises for exampleyou may want to use more advanced editor than the one provided with the default python packageand these alternative configurations can provide one for you figure - the python download page con tains links for all sorts of versions if you want to work with another platformclick the other link on the left side of the page you see list of python installations for other platformsas shown in figure - many of these installations are maintained by volunteers rather than by the people who create the versions of python for windowsmac os xand linux make sure you contact these individuals when you have installation questions because they know how best to help you get good installation on your platform |
9,435 | part igetting started with python figure - volunteers have made python available on all sorts of platforms installing python after you download your copy of pythonit' time to install it on your system the downloaded file contains everything needed to get you startedpython interpreter help files (documentationcommand-line access integrated development environment (idleapplication uninstaller (only on platforms that require it |
9,436 | this book assumes that you're using one of the default python setups found at supported by this bookwindowsmac os xand linux working with windows the installation process on windows system follows the same procedure that you use for other application types the main difference is in finding the file you downloaded so that you can begin the installation process the following procedure should work fine on any windows systemwhether you use the -bit or the -bit version of python locate the downloaded copy of python on your system the name of this file variesbut normally it appears as pythonmsi for -bit systems and pythonamd msi for -bit systems the version number is embedded as part of the filename in this casethe filename refers to version which is the version used for this book double-click the installation file (you may see an open file security warning dialog box that asks whether you want to run this file click run if you see this dialog box pop up you see python setup dialog box similar to the one shown in figure - the exact dialog box you see depends on which version of the python installation program you download figure - the setup process begins by asking you who should have access to python |
9,437 | part igetting started with python choose user installation option (the book uses the default setting of install for all usersand click next install asks you to provide the name of an installation directory for pythonas shown in figure - using the default destination will save you time and effort later howeveryou can install python anywhere you desire figure - decide on an installation location for your copy of python using the windows \program files or \program files ( folder is problematic for two reasons firstthe folder name has space in itwhich makes it hard to access from within the application secondthe folder usually requires administrator accessso you'll constantly battle the user account control (uacfeature of windows if you install python in either folder type destination folder nameif necessaryand click next python asks you to customize its installationas shown in figure - enabling the add python exe to path option will save you time later this feature makes it possible to access python from the command prompt window don' worry too much about how you use this feature just yetbut it really is good feature to have installed the book assumes that you've enabled this feature don' worry about the other features you see in figure - they're all enabled by defaultwhich provides you with maximum access to python functionality |
9,438 | figure - customize your instal lation to meet your needs (optionalclick the down arrow next to the add python exe to path option and choose the will be installed on local drive option click next you see the installation process start at some pointyou might see user account control dialog box asking whether you want to perform the install if you see this dialog boxclick yes the installation continues and you see an installation complete dialog box click finish python is ready for use working with the mac your mac system likely already has python installed on it howeverthis installation is normally few years old -or whatever the age of your system happens to be for the purposes of this bookthe installation will likely work fine you won' be testing the limits of python programming technology -just getting great start using python |
9,439 | part igetting started with python the leopard version of os ( uses really old version of python this particular version lacks direct access to the idle application as resultyou may find that some book exercises won' work properly the article at about how to overcome this particular issue the newest version of os at the time of this writing (mavericksor comes with python which is just fine for working through the examples in the book depending on how you use pythonyou might want to update your installation at some point part of this process involves installing the gnu compiler collection (gcctools so that python has access to the low-level resources it needs the following steps get you started with installing new version of python on your mac os system navigate to with your browser you see information regarding the latest version of pythonas shown in figure - click the appropriate link for your version of os xa python mac os -bit/ -bit - / installer for -bit or -bit versions on the intel processor python mac os -bit /ppc installer for -bit versions on the power pc processor the python disk image begins downloading be patientthe disk image requires several minutes to download most browsers provide method for monitoring the download process so that you can easily see how long the download will take when the download is completeyour mac automatically opens the disk image for you the disk image actually looks like folder inside this folderyou see number of filesincluding python mpkg the python mpkg file is the one that contains the python application the text files contain information about the buildlicensingand any late-breaking notes double-click python mpkg you see welcome dialog box that tells you about this particular python build click continue three times the installation program displays late-breaking notes about pythonlicensing information (click agree when asked about the licensing information)andfinallya destination dialog box |
9,440 | select the volume (hard drive or other mediathat you want to use for installing python and click continue the installation type dialog box appears this dialog box performs two tasksclick customize to change the feature set that is installed on your system click change install location to modify the place where the installer places python the book assumes that you're performing standard installation and that you haven' changed the installation location howeverthese options are available in case you want to use them click install the installer may request your administrator password type the administrator name and passwordif requiredinto the dialog box and click ok you see an installing python dialog box the contents of this dialog box will change as the installation process proceeds so that you know what part of python the installer is working with after the installation is completedyou see an install succeeded dialog box click close python is ready to use (you can close the disk image at this point and remove it from your system working with linux some versions of linux come with python installed for exampleif you have red hat package manager (rpm)-based distribution (such as susered hatyellow dogfedora coreand centos)you likely already have python on your system and don' need to do anything else depending on which version of linux you usethe version of python varies and some systems don' include the interactive development environment (idleapplication if you have an older version of python or earlier)you might want to install newer version so that you have access to idle many of the book exercises require use of idle you actually have two techniques to use to install python on linux the following sections discuss both techniques the first technique works on any linux distributionthe second technique has special criteria that you must meet |
9,441 | part igetting started with python using the standard linux installation the standard linux installation works on any system howeverit requires you to work at the terminal and type commands to complete it some of the actual commands may vary by version of linux the information at docs python org/ /installprovides some helpful tips that you can use in addition to the procedure that follows navigate to with your browser you see information regarding the latest version of pythonas shown in figure - click the appropriate link for your version of linuxa python compressed source tarball (any version of linuxb python xzipped source tarball (better compression and faster download when asked whether you want to open or save the filechoose save the python source files begin downloading be patientthe source files require minute or two to download double-click the downloaded file the archive manager window opens after the files are extractedyou see the python folder in the archive manager window double-click the python folder the archive manager extracts the files to the python subfolder of your home folder open copy of terminal the terminal window appears if you have never built any software on your system beforeyou must install the build essentialssqliteand bzip or the python installation will fail otherwiseyou can skip to step to begin working with python immediately type sudo apt-get install build-essential and press enter linux installs the build essential support required to build packages (see for details type sudo apt-get install libsqlite -dev and press enter linux installs the sqlite support required by python for database manipulation (see libsqlite -dev for details |
9,442 | type sudo apt-get install libbz -dev and press enter linux installs the bzip support required by python for archive manipulation (see details type cd python in the terminal window and press enter terminal changes directories to the python folder on your system type /configure and press enter the script begins by checking the system build type and then performs series of tasks based on the system you're using this process can require minute or two because there is large list of items to check type make and press enter linux executes the make script to create the python application software the make process can require up to minute -it depends on the processing speed of your system type sudo make altinstall and press enter the system may ask you for your administrator password type your password and press enter at this pointa number of tasks take place as the system installs python on your system using the graphical linux installation all versions of linux support the standard installation discussed in the "using the standard linux installationsection of this howevera few versions of debian-based linux distributionssuch as ubuntu and laterprovide graphical installation technique as well you need the administrator group (sudopassword to use this procedureso having it handy will save you time the following steps outline the graphical installation technique for ubuntubut the technique is similar for other linux installations open the ubuntu software center folder (the folder may be named synaptics on other platforms you see listing of the most popular software available for download and installation select developer tools (or developmentfrom the all software dropdown list box you see listing of developer toolsincluding python double-click the python entry the ubuntu software center provides details about the python entry and offers to install it for you |
9,443 | part igetting started with python click install ubuntu begins the process of installing python progress bar shows the download and installation status when the installation is completethe install button changes to remove button close the ubuntu software center folder you see python icon added to the desktop python is ready for use accessing python on your machine after you have python installed on your systemyou need to know where to find it in some respectspython does everything it can to make this process easy by performing certain taskssuch as adding the python path to the machine' path information during installation even soyou need to know how to access the installationwhich the following sections describe using windows windows installation creates new folder in the start menu that contains your python installation you can access it by choosing startall programs python the two items of interest in the folder when creating new applications are idle (python guiand python (command linea word about the screenshots as you work your way through the bookyou'll use either idle or the python command-line shell to work with python the name of the graphical (guienvironmentidleis precisely the same across all three platformsand you won' even see any significant difference in the presenta tion the differences you do see are minorand you should ignore them as you work through the book with this in mindthe book does rely heav ily on windows screenshots -all the screen shots you see were obtained from windows system for the sake of consistency the command-line shell also works pre cisely the same across all three platforms the presentation may vary little more than idle does simply because the shell used for each platform varies slightly howeverthe commands you type for one platform are precisely the same on another platform the output is the same as well when viewing the screenshotlook at the content rather than for specific differences in the presentation of the shell |
9,444 | clicking idle (python guiproduces graphical interactive environment like the one shown in figure - when you open this environmentidle automatically displays some information so that you know you have the right application open for exampleyou see the python version number (which is in this caseit also tells you what sort of system you're using to run python figure - use idle when you want the comforts of graphical environment the python (command lineoption opens command prompt and executes the python commandas shown in figure - againthe environment automatically displays information such as the python version and the host platform figure - use the command prompt when you want the speed and flexibility of commandline interface |
9,445 | part igetting started with python third method to access python is to open command prompttype pythonand press enter you can use this approach when you want to gain additional flexibility over the python environmentautomatically load itemsor execute python in higher-privilege environment (in which you gain additional security rightspython provides significant array of command-line options that you can see by typing python /at the command prompt and pressing enter figure - shows what you typically see don' worry too much about these command-line options -you won' need them for this bookbut it' helpful to know they exist figure - using standard command line offers the flexibility of using switches to change the way python works to use this third method of executing pythonyou must include python in the windows path this is why you want to choose the add python exe to path option when installing python on windows if you didn' add the path during installationyou can add it afterward using the instructions found in the adding location to the windows path article on my blog |
9,446 | at adding python-specific environment variables such as pythonstartup pythonpath pythonhome pythoncaseok pythonioencoding pythonfaulthandler pythonhashseed none of these environment variables is used in the book howeveryou can find out more about them at cmdline html#environment-variables using the mac when working with macyou probably have python already installed and don' need to install it for this book howeveryou still need to know where to find python the following sections tell you how to access python depending on the kind of installation you performed locating the default installation the default os installation doesn' include python-specific folder in most cases insteadyou must open terminal by choosing applicationsutilities terminal after terminal is openyou can type python and press enter to access the command-line version of python the display you see is similar to the one shown in figure - as with windows (see the "using windowssection of the using terminal to open python offers the advantage of using command-line switches to modify the manner in which python works locating the updated version of python you installed after you perform the installation on your mac systemopen the applica tions folder within this folderyou find python folder that contains the followingextras folder idle application (gui developmentpython launcher (interactive command developmentupdate sh command |
9,447 | part igetting started with python double-clicking idle application opens graphical interactive environment that looks similar to the environment shown in figure - there are some small cosmetic differencesbut the content of the window is the same doubleclicking python launcher opens command-line environment similar to the one shown in figure - this environment uses all the python defaults to provide standard execution environment even if you install new version of python on your macyou don' have to settle for using the default environment it' still possible to open terminal to gain access to the python command-line switches howeverwhen you access python from the mac terminal applicationyou need to ensure that you're not accessing the default installation make sure to add /usr/local/binpython to your shell search path using linux after the installation process is completeyou can find python subfolder in your home folder the physical location of python on your linux system is normally the /usr/local/bin/python folder this is important information because you may need to modify the path for your system manually linux developers need to type python rather than just pythonwhen working at the terminal window to obtain access to the python installation testing your installation to ensure that you have usable installationyou need to test it it' important to know that your installation will work as expected when you need it of coursethis means writing your first python application to get startedopen copy of idle as previously mentionedidle automatically displays the python version and host information when you open it (refer to figure - to see python worktype print("this is my first python program "and press enter python displays the message you just typedas shown in figure - the print(command displays onscreen whatever you tell it to display you see the print(command used quite often in this book to display the results of tasks you ask python to performso this is one of the commands you work with frequently |
9,448 | figure - the print(command displays whatever information you tell it to print notice that idle color codes the various entries for you so that they're easier to see and understand the colors codes are your indicator that you've done something right four color codes are shown in figure - (although they're not visible in the print edition of the book)purpleindicates that you have typed command greenspecifies the content sent to command blueshows the output from command blackdefines non-command entries you know that python works now because you were able to issue command to itand it responded by reacting to that command it might be interesting to see one more command type and press enter python responds by outputting as shown in figure - notice that appears in black type because it isn' command howeverthe is still in blue type because it' output figure - python sup ports math directly as part of the interactive environment |
9,449 | part igetting started with python it' time to end your idle session type quitand press enter idle may display message such as the one shown in figure - wellyou never intended to kill anythingbut you will now click okand the session dies figure - idle seems to get little dramatic about ending sessionnotice that the quit(command has parentheses after itjust as the print(command does all commands have parentheses like these two that' how you know they're commands howeveryou don' need to tell the quit(command anythingso you simply leave the area between the parentheses blank |
9,450 | interacting with python in this accessing the command line using commands to perform tasks obtaining help about python ending command-line session ltimatelyany application you create interacts with the computer and the data it contains the focus is on data because without datathere isn' good reason to have an application any application you use (even one as simple as solitairemanipulates data in some way in factthe acronym crud sums up what most applications docreate read update delete if you remember crudyou'll be able to summarize what most applications do with the data your computer contains (and some applications really are quite cruddyhoweverbefore your application accesses the computeryou have to interact with programming language that creates list of tasks to perform in language the computer understands that' the purpose of this you begin interacting with python python takes the list of steps you want to perform on the computer' data and changes those steps into bits the computer understands |
9,451 | part igetting started with python understanding the importance of the readme file many applications include readme file the readme file usually provides updated informa tion that didn' make it into the documentation before the application was put into produc tion status unfortunatelymost people ignore the readme file and some don' even know it exists as resultpeople who should know something interesting about their shiny new product never find out python has readme txt file in the \python directory when you open this fileyou find all sorts of really interesting informationhow to build copy of python for linux systems where to find out about new features in this version of python where to find the latest version of the python documentation what you need to do to test custom python modifications how to install multiple versions of python on the same system how to access bug and issue tracking for python how to request updates to python how to find out when the next version of python will come out opening and reading the readme file will help you become python genius people will be amazed that you really do know something interesting about python and will ask you all sorts of questions (deferring to your wisdomof courseyou could always just sit therethinking that the readme is just too much effort to read how to convert your older python applica tions to work with python opening the command line python offers number of ways to interact with the underlying language for exampleyou worked bit with the integrated development environment (idlein idle makes it easy to develop full-fledged applications howeversometimes you simply want to experiment or to run an existing application oftenusing the command-line version of python works better in these cases because it offers better control over the python environment through command-line switchesuses fewer resourcesand relies on minimalistic interface so that you can focus on trying out code rather than playing with gui |
9,452 | starting python depending on your platformyou might have multiple ways to start the command line here are the methods that are commonly availableselect the python (command-lineoption found in the python folder this option starts command-line session that uses the default settings open command prompt or terminaltype pythonand press enter use this option when you want greater flexibility in configuring the python environment using command-line switches locate the python foldersuch as :\python in windowsand open the python exe file directly this option also opens command-line session that uses the default settingsbut you can do things like open it with increased privileges (for applications that require access to secured resourcesor modify the executable file properties (to add command-line switchesno matter how you start python at the command lineyou eventually end up with prompt similar to the one shown in figure - (your screen may look slightly different from the one shown in figure - if you rely on platform other than windowsyou're using idle instead of the command-line version of pythonyour system is configured differently from mineor you have different version of python this prompt tells you the python versionthe host operating systemand how to obtain additional information figure - the python command prompt tells you bit about the python environment |
9,453 | part igetting started with python using the command line to your advantage this section will seem little complicated at firstand you won' normally need this information when using the book howeverit' still good informationand you'll eventually need it for nowyou can browse the information so that you know what' available and then come back to it later when you really do need the information to start python at command prompttype python and press enter howeverthat' not all you can do you can also provide some additional information to change how python worksoptionsan optionor command-line switchbegins with minus sign followed by one or more letters for exampleif you want to obtain help about pythonyou type python - and press enter you see additional information about how to work with python at the command line the options are described later in this section filenameproviding filename as input tells python to load that file and run it you can run any of the example applications from the downloadable code by providing the name of the file containing the example as input for examplesay that you have an example named sayhello py to run this exampleyou type python sayhello py and press enter argumentsan application can accept additional information as input to control how it runs this additional information is called an argument don' worry too much about arguments right now -they appear later in the book most of the options won' make sense right now they're here so that you can find them later when you need them (this is the most logical place to include them in the bookreading through them will help you gain an understanding of what' availablebut you can also skip this material until you need it later python uses case-sensitive options for example- is completely different option from - the python options are -badd warnings to the output when your application uses certain python features that includestr(bytes_instance)str(bytearray_ instance)and comparing bytes or bytearray with str(-bbadd errors to the output when your application uses certain python features that includestr(bytes_instance)str(bytearray_ instance)and comparing bytes or bytearray with str(-bdon' write py or pyco files when performing module import |
9,454 | - cmduse the information provided by cmd to start program this option also tells python to stop processing the rest of the information as options (it' treated as part of the command-dstart the debugger (used to locate errors in your application-eignore all the python environment variablessuch as pythonpaththat are used to configure python for use -hdisplay help about the options and basic environment variables onscreen python always exits after it performs this task without doing anything else so that you can see the help information -iforce python to let you inspect the code interactively after running script it forces prompt even if stdin (the standard input devicedoesn' appear to be terminal - modrun the library module specified by mod as script this option also tells python to stop processing the rest of the information as options (the rest of the information is treated as part of the command-ooptimize the generated bytecode slightly (makes it run faster-ooperform additional optimization by removing doc-strings -qtell python not to print the version and copyright messages on interactive startup -sforce python not to add the user site directory to sys path ( variable that tells python where to find modules-sdon' run 'import siteon initialization using this option means that python won' look for paths that may contain modules it needs -uallow unbuffered binary input for the stdout (standard outputand stderr (standard errordevices the stdin device is always buffered -vplace python in verbose mode so that you can see all the import statements using this option multiple times increases the level of verbosity -vdisplay the python version number and exit --versiondisplay the python version number and exit - argmodify the warning level so that python displays more or fewer warnings the valid arg values are action message category module lineno |
9,455 | part igetting started with python -xskip the first line of source code filewhich allows the use of nonunix forms of #!cmd - optset an implementation-specific option (the documentation for your version of python discusses these optionsif there are any using python environment variables to your advantage environment variables are special settings that are part of the command line or terminal environment for your operating system they serve to configure python in consistent manner environment variables perform many of the same tasks as do the options that you supply when you start pythonbut you can make environment variables permanent so that you can configure python the same way every time you start it without having to manually supply the option as with optionsmost of these environment variables won' make any sense right now you can read through them to see what is available you find some of the environment variables used later in the book feel free to skip the rest of this section and come back to it later when you need it most operating systems provide the means to set environment variables temporarilyby configuring them during particular sessionor permanentlyby configuring them as part of the operating system setup precisely how you perform this task depends on the operating system for examplewhen working with windowsyou can use the set command (see my blog post at johnmuellerbooks com//using-the-set-command-toyour-advantagefor detailsor rely on special windows configuration feature (see my post at adding- -location-to-the-windows-pathfor setting the path environment variable as an exampleusing environment variables makes sense when you need to configure python the same way on regular basis the following list describes the python environment variablespythoncaseok=xforces python to ignore case when parsing import statements this is windows-only environment variable pythondebug=xperforms the same task as the - option pythondontwritebytecode=xperforms the same task as the - option |
9,456 | pythonfaulthandler=xforces python to dump the python traceback (list of calls that led to an erroron fatal errors pythonhashseed=argdetermines the seed value used to generate hash values from various kinds of data when this variable is set to randompython uses random value to seed the hashes of strbytesand datetime objects the valid integer range is to use specific seed value to obtain predictable hash values for testing purposes pythonhome=argdefines the default search path that python uses to look for modules pythoninspect=xperforms the same task as the - option pythonioencoding=argspecifies the encoding[:errors(such as utf- used for the stdinstdoutand stderr devices pythonnousersiteperforms the same task as the - option pythonoptimize=xperforms the same task as the - option pythonpath=argprovides semicolon (;separated list of directories to search for modules this value is stored in the sys path variable in python pythonstartup=argdefines the name of file to execute when python starts there is no default value for this environment variable pythonunbuffered=xperforms the same task as the - option pythonverbose=xperforms the same task as the - option pythonwarnings=argperforms the same task as the - option typing command after you start the command-line version of pythonyou can begin typing commands using commands makes it possible to perform taskstest ideas that you have for writing your applicationand discover more about python using the command line lets you gain hands-on experience with how python actually works -details that could be hidden by an interactive development environment (idesuch as idle the following sections get you started using the command line |
9,457 | part igetting started with python telling the computer what to do pythonlike every other programming language in existencerelies on commands command is simply step in procedure in you saw how "get the bread and butter from the refrigeratoris step in procedure for making toast when working with pythona commandsuch as print()is simply the same thinga step in procedure to tell the computer what to doyou issue one or more commands that python understands python translates these commands into instructions that the computer understandsand then you see the result command such as print(can display the results onscreen so that you get an instant result howeverpython supports all sorts of commandsmany of which don' display any results onscreen but still do something important as the book progressesyou use commands to perform all sorts of tasks each of these tasks will help you accomplish goaljust as the steps in procedure do when it seems as if all the python commands become far too complexsimply remember to look at them as steps in procedure even human procedures become complex at timesbut if you take them one step at timeyou begin to see how they work python commands are the same way don' get overwhelmed by theminsteadlook at them one at time and focus on just that step in your procedure telling the computer you're done at some pointthe procedure you create ends when you make toastthe procedure ends when you finish buttering the toast computer procedures work precisely the same way they have starting and an ending point when typing commandsthe ending point for particular step is the enter key you press enter to tell the computer that you're done typing the command as the book progressesyou find that python provides number of ways to signify that stepgroup of stepsor even an entire application is complete no matter how the task is accomplishedcomputer programs always have distinct starting and stopping point seeing the result you now know that command is step in procedure and that each command has distinct starting and ending point in additiongroups of commands and entire applications also have distinct starting and ending |
9,458 | point sotake look at how this works the following procedure helps you see the result of using command start copy of the python command-line version you see command prompt where you can type commandsas shown in figure - type print("this is line of text "at the command line notice that nothing happens yesyou typed commandbut you haven' signified that the command is complete press enter the command is completeso you see result like the one shown in figure - figure - issuing commands tells python what to tell the computer to do this exercise shows you how things work within python each command that you type performs some taskbut only after you tell python that the command is complete in some way the print(command displays data onscreen in this caseyou supplied text to display notice that the output shown in figure - comes immediately after the command because this is an interactive environment -one in which you see the result of any given command immediately after python performs it lateras you start creating applicationsyou notice that sometimes result doesn' appear immediately because the application environment delays it even sothe command is executed by python immediately after the application tells python that the command is complete |
9,459 | part igetting started with python using help python is computer languagenot human language as resultyou won' speak it fluently at first if you think about it for momentit makes sense that you won' speak python fluently (and as with most human languagesyou won' know every command even after you do become fluenthaving to discover python commands little at time is the same thing that happens when you learn to speak another human language if you normally speak english and try to say something in germanyou find that you must have some sort of guide to help you along otherwiseanything you say is gibberish and people will look at you quite oddly even if you manage to say something that makes senseit may not be what you want you might go to restaurant and order hot hubcaps for dinner when what you really wanted was steak likewisewhen you try to speak pythonyou need guide to help you fortu natelypython is quite accommodating and provides immediate help to keep you from ordering something you really don' want the help provided inside python works at two levelshelp modein which you can browse the available commands direct helpin which you ask about specific command there isn' correct way to use help -just the method that works best for you at particular time the following sections describe how to obtain help getting into help mode when you first start pythonyou see display similar to the one shown in figure - notice that python provides you with four commands at the outset (which is actually your first piece of help information)help copyright credits license all four commands provide you with helpof sortabout python for examplethe copyright(command tells you about who holds the right to copylicenseor otherwise distribute python the credits(command tells you |
9,460 | who put python together the license(command describes the usage agreement between you and the copyright holder howeverthe command you most want to know about is simply help(to enter help modetype helpand press enter notice that you must include the parentheses after the command even though they don' appear in the help text every python command has parentheses associated with it after you enter this commandpython goes into help mode and you see display similar to the one shown in figure - figure - you ask python about other commands in help mode you can always tell that you're in help mode by the helpprompt that you see in the python window as long as you see the helppromptyou know that you're in help mode asking for help to obtain helpyou need to know what question to ask the initial help message that you see when you go into help mode (refer to figure - provides some helpful tips about the kinds of questions you can ask if you want to explore pythonthe three basic topics are modules keywords topics |
9,461 | part igetting started with python the first two topics won' tell you much for now you won' need the modules topic until the keywords topic will begin proving useful in howeverthe topics keyword is already useful because it helps you understand where to begin your python adventure to see what topics are availabletype topics and press enter you see list of topics similar to those shown in figure - figure - the topics help topic provides you with starting point for your python adventure when you see topic that you likesuch as functionssimply type that topic and press enter to see how this workstype functions and press enter (you must type the word in uppercase -don' worrypython won' think you're shoutingyou see help information similar to that shown in figure - figure - you must use uppercase when requesting topic information |
9,462 | as you work through examples in the bookyou use commands that look interestingand you might want more information about them for examplein the "seeing the resultsection of this you use the print(command to see more information about the print(commandtype print and press enter (notice that you don' include the parentheses this time because you're requesting help about print()not actually using the commandfigure - shows typical help information for the print(command figure - request com mand help information by typing the command using whatever case it actually uses unfortunatelyreading the help information probably doesn' help much yet because you need to know more about python howeveryou can ask for more information for exampleyou might wonder what sys stdout means -and the help topic certainly doesn' tell you anything about it type sys stdout and press enter you see the help information shown in figure - figure - you can ask for help on the help you receive |
9,463 | part igetting started with python you may still not find the information as helpful as you needbut at least you know little more in this casehelp has lot to say and it can' all fit on one screen notice the following entry at the bottom of the screen-more -to see the additional informationpress the spacebar the next page of help appears as you read to the bottom of each page of helpyou can press the spacebar to see the next page the pages don' go away -you can scroll up to see previous material leaving help mode at some pointyou need to leave help mode to perform useful work all you have to do is press enter without typing anything when you press enteryou see message about leaving helpand then the prompt changes to the standard python promptas shown in figure - figure - exit help mode by pressing enter with out typing anything obtaining help directly entering help mode isn' necessary unless you want to browsewhich is always good ideaor unless you don' actually know what you need to find if you have good idea of what you needall you need to do is ask for help directly ( really nice thing for python to dosoinstead of fiddling with help modeyou simply type the word helpfollowed by left parenthesis and |
9,464 | single quotewhatever you want to findanother single quoteand the right parenthesis for exampleif you want to know more about the print(commandyou type help('print'and press enter figure - shows typical output when you access help this way figure - python makes it possible to obtain help whenever you need it without leaving the python prompt you can browse at the python prompttoo for examplewhen you type help('topics'and press enteryou see list of topics like the one that appears in figure - you can compare this list with the one shown in figure - the two lists are identicaleven though you typed one while in help mode and the other while at the python prompt figure - it' possible to browse at the python prompt if you really want to |
9,465 | part igetting started with python you might wonder why python has help mode at all if you can get the same results at the python prompt the answer is convenience it' easier to browse in the help mode in additioneven though you don' do lot of extra typing at the promptyou do perform less typing while in help mode help mode also provides additional helpssuch as by listing commands that you can typeas shown in figure - so you have all kinds of good reasons to enter help mode when you plan to ask python lot of help questions no matter where you ask for helpyou need to observe the correct capitalization of help topics for exampleif you want general information about functionsyou must type help('functions'and not help('functions'or help('functions'when you use the wrong capitalizationpython will tell you that it doesn' know what you mean or that it couldn' find the help topic it won' know to tell you that you used the wrong capitalization someday computers will know what you meant to typerather than what you did typebut that hasn' happened yet closing the command line eventuallyyou want to leave python yesit' hard to believebut people have other things to do besides playing with python all day long you have two standard methods for leaving python and whole bunch of nonstandard methods generallyyou want to use one of the standard methods to ensure that python behaves as you expect it tobut the nonstandard methods work just fine when you simply want to play around with python and not perform any productive work the two standard methods are quit(exit(either of these methods will close the interactive version of python the shell (the python programis designed to allow either command both of these commands can accept an optional argument for exampleyou can type quit( or exit( and press enter to exit the shell the numeric argument sets the command prompt' errorlevel environment variablewhich you can then intercept at the command line or as part of batch file standard practice is to simply use quit(or exit(when nothing has gone wrong with the application to see this way of exiting at workyou must open command prompt or terminal you see prompt type python and press enter to start python you see the python prompt |
9,466 | type quit( and press enter you see the prompt again type echo %errorleveland press enter you see the error codeas shown in figure - when working with platforms other than windowsyou may need to type something other than echo %errorlevelfor examplewhen working with bash scriptyou type echo instead figure - add an error code when needed to tell others the python exit status one of the most common nonstandard exit methods is to simply click the command prompt' or terminal' close button using this approach means that your application may not have time to perform any required cleanupwhich can result in odd behaviors it' always better to close python using an expected approach if you've been doing anything more than simply browsing you also have access to number of other commands for closing the command prompt when needed in most casesyou won' need these special commandsso you can skip the rest of this section if desired when you use quit(or exit()python performs number of tasks to ensure that everything is neat and tidy before the session ends if you suspect that session might not end properly anywayyou can always rely on one of these two commands to close the command promptsys exit(os _exit( |
9,467 | part igetting started with python both of these commands are used in emergency situations only the firstsys exit()provides special error-handling features that you discover in the secondos _exit()exits python without performing any of the usual cleanup tasks in both casesyou must import the required moduleeither sys or osbefore you can use the associated command consequentlyto use the sys exit(commandyou actually use this codeimport sys sys exit(you must provide an error code when using os _exit(because this command is used only when an extreme error has occurred the call to this ommand will fail if you don' provide an error code to use the os exit(commandyou actually use this code (where the error code is )import os os _exit( discusses importing modules in detail for nowjust know that these two commands are for special uses only and you won' normally use them in an application |
9,468 | writing your first application in this working with the integrated development environment (idlegetting started with idle writing the first application seeing how the first application works formatting your application code using comments effectively working with existing applications ending your idle session any people view application development as some sort of magic practiced by wizards called geeks who wave their keyboard to produce software both great and small howeverthe truth is lot more mundane application development follows number of processes it' more than strict procedurebut is most definitely not magic of any sort as arthur clark once noted"any sufficiently advanced technology is indistinguishable from magic this is all about removing the magic from the picture and introducing you to the technology by the time you're finished with this you too will be able to develop simple application (and you won' use magic to do itas with any other taskpeople use tools to write applications in the case of pythonyou don' have to use toolbut using tool makes the task so much easier that you really will want to use one in this you use tool that comes with pythonthe integrated development environment (idlein the previous you use the command-line tool to play around with python little howeveridle goes further than the command line tool and makes it possible to write applications with greater ease |
9,469 | part igetting started with python vast number of other tools are available for you to use when writing python applications this book doesn' tell you much about them because idle performs every task needed and it comes with python howeveras your skills increaseyou might find that tools such as komodo edit (activestate com/komodo-edit/downloadsare easier to work with than idle you can find great list of these tools at org/moin/integrateddevelopmentenvironments understanding the integrated development environment (idleyou can literally create any python application you want using just text editor as long as the editor outputs pure text rather than formatted text as word processor doesyou can use it to write python code howeverusing text editor isn' efficient or straightforward to make the development process easierdevelopers have written interactive development environments (idesthe ide that comes with python is idle howevermany other ides are capable of working with python the feature set provided by ides varies in factthat' why there are so many of them on the market idle provides basic feature set that is shared by most ides out there it provides the functionality required to write python code recognize and highlight keywords and certain types of special text perform both simple editing (such as cutcopyand pasteand codespecific editing (such as showing the parentheses that surround an expressionsave and open python files browse the python path to make locating files easy browse and locate python classes perform simple debugging tasks (removing errors from the codeidle differs from the command-line version of python in that you get fullfledged gui and you can accomplish many tasks much more easily through idle than through the command line in additionthe command line doesn' really offer all the same features as idle yesyou can debug your application using the command linebut it' difficulterror-prone process using idle is whole lot easier |
9,470 | starting idle you find idle in the python folder on your system as idle (python guiwhen you click or double-click this entry (depending on your platform)you see the idle editor shown in figure - the two lines of text contain information about the python host and provide suggestions on the commands you can try the precise information you see differs by platform your screenshots may differ from mine depending on the version of python you usethe platform you usehow you have idle configuredand how you have your system configured figure - idle pro vides you with gui editing experience for your application code |
9,471 | part igetting started with python using standard commands idle provides all the same commands as the command-line version of python it doesn' list them all because the assumption is that you'll use the gui features of idle to make things easy howeverif you wantyou can type helpand press enter to enter help modeeven though this command isn' listed as one of the initial commands for idle as it is for the command-line version figure - shows the results figure - you can access all the same commands in idle that you can with the com mand line version |
9,472 | understanding color coding the book doesn' show the color coding that you see when you type help)but you can see it in the editor color coding lets you see commands with greater ease and differentiate commands from other sorts of text press enter to get out of help mode as with the command-line versionyou see descriptive text each time you perform an action nowtype print('this is some text 'and press enter you see the expected outputjust as you normally would (see figure - notice the color codingthough the print(command is in purple text to show that it' command the text within the print(command is green to show that it' data and not command the output is shown in blue the color coding makes things lot easierwhich is just one of many reasons that using idle is easier than using the command line figure - with color codingyou can easily determine the use for each kind of text in an application |
9,473 | part igetting started with python getting gui help idle makes obtaining the help you need easy look at the help menu and you see three entries for obtaining helpabout idleprovides you with the latest information about idle idle helpshows you text file containing information about working with the idle ide for examplethis is where you find list of the idle commands python docscontains information required to work with python commands and other elements choose helpabout idle to see the about idle dialog box shown in figure - near the middle of the dialog boxyou see urls for obtaining additional help each of the buttons displays text file containing useful informationespecially in the readme and news files click close to exit this dialog box figure - the about idle dialog box contains useful infor mation that you might not see otherwise precisely what you see when you choose helppython docs depends on the platform you use figure - shows the windows version of the dialog box the python docs file contains information about how to work with and use python to create applications it even has tutorial section in which you can find additional helpful tips after working your way through this book |
9,474 | figure - use python docs to dis cover more about using python to create applications configuring idle idle is basically fancy text editorwhen you think about itso it' not surprising that you can configure it to perform the task of editing text better choose optionsconfigure idle to see the idle preferences dialog box shown in figure - this is where you can choose things like what font idle uses when displaying text in the figureyou see the font/tabs tabwhich lets you choose the size and style font used for textalong with the number of spaces used for indentation (see the "understanding the use of indentationsection of this for detailsas previously mentionedidle uses color coding to make reading and understanding the code easier this tab lets you choose the colors used to perform highlightingas shown in figure - notice that you can save your selections as theme you can create different themes for different needs for exampleyou may use one theme when you use your laptop or other computing device in bright conditions and another theme in low light conditions |
9,475 | part igetting started with python figure - configure idle to meet your particular require ments figure - change the highlighting used for text so that you can see it better |
9,476 | even though you won' see shortcut keys used very often in this book due to platform differencesidle does support them the shortcut keys on your platform may differ from those shown in figure - idle comes with builtin key sets for windowsmacos xand unix you can choose any of these themes by clicking the small button next to the idle classic windows entry (see figure - you can also create your own custom theme that' based on another application you use figure - use shortcut keys that make the most sense to you as developer the general tabshown in figure - controls how idle works for exampleyou can tell idle to open python shell window (so that you can experimentor an edit window (so that you can write an applicationthe default is to open python shell window so that you can experiment with python and try new techniques you can also control whether idle prompts you to save files before running applications (always good idea in case the application causes the system to freezeand the size of the initial window when you create one paragraph formatting keeps your text from becoming too long to comfortably see in the window the defaults you see normally work just fineso there really isn' good reason to change them |
9,477 | part igetting started with python figure - the general tab controls the func tioning of the idle application the additional help sources feature lets you create new help sources for idle to use for exampleyou can create link to an online sourcesuch as python' online documentation at add new sourceclick add you see the new help source dialog boxshown in figure - where you can add the text that appears on the help menu for this information source and the location of that source on hard drive or online when you finish adding the sourceclick ok and you'll see it added to the idle help menu there are also buttons on the general tab of the idle preferences dialog box for editing and removing help sources figure - create new help sources as needed to make your develop ment experi ence easier |
9,478 | creating the application it' time to create your first python application your initial python shell window won' work for creating an applicationso you can begin by creating new edit window for the application you'll type the required commands and then save the file to disk opening new window the initial python shell window is just fine for experimentationbut you need niceclean edit window for typing your first application the python shell window is interactivewhich means that it gives you immediate feedback for any commands you type the edit window provides static environmentwhere you type commandssave themand then run them after you type enough commands to create an application the two windows serve distinctly different purposes choose filenew file to create new window new window like the one shown in figure - opens notice that the title bar says python untitled instead of python shell python shell window will always have the word "shellin the title bar the two windows also have some unique toolbar entries for examplean edit window includes the run commandwhich you use later to test your application figure - use the edit window to create applications working with the edit window is just like working with any other text editor you have access to basic editing commands such as copycutand paste pressing enter moves to the next line rather than executing command as it would when working in the python shell window that' because the edit window is static environment -one where you type commands and save them for later reuse |
9,479 | part igetting started with python the edit window also provides special commands to format the text the "understanding the use of indentationand "adding commentssections of this describe how to use the formatting features what you need to know now is that these formatting commands act differently from those in standard text editor because they help you control the appearance of code rather than of generic text many of the formatting features work automaticallyso you don' need to worry about them now finallythe edit window provides access to commands that tell python to perform the steps in the procedure you create one at time this process is called running the application the "running the applicationsection of this describes this process in greater detail typing the command as with the python shell windowyou can simply type command into the edit window to see how this workstype printnotice that the edit window provides you with helpful information about the print(commandas shown in figure - the information is little terseso you may not understand it now as the book progressesyou learn more about the print(command and the help provided by the edit window will make more sense for nowthe word value is the one that you need to focus on the print(command needs value before it can print anything and you'll encounter host of different values as the book progresses figure - the edit window pro vides helpful information about the commands you type |
9,480 | finish the command by typing "this is simple python application and pressing enter your application should look like the one shown in figure - this is one of the simplest applications you can create using python figure - complete application can be quite short saving the file you could run the application now if you wanted to howeversaving your application before you run it is always good idea that wayif you make mistake that causes python or the system to freeze for some reasonyour application code is still safe saving the application makes it easier to go back later to determine what went wrongmake correctionsand try running the application again choose filesave to display the save as dialog boxshown in figure - the edit window automatically chooses the python folder to save the application in howeverthis is where the python code residesand saving your application code in the same folder is bad idea the example code for this book is contained in folder named bp (beginning python for dummiesthe code for this is found in the \bp dsubfolder of the downloadable source (see the introduction for the location of the source code onlineif you wantcreate directory structure with similar names using technique that works for your platform as you follow along in the book you can also open the downloadable source code file for the book and avoid typing the example code |
9,481 | part igetting started with python type firstapp py in the filename field of the save as dialog box and click save your application code is now saved on disk and you can access it anytime you want figure - the save as dialog box provides the means for saving your application when you return to the edit windowthe title bar text changesas shown in figure - notice that the title bar includes the full path to the application figure - an applica tion on disk displays its name and path in the title bar |
9,482 | running the application applications aren' much good if you can' run them python provides variety of methods for running any application you create this section explores the easiest method for running an application after you create it you see additional methods in the "loading and running existing applicationssection of the the important thing to remember is that python provides an extremely flexible environmentso if one method of performing task doesn' quite workanother method will almost certainly succeed to run this first applicationchoose runrun module you see new copy of the python shell window opens and then the output of your application appearsas shown in figure - figure - the output of the example application appears in python shell window the top two lines of the output in figure - should be familiar by now -they're the information that always appears when you start the shell next comes ===============================restart ===============================message you see this message every time you run the application to see this for yourselfselect the edit window and choose runrun module the original python shell window is selectedanother message appearsand you see the output from your application againas shown in figure - |
9,483 | part igetting started with python figure - the python shell window displays restart message each time you run the application understanding the use of indentation as you work through the examples in this bookyou see that certain lines are indented in factthe examples also provide fair amount of white space (such as extra lines between lines of codepython ignores any indentation in your application the main reason to add indentation is to provide visual cues about your code in the same way that indentation is used for book outlinesindentation in code shows the relationships between various code elements the various uses of indentation will become more familiar as you work your way through the examples in the book howeverit' important to know at the outset why indentation is used and how it gets put in place soit' time for another example the following steps help you create new example that uses indentation to make the relationship between application elements lot more apparent and easier to figure out later choose filenew file idle creates new edit window for you type print("this is really long line of text that will you see the text displayed normally onscreenjust as you expect the plus sign (+tells python that there is additional text to display adding text from multiple lines together into single long piece of text is called concatenation you learn more about using this feature later in the bookso you don' need to worry about it now press enter the insertion point doesn' go back to the beginning of the lineas you might expect insteadit ends up directly under the first double quote |
9,484 | as shown in figure - this feature is called automatic indention and it' one of the features that differentiates regular text editor from one designed to write code type "appear on multiple lines in the source code file "and press enter notice that the insertion point goes back to the beginning of the line when idle senses that you have reached the end of the codeit automatically outdents the text to its original position choose filesave you see the save as dialog box type longline py in the file name field and click save to save it choose runrun module new python shell window opens with the text displayed even though the text appears on multiple lines in the source code fileit appears on just one line in the outputas shown in figure - figure - the edit window automati cally indents some types of text figure - use concat enation to make mul tiple lines of text appear on single line in the output |
9,485 | part igetting started with python adding comments people create notes for themselves all the time when you need to buy groceriesyou look through your cabinetsdetermine what you needand write it down on list when you get to the storeyou review your list to remember what you need using notes comes in handy for all sorts of needssuch as tracking the course of conversation between business partners or remembering the essential points of lecture humans need notes to jog their memories comments in source code are just another form of note you add them to the code so that you can remember what task the code performs later the following sections describe comments in more detail understanding comments computers need some special way to determine that the text you're writing is commentnot code to execute python provides two methods of defining text as comment and not as code the first method is the single-line comment it uses the number sign (#)like thisthis is comment print("hello from python!"#this is also comment single-line comment can appear on line by itself or it can appear after executable code it appears on only one line you typically use single-line comment for short descriptive textsuch as an explanation of particular bit of code when you need to create longer commentyou use multiline comment multiline comment both starts and ends with three double quotes (""")like this""applicationcomments py written byjohn purposeshows how to use comments ""everything between the two sets of triple double quotes is considered comment you typically use multiline comments for longer explanations of who created an applicationwhy it was createdand what tasks it performs of coursethere aren' any hard rules on precisely how you use comments the main goal is to tell the computer precisely what is and isn' comment so that it doesn' become confused |
9,486 | even though single-line and multiline comments are both commentsthe idle editor makes it easy to tell the difference between the two when you're using the default color schemesingle-line comments show up in red textwhile multiline comments show up in green text python doesn' care about the colorationit' only there to help you as the developer using comments to leave yourself reminders lot of people don' really understand comments -they don' quite know what to do with notes in code keep in mind that you might write piece of code today and then not look at it for years you need notes to jog your memory so that you remember what task the code performs and why you wrote it in facthere are some common reasons to use comments in your codereminding yourself about what the code does and why you wrote it telling others how to maintain your code making your code accessible to other developers listing ideas for future updates providing list of documentation sources you used to write the code maintaining list of improvements you've made you can use comments in lot of other waystoobut these are the most common ways look at the way comments are used in the examples in the bookespecially as you get to later where the code becomes more complex as your code becomes more complexyou need to add more comments and make the comments pertinent to what you need to remember about it using comments to keep code from executing developers also sometimes use the commenting feature to keep lines of code from executing (referred to as commenting outyou might need to do this in order to determine whether line of code is causing your application to fail in factit' such common and useful way to work with code that technique for adding this sort of comment is built right in to idle here' an example of |
9,487 | part igetting started with python how this feature works say that you have an application like the one shown in figure - (found in the comments py file provided as part of the downloadable source codefigure - sometimes developers need to comment out lines of code you might want to comment out the line that reads print("this code is commented out "to make this happenplace the insertion point at the beginning of the lineor simply select the entire lineand choose formatcomment out region idle then adds single-line comment to the codeas shown in figure - notice that this single-line comment uses two number signs (##to differentiate it from single-line comment you create by hand figure - comment out any code you don' want python to execute |
9,488 | of courseyou don' know yet whether the commenting has worked save the file to disk and then choose runrun module you see new python shell window open with just single line of outputas shown in figure - sothe first print(commandwhich isn' commented outexecutes just finebut the second one doesn' figure - commented out lines of code don' execute to add the code back into the applicationplace the insertion point at the beginning of the lineor highlight the entire lineand choose formatuncomment region idle removes the comment that it added earlier save the file and then choose runrun module to see the result this timeyou see both print(commands executeas shown in figure - figure - both print(commands execute when nei ther is com mented out you can comment out multiple lines of code at once by highlighting all of the lines and choosing formatcomment out region likewiseyou can uncomment out multiple lines of code by highlighting all the lines and choosing formatuncomment region it isn' necessary to comment out or uncomment out one line at time unless you have just one line of code to check |
9,489 | part igetting started with python loading and running existing applications running your application immediately after you write it is fun and interestingbut at some point you'll close idle and be left with file on your disk the file contains your applicationbut you need to know how to use that file to execute it python actually provides considerable number of ways to achieve this task the following sections describe just three of these approaches using the command line or terminal window the command lineor terminal windowprovides the means to execute commands by typing them in you can also create batch files to execute number of commands as part of batch process in this caseyou're looking at the native command environment provided by the platform you're usingrather than at the specialized python command line when working in this environmentyou type commands to start python and perform specific tasks for exampleif you want to execute firstapp (described in the "creating the applicationsection of this you type python firstapp py and press enter figure - shows typical results you can execute any other application this way as well figure - it' possible to execute an applica tion directly at the com mand line |
9,490 | using the edit window any time you're in idleyou can open an existing application in an edit window and execute itjust as you have in previous sections of this to perform this taskload the file you saved earlier by choosing fileopen you see an open dialog box that looks similar to the save as dialog box shown in figure - choose the folder containing the application in the look in field and highlight it in the list provided click open to open the file at this pointyou can choose runrun module to run the applicationjust as you would normally using the python shell window or python command line when you're in the idle python shell window or at the python command lineyou're in an environment where you can type commands and see them executed immediately howeveryou need to know the right commands to perform specific tasks in this casethe command is little more complex than the print(command you've been using to date if you want to execute firstappyou need really odd-looking command like one of the two shown hereexec(open(" :\\bp \\\\firstapp py"read()exec(open(" :/bp //firstapp py"read()the preceding two commands are really the same one using different type of slash the command works equally well with forward slashes or backslashes what this command says to do is this open the firstapp py file located in the \bp dfolder on the drive (open(command read the content of this file into the python environment (read(command execute the instructions found in the file after it' loaded (exec(commandit' little early for command like this onebut you'll discover that you can create combined commands of all sorts later in the book for nowjust try the command to see that it works figure - shows typical results |
9,491 | part igetting started with python figure - use forward slashes or backslashes to define the loca tion of your application closing idle eventuallyyou need to close idle when your session is finished the commands for closing idle appear on the file menuand there are actually two of them (which seems bit confusing)closecloses just the window that currently has focus this means that if you're in python shell window after running an applicationjust the python shell window closes and not the associated edit window exitcloses the current window and all associated windows this means that if you're in python shell window after running an applicationboth the python shell window and the associated edit window close when you close windowidle checks to ensure that you have saved any content to disk if you haven' saved the contentyou see dialog box asking whether you want to save it the fileclose and fileexit commands affect only the current session for exampleif you open two separate python filesyou need to close each file separately because each file is opened in separate session |
9,492 | talking the talk see an example of how you can combine functions and repetitive tasks at www dummies com/extras/beginningprogramming withpython |
9,493 | see how to create variables to hold data create functions to make code easier to read tell your python application to make decision perform repeating tasks ensure that your application can deal with errors |
9,494 | storing and modifying information in this understanding data storage considering the kinds of data storage adding dates and times to applications hapter introduces you to crudcreatereadupdateand delete -not that contains cruddy material this acronym provides an easy method to remember precisely what tasks all computer programs perform with information you want to manage of coursegeeks use special term for information -databut either information or data works fine for this book in order to make information usefulyou have to have some means of storing it permanently otherwiseevery time you turned the computer offall your information would be gone and the computer would provide limited value in additionpython must provide some rules for modifying information the alternative is to have applications running amokchanging information in any and every conceivable manner this is about controlling information -defining how information is stored permanently and manipulated by applications you create storing information an application requires fast access to information or else it will take long time to complete tasks as resultapplications store information in memory howevermemory is temporary when you turn off the machinethe information must be stored in some permanent formsuch as on your hard drivea universal serial bus (usbflash driveor secure digital (sdcard in additionyou must also consider the form of the informationsuch as whether it' number or text the following sections discuss the issue of storing information as part of an application in more detail |
9,495 | part iitalking the talk seeing variables as storage boxes when working with applicationsyou store information in variables variable is kind of storage box whenever you want to work with the informationyou access it using the variable if you have new information you want to storeyou put it in variable changing information means accessing the variable first and then storing the new value in the variable just as you store things in boxes in the real worldso you store things in variables ( kind of storage boxwhen working with applications computers are actually pretty tidy each variable stores just one piece of information using this technique makes it easy to find the particular piece of information you need -unlike in your closetwhere things from ancient egypt could be hidden even though the examples you work with in previous don' use variablesmost applications rely heavily on variables to make working with information easier using the right box to store the data people tend to store things in the wrong sort of box for exampleyou might find pair of shoes in garment bag and supply of pens in shoebox howeverpython likes to be neat as resultyou find numbers stored in one sort of variable and text stored in an entirely different kind of variable yesyou use variables in both casesbut the variable is designed to store particular kind of information using specialized variables makes it possible to work with the information inside in particular ways you don' need to worry about the details just yet -just keep in mind that each kind of information is stored in special kind of variable python uses specialized variables to store information to make things easy for the programmer and to ensure that the information remains safe howevercomputers don' actually know about information types all that the computer knows about are and swhich is the absence or presence of voltage at higher levelcomputers do work with numbersbut that' the extent of what computers do numberslettersdatestimesand any other kind of information you can think about all come down to and in the computer system for examplethe letter is actually stored as or the number the computer has no concept of the letter or of date such as |
9,496 | defining the essential python data types every programming language defines variables that hold specific kinds of informationand python is no exception the specific kind of variable is called data type knowing the data type of variable is important because it tells you what kind of information you find inside in additionwhen you want to store information in variableyou need variable of the correct data type to do it python doesn' allow you to store text in variable designed to hold numeric information doing so would damage the text and cause problems with the application you can generally classify python data types as numericstringand booleanalthough there really isn' any limit on just how you can view them the following sections describe each of the standard python data types within these classifications putting information into variables to place value into any variableyou make an assignment using the assignment operator (= discusses the whole range of basic python operators in more detailbut you need to know how to use this particular operator to some extent now for exampleto place the number into variable named myvaryou type myvar and press enter at the python prompt even though python doesn' provide any additional information to youyou can always type the variable name and press enter to see the value it containsas shown in figure - figure - use the assignment operator to place infor mation into variable understanding the numeric types humans tend to think about numbers in general terms we view and as being the same number -one of them simply has decimal point howeveras far as we're concernedthe two numbers are equal and we could easily use them interchangeably python views them as being different kinds of numbers |
9,497 | part iitalking the talk because each form requires different kind of processing the following sections describe the integerfloating-pointand complex number classes of data types that python supports integers any whole number is an integer for examplethe value is whole numberso it' an integer on the other hand isn' whole numberit has decimal part to itso it' not an integer integers are represented by the int data type as with storage boxesvariables have capacity limits trying to stuff value that' too large into storage box results in an error on most platformsyou can store numbers between - , , , , , , and , , , , , , within an int (which is the maximum value that fits in -bit variableeven though that' really large numberit isn' infinite when working with the int typeyou have access to number of interesting features many of them appear later in the bookbut one feature is the ability to use different numeric basesbase uses only and as numbers base uses the numbers through base uses the usual numeric system base is also called hex and uses the numbers through and the letters through to create different possible values to tell python when to use bases other than base you add and special letter to the number for example is the value one-zero-zero in base here are the letters you normally usebbase obase xbase it' also possible to convert numeric values to other bases using the bin()oct()and hex(commands soputting everything togetheryou can see how to convert between bases using the commands shown in figure - try the command shown in the figure yourself so that you can see how the various bases work using different base actually makes things easier in many situationsand you'll encounter some of those situations later in the book for nowall you really need to know is that integers support different numeric bases |
9,498 | figure - integers have many interesting featuresincluding the capabil ity to use different numeric bases floating-point values any number that includes decimal portion is floating-point value for example has decimal partso it' floating-point value many people get confused about whole numbers and floating-point numbersbut the difference is easy to remember if you see decimal in the numberthen it' floatingpoint value python stores floating-point values in the float data type floating-point values have an advantage over integer values in that you can store immensely large or incredibly small values in them as with integer variablesfloating-point variables have storage capacity in their casethe maximum value that variable can contain is +- and the minimum value that variable can contain is +- - on most platforms when working with floating-point valuesyou can assign the information to the variable in number of ways the two most common methods are to provide the number directly and to use scientific notation when using scientific notationan separates the number from its exponent figure - shows both methods of making an assignment notice that using negative exponent results in fractional value |
9,499 | part iitalking the talk figure - floatingpoint values provide multiple assignment techniques complex numbers you may or may not remember complex numbers from school complex number consists of real number and an imaginary number that are paired together just in case you've completely forgotten about complex numbersyou can read about them at complex-numbers html real-world uses for complex numbers includeelectrical engineering fluid dynamics quantum mechanics computer graphics dynamic systems complex numbers have other usestoobut this list should give you some ideas in generalif you aren' involved in any of these disciplinesyou probably won' ever encounter complex numbers howeverpython is one of the few languages that provides built-in data type to support them as you progress through the bookyou find other ways in which python lends itself especially well to science and engineering the imaginary part of complex number always appears with after it soif you want to create complex number with as the real part and as the imaginary partyou make an assignment like thismycomplex if you want to see the real part of the variableyou simply type mycomplex real at the python prompt and press enter likewiseif you want to see the imaginary part of the variableyou type mycomplex imag at the python prompt and press enter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.