id
int64
0
25.6k
text
stringlengths
0
4.59k
2,400
error handling in python introduction to error handling so far error messages haven' been discussed you could say that we have kinds of errorssyntax errors and exceptions syntax errors below we see an example of syntax errorsp world " world syntaxerror syntax in the example we have written print(hello worldinstead of print("hello world"and then the python interpreter gives us an error message exceptions even if statement or expression is syntactically correctit may cause an error when an attempt is made to execute it errors detected during execution are called exceptions and are not unconditionally fatalyou will soon learn how to handle them in python programs most exceptions are not handled by programshoweverand result in error messages as shown here traceback most last " by or traceback most last
2,401
" ' typeerror must be not exceptions handling it is possible to write programs that handle selected exceptions in python we can use the following built-in exceptions handling featuresthe try block lets you test block of code for errors the except block lets you handle the error the finally block lets you execute coderegardless of the result of the tryand except blocks when an error occursor exception as we call itpython will normally stop and generate an error message these exceptions can be handled using the try except statements some basic example try except "the or try print (xexcept " not you can also use multiple exceptions try print (xe nameerror " not except something wrong the finally blockif specifiedwill be executed regardless if the try block raises an error or not example
2,402
= try print (xe nameerror " not except something wrong finally "the program in general you should use try except finally when you try to open fileread or write to filesconnect to databaseetc example try open "lorum ipsum except something went wrong when finally close (
2,403
debugging in python debugging is the process of finding and resolving defects or problems within computer program that prevent correct operation of computer software or system [ debuggers are software tools which enable the programmer to monitor the execution of programstop itrestart itset breakpointsand change values in memory the term debugger can also refer to the person who is doing the debugging as programmerone of the first things that you need for serious program development is debugger python has built-in debugger that can be used if you are coding python with basic text editor and running your python programs from the command line better option is to use the debugging features integrated in your python editor debugging is typically integrated with the python editor you are using see the specific for the different python editors
2,404
installing and using python packages package contains all the files you need for module modules are python code libraries you can include in your project since python is open source you can find thousands of python packages that you can install and use in your python programs you can use python distribution like anaconda distribution (or similar python distributionsto download and install many common python packages as mentioned previously what is pippip is package manager for python packagesor modules if you like pip is tool for installing python packages if you do not have pip installedyou can download and install it from this pagepip is typically used from the command prompt (windowsor terminal window (macosinstalling python packages packagename uninstalling python packages packagename some python editors also have graphical way of installing python packageslikee visual studio
2,405
python environments and distributions
2,406
introduction to python environments and distributions python comes with many flavours and version python is open source and everybody can bundle and distribute python and different python packages python environment is context in which you run python code and includes python packages an environment consists of an interpretera library (typically the python standard library)and set of installed packages these components together determine which language constructs and syntax are validwhat operating-system functionality you can accessand which packages you can use you can have multiple python environments on your computer some of them arecpython distribution available from python org anaconda enthought canopy winpython etc it is easy to start using python by installing one of these python distributions
2,407
then install the additional python packages you need by using pip package and environment managers the two most popular tools for installing python packages and setting up python environments arepip python package manager conda package and environment manager (for python and other languagespip webpip is typically used from the command prompt (windowsor terminal window (macosinstalling python packages packagename uninstalling python packages packagename conda conda is an open source package management system and environment management system that runs on windowsmacos and linux conda installsruns and updates packages and their dependencies the conda package and environment manager is included in all versions of anaconda conda was created for python programsbut it can package and distribute software for any language conda allows you to to also create separate environments containing filespackages and their dependencies that will not interact with other environments
2,408
conda is part of or integrated with the anaconda python distribution web python virtual environments python "virtual environmentsallow python packages to be installed in an isolated location for particular applicationrather than being installed globally you can have multiple python environments on your computer python virtual environments have their own installation directories and they don' share libraries with other virtual environments python "virtual environmentsis handy when you have different python applications that needs different versions of python or different version of the python packages you are using
2,409
anaconda anaconda is not an editorbut python distribution package spyder is included in the python distribution package you can also use anaconda to install other editors or python packages it is available for windowsmacos and linux webwikipedia anaconda navigator anaconda navigator is desktop graphical user interface (guiincluded in anaconda distribution that allows users to launch applications and manage python packages the anaconda navigator can search for packages and install them on your computerrun the packages and update them figure shows the anaconda navigator
2,410
2,411
enthought canopy enthought canopy is python platform or python distribution for scientists and engineers it is available for windowsmacos and linux canopy is freely available to all users under the canopy license canopy provides access to several hundreds python packagesincluding numpyscipypandasmatplotliband ipython in additionwe have the canopy python editor enthought canopy is competitor to the anaconda python distribution it is matter of taste who you prefer web
2,412
python editors
2,413
python editors an editor is program where you create your code (and where you can run and test itmost editors have also features for debugging and intellisense in theoryyou can use windows notepad for creating python programsbut in practice it is impossible to create programs without having an editor with debuggingintellisensecolor formattingetc for simple python programs you can use the idle editorbut for more advanced programs better editor is recommended examples of python editorsspyder visual studio code visual studio pycharm wing jupyternotebook we will give an overview of these code editors in the next guess hundreds of different editors can be used for python programmingeither out of the box or if you install an additional extension that makes sure you can use python in that editor if you already have favorite code editorit is good change you can use that one for python programming which editor you should use depends on your backgroundwhat kind of code editors you have used previouslyyour programming skillswhat your are going to develop in pythonetc
2,414
to use python for numerical calculations and computationsspyder is good choice if you want to create web applications or other kinds of applicationsother editors are probably better to use for list of "best python editors"see [
2,415
spyder spyder short for "scientific python development environmentspyder is an open source cross-platform integrated development environment(idefor scientific programming in the python language figure spyder editor the spyder editor consists of the following parts or windowscode editor window ipython console window
2,416
etc webif you have used matlab previously or want to use python for scientific usespyder is good choice it is easy to install using the anaconda distribution web
2,417
visual studio code introduction to visual studio code visual studio code is simple and easy to use editor that can be used for many different programming languages figure using visual studio code as python editor right-click and select "run python file in terminalwebwikipedia
2,418
python in visual studio code in addition to visual studio code you need to install the python extension for visual studio code you must install python interpreter yourself separately from the extension for quick installuse python from python org python is an interpreted languageand in order to run python code and get python intellisense within visual studio codeyou must tell visual studio code which interpreter to use web
2,419
visual studio introduction to visual studio microsoft visual studio is an integrated development environment (idefrom microsoft it is used to develop computer programsas well as websitesweb appsweb services and mobile apps the default (mainprogramming language in visual studio is cbut many other programming languages are supported you could say visual studio is the big brother of visual studio code visual studio is available for windows and macos visual studio (from )has integrated support for pythonit is called "python support in visual studiowebwikipediago to my web site to learn more about visual studio and programmingvisual studio and work with python in visual studio work with python in visual studio
2,420
make visual studio ready for python programming visual studio is mainly for windows macos version of visual studio do existsbut it has lot less features than the windows edition note that python support is available only on visual studio for windows if you use mac and linuxyou need to use visual studio code you could say visual studio code is down-scaled version of visual studio visual studio (from )has integrated support for pythonit is called "python support in visual studioeven if it is integratedyou need to manually select which components you want to install on your computer make sure to download and run the latest visual studio installer for windows when you run the visual studio installer (either for the first time or if you already have installed visual studio and want to modify itthe window shown in figure pops up the installer presents you with list of so called workloadswhich are groups of related options for specific development areas for pythonselect the "python developmentworkload and select install (figure python interactive to quickly test python supportlaunch visual studiopress alt+ (or select from the menutools python python interactive windowto open the python interactive window see figure lets write something like this
2,421
figure python development workload * new python project lets see how we can create python application start by select from the menufile new project the new project window pops up see figure we can create an ordinary python application (one or more python scripts)we can choose to create web application using either web frameworks like django or flaskor we can create different desktop gui applications we can also create games example python hello world application in visual studio
2,422
we start by creating basic hello world python application see figure select file new project the new project window pops up see figure name the projecte "pythonapplication in the project exploreropen the "pythonapplication pyfile and enter the following python code worldhit (our click the green arrowin order to run or execute the python program you can also right click on the file and select "start without debugging[end of exampleexample visual studio python plotting create new python file by right click in the solution explorer and select add new item and then select "empty python fileenter the following python code im po rt im po rt numpy np xstart np increment np xstop np plt plot ( yp =
2,423
plt xlabel ' plt ylabel ' plt grid ( np pi - show see also figure make sure to select proper python environment see figure ( visual studio supports multiple python environments in this example we use the matplotlib package for plottingso we need to have that package installed on the computer you can install the matplotlib package in different python environments have installed the matplotlib package as part of the anaconda distribution setupso select "anaconda xin the python environments window if you haven' installed the matplotlib package yet (either as part of anaconda or manually using pip)you can also easily install python packages from visual studio see figure you can also easily see which python packages that are installed for the different python environments see figure
2,424
the good thing about using visual studio is that you have graphical user interface for everythingyou don' need to use the command window etc for installing python packagesetc hit (our click the green arrowin order to run or execute the python program you can also right click on the file and select "start without debuggingwe get the following resultssee figure [end of example
2,425
figure install python packages from visual studio
2,426
visual studio figure python plotting example with visual studio
2,427
pycharm pycharm is cross-platformwith windowsmacos and linux versions the community edition is free to usewhile the professional edition (paid versionhas some extra features the pycharm editor is shown in figure figure pycharm python editor webwikipediaanaconda and jetbrains also have collaboration and offer what they call pycharm for anaconda you can download it here
2,428
we have code editors like visual studio and visual studio code which can be used for many different programming languages by installing different types of plugins editors like spyder and pycharm are tailor-made editors for the python language spyder is light-weight ide typically used for scientific use pycharm on the other hand is full-blown ide for software development in general by using the python language it supports many pluginsit' easier to program djangoetc
2,429
wing python ide the wing python ide family of integrated development environments (idesfrom wingware were created specifically for the python programming language different version of wing exists [ ]wing very simplified free versionfor teaching beginning programmers wing personal free version that omits some featuresfor students and hobbyists wing pro full-featured commercial (paidversionfor professional programmers figure wing python ide web
2,430
2,431
jupyter notebook the jupyter notebook is an open-source web application that allows you to create and share documents that contain live codeequationsvisualizations and text the notebook has support for over programming languagesincluding python figure jupyter notebook [ webwikipedia
2,432
jupyterhub jupyterhub is multi-user version of the notebook designed for companiesclassrooms and research labs [ jupyterhub runs in the cloud or on your own hardware jupyterhub is open-source and designed to be run on variety of infrastructure this includes commercial cloud providersvirtual machinesor even your own laptop hardware web microsoft azure notebooks microsoft azure notebooks is version of jupyter notebook from microsoft the good thing about microsoft azure notebooks is that you have the infrastructure and everything up and running ready for you to use you can use it for free as well webexample example name figure shows an overview of my azure notebook projects figure azure notebook projects figure shows an overview of my azure notebook project notebooks figure shows an example of simple notebook [end of example
2,433
figure azure notebook example
2,434
python for mathematics applications
2,435
mathematics in python python is powerful tool for mathematical calculations if you are looking for similar using matlabplease take look at these resources basic math functions the python standard library consists of different modules for handling file /obasic mathematicsetc you don' need to install these separatelybut you need to important them when you want to use some of these modules or some of the functions within these modules in this we will focus on the math module that is part of the python standard library the math module has all the basic math functions you needsuch astrigonometric functionssin( )cos( )etc logarithmic functionslog()log ()etc constants like pieinfnanetc etc example using the math module we create some basic examples how to use librarya package or moduleif we need only the sin(function we can do like this from math im por sin ( print (yif we need few functions we can do like this
2,436
from math im por sin ( print ( cos (xprint (yif we need many functions we can do like this from math im por sin ( print ( cos (xprint (ywe can also use this alternative im po rt math math print (ywe can also write it like this im po rt math mt mt print ( [end of examplethere are advantages and disadvantages with the different approaches in your program you may need to use functions from many different modules or packages if you import the whole module instead of just the function(syou need you use more of the computer memory very often we also need to import and use multiple libraries where the different libraries have some functions with the same name but different use other useful modules in the python standard library are statistics (where you have functions like mean()stdev()etc for more information about the functions in the python standard librarysee
2,437
exercises below you find different self-paced exercises that you should go through and solve on your own the only way to learn python is to do lots of exercisesexercise create mathematical expressions in python create function that calculates the following mathematical expressionp eln ( ( test with different values for and [end of exerciseexercise create advanced mathematical expressions in python create the following expression in pythonf (xln (ax bx csin(ax bx px cos( )(ax bx ( given find ( (the answer should be ( tipyou should split the expressions into different partssuch aspoly ax bx num den this makes the expression simpler to read and understandand you minimize the risk of making an error while typing the expression in python when you got the correct answer try to change toe find ( [end of exerciseexercise pythagoras
2,438
pythagoras theorem is as followsc ( create function that uses pythagoras to calculate the hypotenuse of rightangled triangle (figure ) def pythagoras ( breturn [end of exerciseexercise albert einstein given the famous equation from albert einsteine mc ( the sun radiates / of energy calculate how much of the mass on the sun is used to create this energy per day how many years will it take to convert all the mass of the sun completelydo we need to worry if the sun will be used up in our generation or the nextjustify the answer the mass of the sun is kg
2,439
exercise cylinder surface area create function that finds the surface area of cylinder based on the height (hand the radius (rof the cylinder see figure ?figure cylinder [end of exercise statistics introduction to statistics mean or averagethe mean is the sum of the data divided by the number of data points it is commonly called "the average"formula for meann xn xi = ( example mean given the following dataset meann xi = (
2,440
variancevariance is measure of the variation in data set var( (xi ) = ( standard deviationthe standard deviation is measure of the spread of the values in dataset or the value of random variable it is defined as the square root of the variance std(xs var (xi ) = ( we typically use the symbol for standard deviation we have that var(xstatistics functions in python mathematical statistics functions in pythonstatistics is part of the the python standard library for more information about the functions in the python standard libraryseeexample statistics using the statistics module in python standard library below you find some examples how to use some of the statistics functions in the statistics module in python standard library im po rt data #mean average mean data ( standard data
2,441
print st dev median med median data med variance data listing statistics functions in python [end of exampleimportantdo not name your file "statistics pysince the import will be confused and throw the errors of the library not existing and the mean function not existing you can also use the numpy library numpy is the fundamental package for scientific computing with python here you find an overview of the numpy libraryexample statistics using the numpy library below you find some examples how to use some of the statistics functions in numpy im po rt numpy np data #mean average np mean data ( standard np data median med np median data med minimum value minv np min data minv maxumum value maxv np maxdata maxv listing statistics using the numpy library
2,442
exercise create your own statistics module in python using the built-in functions in the python standard library or the numpy library is straightforward in order to get deeper understanding of the mathematics behind these functions and to learn more python programmingyou should create your own statistics module in python create your own statistics module in python ( "mystatistics pyand then create python script ( "testmystatistics pywhere you test these functions you should at least implement functions for meanvariancestandard deviationminimum and maximum [end of exercise trigonometric functions python offers lots of trigonometric functionse sincostanetc notemost of the trigonometric functions require that the angle is expressed in radians example trigonometric functions in math module im po rt math mt *mt mt print ( mt print ( mt tan print (ylisting trigonometric functions in math module here we have used the math module in the python standard library for more information about the functions in the python standard librarysee
2,443
example plotting trigonometric functions in the example above we used some of the trigonometric functiosn in basic calculations lets see if we are able to plot these functions im po rt math mt im po rt xdata ydata in range ( xdata append mt ydata append xdata ydata show listing plotting trigonometric functions in the example we have plotted sin( )we can easily extend the program to plot cos( )etc for more information about the functions in the python standard librarysee[end of exampleexample trigonometric functions using numpy the problem with using the trigonometric functions in the the math module from the python standard library is that they don' handle an array as input we will use the numpy library instead because they handle arraysin addition to all the handy functionality in the numpy library im po rt numpy np im po rt xstart np increment np xstop np
2,444
plt plot ( yp = plt xlabel ' plt ylabel ' plt grid ( np pi - show np plt plot ( = np pi - show np tan plt plot ( =tan np pi - show listing trigonometric functions using numpy this python script gives the plots as shown in figure [end of exampleexercise create python functions for converting between radians an degrees since most of the trigonometric functions require that the angle is expressed in radianswe will create our own functions in order to convert between radians and degrees it is quite easy to convert from radians to degrees or from degrees to radians we have that [radians [degrees( this givesd[degreesr[radiansx ( and ( create two functions that convert from radians to degrees ( ( )and from degrees to radians ( ( )respectively [radiansd[degreesx
2,445
test the functions to make sure that they work as expected [end of exerciseexercise trigonometric functions on right triangle given right triangle as shown in figure create function that finds the angle (in degreesbased on input arguments ( , )( ,cand ( ,brespectively usee third input "typeto define the different types above use you previous function (to make sure the output of your function is in degrees and not in radians test the function to make sure it works properly tipwe have thatsin(aa arcsinc ( cos(ab arccosc ( tan(aa arctanb ( we may also need to use the pythagorastheoremc = = ** tan we also see that the answer in this case is the samewhich is expected (
2,446
exercise law of cosines given the triangle as shown in figure create function where you find using the law of cosines ab cos( ( test the functions to make sure it works properly [end of exerciseexercise plotting trigonometric functions plot sin(thand cos(thfor <th < in the same plot (both in the same plot and in different subplotsmake sure to add labels and legend and use different line styles and colors for the plots [end of exercise polynomials polynomial is expressed asp(xp xn xn- pn pn+ ( where are the coefficients of the polynomial we will use the polynomial module in the numpy package webother resourcespython advanced course topics polynomials
2,447
figure trigonometric functions
2,448
figure law of cosines
2,449
resources
2,450
python resources here you find my web page with python resources [ ]python home page [ ]python standard library [ ] python distributions anaconda python libraries numpy libraryscipy librarymatplotlib library python editors spyder
2,451
visual studiopycharmwingjupyter notebook python tutorials python tutorial schools com [ ]the python guru [ ]wikibooks beginner' python tutorialtutorialspoints python tutorialthe hitchhiker' guide to pythongoogle' python class python in visual studio work with python in visual studio
2,452
[ - halvorsen"technology blog [ - halvorsen"technology blog [ languages"the top programming languages [ overflow"stack overflow developer survey [ stackoverflow blog"the incredible growth of python [ python org"python org [ python org"the python tutorial [ python org"python documentation [ scipy org"scipy [ matplotlib org"matplotlib [ pandas"pandas [ wingware"wingware python ide [ schools com"python tutorial [ wikipedia"debugging [ techbeamers"get the best python ide [ jupyter"jupyter [ jupyterhub"jupyterhub
2,453
"the python standard library [ guru"the python guru
2,454
all rights reserved no part of this work may be reproduced or transmitted in any form or by any meanselectronic or mechanicalincluding photocopyingrecordingor by any information storage or retrieval systemwithout the prior written permission of the copyright owner and the publisher isbn- - isbn- - - publisherwilliam pollock production editorlaurel chun cover illustrationjosh ellingson interior designoctopod studios developmental editorsfrances saux and jan cash technical reviewersari lacenski and philip james copyeditorskim wimpsettbritt boganand paula fleming compositorssusan glinert stevens and danielle foster proofreaderslisa devoto farrell and emelie burnette indexerbim indexing and proofreading services for information on distributiontranslationsor bulk salesplease contact no starch pressinc directlyno starch pressinc th streetsan franciscoca phone info@nostarch com www nostarch com the library of congress control number for the first edition is no starch press and the no starch press logo are registered trademarks of no starch pressinc other product and company names mentioned herein may be the trademarks of their respective owners rather than use trademark symbol with every occurrence of trademarked namewe are using the names only in an editorial fashion and to the benefit of the trademark ownerwith no intention of infringement of the trademark the information in this book is distributed on an "as isbasiswithout warranty while every precaution has been taken in the preparation of this workneither the author nor no starch pressinc shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it this work is licensed under the creative commons attribution-noncommercial-sharealike united states license to view copy of this licensevisit send letter to creative commonspo box mountain viewca usa
2,455
2,456
al sweigart is software developer and tech book author python is his favorite programming languageand he is the developer of several open source modules for it his other books are freely available under creative commons license on his website weighs pounds about the tech reviewer philip james has been working in python for over decade and is frequent speaker in the python community he speaks on topics ranging from unix fundamentals to open source social networks philip is core contributor to the beeware project and lives in the san francisco bay area with his partner nic and her cat river
2,457
acknowledgments xxv introduction xxvii part ipython programming basics python basics flow control functions lists dictionaries and structuring data manipulating strings part iiautomating tasks pattern matching with regular expressions input validation reading and writing files organizing files debugging web scraping working with excel spreadsheets working with google sheets working with pdf and word documents working with csv files and json data keeping timescheduling tasksand launching programs sending email and text messages
2,458
controlling the keyboard and mouse with gui automation appendix ainstalling third-party modules appendix brunning programs appendix canswers to the practice questions index viii brief contents
2,459
acknowledgments xxv introduction xxvii whom is this book forxxviii conventions xxviii what is programmingxxix what is pythonxxx programmers don' need to know much math xxx you are not too old to learn programming xxxi programming is creative activity xxxi about this book xxxi downloading and installing python xxxiii downloading and installing mu xxxiv starting mu xxxiv starting idle xxxv the interactive shell xxxv installing third-party modules xxxvi how to find help xxxvi asking smart programming questions xxxviii summary xxxix part ipython programming basics python basics entering expressions into the interactive shell the integerfloating-pointand string data types string concatenation and replication storing values in variables assignment statements variable names your first program dissecting your program comments the print(function the input(function printing the user' name the len(function the str()int()and float(functions summary practice questions
2,460
flow control boolean values comparison operators boolean operators binary boolean operators the not operator mixing boolean and comparison operators elements of flow control conditions blocks of code program execution flow control statements if statements else statements elif statements while loop statements break statements continue statements for loops and the range(function importing modules from import statements ending program early with the sys exit(function short programguess the number short programrockpaperscissors summary practice questions functions def statements with parameters definecallpassargumentparameter return values and return statements the none value keyword arguments and the print(function the call stack local and global scope local variables cannot be used in the global scope local scopes cannot use variables in other local scopes global variables can be read from local scope local and global variables with the same name the global statement exception handling short programzigzag summary practice questions contents in detail
2,461
the collatz sequence input validation lists the list data type getting individual values in list with indexes negative indexes getting list from another list with slices getting list' length with the len(function changing values in list with indexes list concatenation and list replication removing values from lists with del statements working with lists using for loops with lists the in and not in operators the multiple assignment trick using the enumerate(function with lists using the random choice(and random shuffle(functions with lists augmented assignment operators methods finding value in list with the index(method adding values to lists with the append(and insert(methods removing values from lists with the remove(method sorting the values in list with the sort(method reversing the values in list with the reverse(method example programmagic ball with list sequence data types mutable and immutable data types the tuple data type converting types with the list(and tuple(functions references identity and the id(function passing references the copy module' copy(and deepcopy(functions short programconway' game of life summary practice questions practice projects comma code coin flip streaks character picture grid dictionaries and structuring data the dictionary data type dictionaries vs lists the keys()values()and items(methods contents in detail xi
2,462
the get(method the setdefault(method pretty printing using data structures to model real-world things tic-tac-toe board nested dictionaries and lists summary practice questions practice projects chess dictionary validator fantasy game inventory list to dictionary function for fantasy game inventory manipulating strings working with strings string literals indexing and slicing strings the in and not in operators with strings putting strings inside other strings useful string methods the upper()lower()isupper()and islower(methods the isx(methods the startswith(and endswith(methods the join(and split(methods splitting strings with the partition(method justifying text with the rjust()ljust()and center(methods removing whitespace with the strip()rstrip()and lstrip(methods numeric values of characters with the ord(and chr(functions copying and pasting strings with the pyperclip module projectmulti-clipboard automatic messages step program design and data structures step handle command line arguments step copy the right phrase projectadding bullets to wiki markup step copy and paste from the clipboard step separate the lines of text and add the star step join the modified lines short progampig latin summary practice questions practice projects table printer zombie dice bots xii contents in detail
2,463
pattern matching with regular expressions finding patterns of text without regular expressions finding patterns of text with regular expressions creating regex objects matching regex objects review of regular expression matching more pattern matching with regular expressions grouping with parentheses matching multiple groups with the pipe optional matching with the question mark matching zero or more with the star matching one or more with the plus matching specific repetitions with braces greedy and non-greedy matching the findall(method character classes making your own character classes the caret and dollar sign characters the wildcard character matching everything with dot-star matching newlines with the dot character review of regex symbols case-insensitive matching substituting strings with the sub(method managing complex regexes combining re ignorecasere dotalland re verbose projectphone number and email address extractor step create regex for phone numbers step create regex for email addresses step find all matches in the clipboard text step join the matches into string for the clipboard running the program ideas for similar programs summary practice questions practice projects date detection strong password detection regex version of the strip(method input validation the pyinputplus module the minmaxgreaterthanand lessthan keyword arguments the blank keyword argument contents in detail xiii
2,464
the allowregexes and blockregexes keyword arguments passing custom validation function to inputcustom( projecthow to keep an idiot busy for hours projectmultiplication quiz summary practice questions practice projects sandwich maker write your own multiplication quiz reading and writing files files and file paths backslash on windows and forward slash on macos and linux using the operator to join paths the current working directory the home directory absolute vs relative paths creating new folders using the os makedirs(function handling absolute and relative paths getting the parts of file path finding file sizes and folder contents modifying list of files using glob patterns checking path validity the file reading/writing process opening files with the open(function reading the contents of files writing to files saving variables with the shelve module saving variables with the pprint pformat(function projectgenerating random quiz files step store the quiz data in dictionary step create the quiz file and shuffle the question order step create the answer options step write content to the quiz and answer key files projectupdatable multi-clipboard step comments and shelf setup step save clipboard content with keyword step list keywords and load keyword' content summary practice questions practice projects extending the multi-clipboard mad libs regex search xiv contents in detail
2,465
organizing files the shutil module copying files and folders moving and renaming files and folders permanently deleting files and folders safe deletes with the send trash module walking directory tree compressing files with the zipfile module reading zip files extracting from zip files creating and adding to zip files projectrenaming files with american-style dates to european-style dates step create regex for american-style dates step identify the date parts from the filenames step form the new filename and rename the files ideas for similar programs projectbacking up folder into zip file step figure out the zip file' name step create the new zip file step walk the directory tree and add to the zip file ideas for similar programs summary practice questions practice projects selective copy deleting unneeded files filling in the gaps debugging raising exceptions getting the traceback as string assertions using an assertion in traffic light simulation logging using the logging module don' debug with the print(function logging levels disabling logging logging to file mu' debugger continue step in step over step out stop contents in detail xv
2,466
breakpoints summary practice questions practice project debugging coin toss web scraping projectmapit py with the webbrowser module step figure out the url step handle the command line arguments step handle the clipboard content and launch the browser ideas for similar programs downloading files from the web with the requests module downloading web page with the requests get(function checking for errors saving downloaded files to the hard drive html resources for learning html quick refresher viewing the source html of web page opening your browser' developer tools using the developer tools to find html elements parsing html with the bs module creating beautifulsoup object from html finding an element with the select(method getting data from an element' attributes projectopening all search results step get the command line arguments and request the search page step find all the results step open web browsers for each result ideas for similar programs projectdownloading all xkcd comics step design the program step download the web page step find and download the comic image step save the image and find the previous comic ideas for similar programs controlling the browser with the selenium module starting selenium-controlled browser finding elements on the page clicking the page filling out and submitting forms sending special keys clicking browser buttons more information on selenium xvi contents in detail
2,467
practice questions practice projects command line emailer image site downloader link verification working with excel spreadsheets excel documents installing the openpyxl module reading excel documents opening excel documents with openpyxl getting sheets from the workbook getting cells from the sheets converting between column letters and numbers getting rows and columns from the sheets workbookssheetscells projectreading data from spreadsheet step read the spreadsheet data step populate the data structure step write the results to file ideas for similar programs writing excel documents creating and saving excel documents creating and removing sheets writing values to cells projectupdating spreadsheet step set up data structure with the update information step check all rows and update incorrect prices ideas for similar programs setting the font style of cells font objects formulas adjusting rows and columns setting row height and column width merging and unmerging cells freezing panes charts summary practice questions practice projects multiplication table maker blank row inserter spreadsheet cell inverter text files to spreadsheet spreadsheet to text files contents in detail xvii
2,468
working with google sheets installing and setting up ezsheets obtaining credentials and token files revoking the credentials file spreadsheet objects creatinguploadingand listing spreadsheets spreadsheet attributes downloading and uploading spreadsheets deleting spreadsheets sheet objects reading and writing data creating and deleting sheets copying sheets working with google sheets quotas summary practice questions practice projects downloading google forms data converting spreadsheets to other formats finding mistakes in spreadsheet working with pdf and word documents pdf documents extracting text from pdfs decrypting pdfs creating pdfs projectcombining select pages from many pdfs step find all pdf files step open each pdf step add each page step save the results ideas for similar programs word documents reading word documents getting the full text from docx file styling paragraph and run objects creating word documents with nondefault styles run attributes writing word documents adding headings adding line and page breaks adding pictures creating pdfs from word documents summary practice questions xviii contents in detail
2,469
pdf paranoia custom invitations as word documents brute-force pdf password breaker working with csv files and json data the csv module reader objects reading data from reader objects in for loop writer objects the delimiter and lineterminator keyword arguments dictreader and dictwriter csv objects projectremoving the header from csv files step loop through each csv file step read in the csv file step write out the csv file without the first row ideas for similar programs json and apis the json module reading json with the loads(function writing json with the dumps(function projectfetching current weather data step get location from the command line argument step download the json data step load json data and print weather ideas for similar programs summary practice questions practice project excel-to-csv converter keeping timescheduling tasksand launching programs the time module the time time(function the time sleep(function rounding numbers projectsuper stopwatch step set up the program to track times step track and print lap times ideas for similar programs the datetime module the timedelta data type pausing until specific date converting datetime objects into strings converting strings into datetime objects contents in detail xix
2,470
multithreading passing arguments to the thread' target function concurrency issues projectmultithreaded xkcd downloader step modify the program to use function step create and start threads step wait for all threads to end launching other programs from python passing command line arguments to the popen(function task schedulerlaunchdand cron opening websites with python running other python scripts opening files with default applications projectsimple countdown program step count down step play the sound file ideas for similar programs summary practice questions practice projects prettified stopwatch scheduled web comic downloader sending email and text messages sending and receiving email with the gmail api enabling the gmail api sending mail from gmail account reading mail from gmail account searching mail from gmail account downloading attachments from gmail account smtp sending email connecting to an smtp server sending the smtp "hellomessage starting tls encryption logging in to the smtp server sending an email disconnecting from the smtp server imap retrieving and deleting emails with imap connecting to an imap server logging in to the imap server searching for email fetching an email and marking it as read getting email addresses from raw message xx contents in detail
2,471
deleting emails disconnecting from the imap server projectsending member dues reminder emails step open the excel file step find all unpaid members step send customized email reminders sending text messages with sms email gateways sending text messages with twilio signing up for twilio account sending text messages project"just text memodule summary practice questions practice projects random chore assignment emailer umbrella reminder auto unsubscriber controlling your computer through email manipulating images computer image fundamentals colors and rgba values coordinates and box tuples manipulating images with pillow working with the image data type cropping images copying and pasting images onto other images resizing an image rotating and flipping images changing individual pixels projectadding logo step open the logo image step loop over all files and open images step resize the images step add the logo and save the changes ideas for similar programs drawing on images drawing shapes drawing text summary practice questions practice projects extending and fixing the project programs identifying photo folders on the hard drive custom seating cards contents in detail xxi
2,472
controlling the keyboard and mouse with gui automation installing the pyautogui module setting up accessibility apps on macos staying on track pauses and fail-safes shutting down everything by logging out controlling mouse movement moving the mouse getting the mouse position controlling mouse interaction clicking the mouse dragging the mouse scrolling the mouse planning your mouse movements working with the screen getting screenshot analyzing the screenshot image recognition getting window information obtaining the active window other ways of obtaining windows manipulating windows controlling the keyboard sending string from the keyboard key names pressing and releasing the keyboard hotkey combinations setting up your gui automation scripts review of the pyautogui functions projectautomatic form filler step figure out the steps step set up coordinates step start typing data step handle select lists and radio buttons step submit the form and wait displaying message boxes summary practice questions practice projects looking busy using the clipboard to read text field instant messenger bot game-playing bot tutorial xxii contents in detail
2,473
installing third-party modules the pip tool installing third-party modules installing modules for the mu editor running programs running programs from the terminal window running python programs on windows running python programs on macos running python programs on ubuntu linux running python programs with assertions disabled answers to the practice questions index contents in detail xxiii
2,474
it' misleading to have just my name on the cover couldn' have written book like this without the help of lot of people ' like to thank my publisherbill pollockmy editorslaurel chunleslie shengreg poulosjennifer griffith-delgadoand frances sauxand the rest of the staff at no starch press for their invaluable help thanks to my tech reviewersari lacenski and philip jamesfor great suggestionseditsand support many thanks to everyone at the python software foundation for their great work the python community is the best one 've found in the tech industry finallyi would like to thank my familyfriendsand the gang at shotwell' for not minding the busy life 've had while writing this book cheers
2,475
"you've just done in two hours what it takes the three of us two days to do my college roommate was working at retail electronics store in the early occasionallythe store would receive spreadsheet of thousands of product prices from other stores team of three employees would print the spreadsheet onto thick stack of paper and split it among themselves for each product pricethey would look up their store' price and note all the products that their competitors sold for less it usually took couple of days "you knowi could write program to do that if you have the original file for the printouts,my roommate told themwhen he saw them sitting on the floor with papers scattered and stacked all around after couple of hourshe had short program that read competitor' price from filefound the product in the store' databaseand noted whether the competitor was cheaper he was still new to programmingso he spent most of his time looking up documentation in programming
2,476
and his co-workers took an extra-long lunch that day this is the power of computer programming computer is like swiss army knife that you can configure for countless tasks many people spend hours clicking and typing to perform repetitive tasksunaware that the machine they're using could do their job in seconds if they gave it the right instructions whom is this book forsoftware is at the core of so many of the tools we use todaynearly everyone uses social networks to communicatemany people have internet-connected computers in their phonesand most office jobs involve interacting with computer to get work done as resultthe demand for people who can code has skyrocketed countless booksinteractive web tutorialsand developer boot camps promise to turn ambitious beginners into software engineers with six-figure salaries this book is not for those people it' for everyone else on its ownthis book won' turn you into professional software developer any more than few guitar lessons will turn you into rock star but if you're an office workeradministratoracademicor anyone else who uses computer for work or funyou will learn the basics of programming so that you can automate simple tasks such as thesemoving and renaming thousands of files and sorting them into folders filling out online forms--no typing required downloading files or copying text from website whenever it updates having your computer text you custom notifications updating or formatting excel spreadsheets checking your email and sending out prewritten responses these tasks are simple but time-consuming for humansand they're often so trivial or specific that there' no ready-made software to perform them armed with little bit of programming knowledgehoweveryou can have your computer do these tasks for you conventions this book is not designed as reference manualit' guide for beginners the coding style sometimes goes against best practices (for examplesome programs use global variables)but that' trade-off to make the code simpler to learn this book is made for people to write throwaway codeso there' not much time spent on style and elegance sophisticated programming concepts--like object-oriented programminglist comprehensionsand generators--aren' covered because of the complexity they xxviii introduction
2,477
be changed to improve efficiencybut this book is mostly concerned with getting programs to work with the least amount of effort on your part what is programmingtelevision shows and films often show programmers furiously typing cryptic streams of and on glowing screensbut modern programming isn' that mysterious programming is simply the act of entering instructions for the computer to perform these instructions might crunch some numbersmodify textlook up information in filesor communicate with other computers over the internet all programs use basic instructions as building blocks here are few of the most common onesin english"do thisthen do that "if this condition is trueperform this actionotherwisedo that action "do this action exactly times "keep doing that until this condition is true you can combine these building blocks to implement more intricate decisionstoo for examplehere are the programming instructionscalled the source codefor simple program written in the python programming language starting at the topthe python software runs each line of code (some lines are run only if certain condition is true or else python runs some other lineuntil it reaches the bottom passwordfile open('secretpasswordfile txt' secretpassword passwordfile read( print('enter your password 'typedpassword input( if typedpassword =secretpasswordy print('access granted' if typedpassword =' 'print('that password is one that an idiot puts on their luggage 'elseprint('access denied'you might not know anything about programmingbut you could probably make reasonable guess at what the previous code does just by reading it firstthe file secretpasswordfile txt is opened uand the secret password in it is read thenthe user is prompted to input password (from the keyboardw these two passwords are compared xand if they're the samethe program prints access granted to the screen nextthe program checks to see whether the password is and hints that this choice might not be the best for password if the passwords are not the samethe program prints access denied to the screen introduction xxix
2,478
python is programming language (with syntax rules for writing what is considered valid python codeand the python interpreter software that reads source code (written in the python languageand performs its instructions you can download the python interpreter for free at python org/and there are versions for linuxmacosand windows the name python comes from the surreal british comedy group monty pythonnot from the snake python programmers are affectionately called pythonistasand both monty python and serpentine references usually pepper python tutorials and documentation programmers don' need to know much math the most common anxiety hear about learning to program is the notion that it requires lot of math actuallymost programming doesn' require math beyond basic arithmetic in factbeing good at programming isn' that different from being good at solving sudoku puzzles to solve sudoku puzzlethe numbers through must be filled in for each roweach columnand each interior square of the full board some numbers are provided to give you startand you find solution by making deductions based on these numbers in the puzzle shown in figure - since appears in the first and second rowsit cannot show up in these rows again thereforein the upper-right gridit must be in the third row since the last column also already has in itthe cannot go to the right of the so it must go to the left of the solving one rowcolumnor square will provide more clues to the rest of the puzzleand as you fill in one group of numbers to and then anotheryou'll soon solve the entire grid figure - new sudoku puzzle (leftand its solution (rightdespite using numberssudoku doesn' involve much math (images (cwikimedia commonsjust because sudoku involves numbers doesn' mean you have to be good at math to figure out the solution the same is true of programming like solving sudoku puzzlewriting programs involves breaking xxx introduction
2,479
programs (that isfinding and fixing errors)you'll patiently observe what the program is doing and find the cause of the bugs and like all skillsthe more you programthe better you'll become you are not too old to learn programming the second most common anxiety hear about learning to program is that people think they're too old to learn it read many internet comments from folks who think it' too late for them because they are already (gasp! years old this is clearly not "too oldto learn to programmany people learn much later in life you don' need to have started as child to become capable programmer but the image of programmers as whiz kids is persistent one unfortunatelyi contribute to this myth when tell others that was in grade school when started programming howeverprogramming is much easier to learn today than it was in the todaythere are more booksbetter search enginesand many more online question-and-answer websites on top of thatthe programming languages themselves are far more user-friendly for these reasonseverything learned about programming in the years between grade school and high school graduation could be learned today in about dozen weekends my head start wasn' really much of head start it' important to have "growth mindsetabout programming--in other wordsunderstand that people develop programming skills through practice they aren' just born as programmersand being unskilled at programming now is not an indication that you can never become an expert programming is creative activity programming is creative tasklike paintingwritingknittingor constructing lego castles like painting blank canvasmaking software has many constraints but endless possibilities the difference between programming and other creative activities is that when programmingyou have all the raw materials you need in your computeryou don' need to buy any additional canvaspaintfilmyarnlego bricksor electronic components decade-old computer is more than powerful enough to write programs once your program is writtenit can be copied perfectly an infinite number of times knit sweater can only be worn by one person at timebut useful program can easily be shared online with the entire world about this book the first part of this book covers basic python programming conceptsand the second part covers various tasks you can have your computer automate each in the second part has project programs for you to study here' brief rundown of what you'll find in each introduction xxxi
2,480
python basics covers expressionsthe most basic type of python instructionand how to use the python interactive shell software to experiment with code flow control explains how to make programs decide which instructions to execute so your code can intelligently respond to different conditions functions instructs you on how to define your own functions so that you can organize your code into more manageable chunks lists introduces the list data type and explains how to organize data dictionaries and structuring data introduces the dictionary data type and shows you more powerful ways to organize data manipulating strings covers working with text data (called strings in pythonpart iiautomating tasks pattern matching with regular expressions covers how python can manipulate strings and search for text patterns with regular expressions input validation explains how your program can verify the information user gives itensuring that the user' data arrives in format that won' cause errors in the rest of the program reading and writing files explains how your program can read the contents of text files and save information to files on your hard drive organizing files shows how python can copymoverenameand delete large numbers of files much faster than human user can also explains compressing and decompressing files debugging shows how to use python' various bugfinding and bug-fixing tools web scraping shows how to write programs that can automatically download web pages and parse them for information this is called web scraping working with excel spreadsheets covers programmatically manipulating excel spreadsheets so that you don' have to read them this is helpful when the number of documents you have to analyze is in the hundreds or thousands working with google sheets covers how to read and update google sheetsa popular web-based spreadsheet applicationusing python working with pdf and word documents covers programmatically reading word and pdf documents xxxii introduction
2,481
explain how to programmatically manipulate documentsnow discussing csv and json files keeping timescheduling tasksand launching programs explains how python programs handle time and dates and how to schedule your computer to perform tasks at certain times also shows how your python programs can launch non-python programs sending email and text messages explains how to write programs that can send emails and text messages on your behalf manipulating images explains how to programmatically manipulate images such as jpeg or png files controlling the keyboard and mouse with gui automation explains how to programmatically control the mouse and keyboard to automate clicks and keypresses appendix ainstalling third-party modules shows you how to extend python with useful additional modules appendix brunning programs shows you how to run your python programs on windowsmacosand linux from outside of the code editor appendix canswers to the practice questions provides answers and some additional context to the practice questions at the end of each downloading and installing python you can download python for windowsmacosand ubuntu for free at website' download pageall of the programs in this book should work warning be sure to download version of python (such as the programs in this book are written to run on python and may not run correctlyif at allon python on the download pageyou'll find python installers for -bit and -bit computers for each operating systemso first figure out which installer you need if you bought your computer in or laterit is most likely -bit system otherwiseyou have -bit versionbut here' how to find out for sureon windowsselect start control panel system and check whether system type says -bit or -bit on macosgo the apple menuselect about this macmore info system reporthardwareand then look at the processor name field if it says intel core solo or intel core duoyou have -bit machine if it says anything else (including intel core duo)you have -bit machine introduction xxxiii
2,482
on ubuntu linuxopen terminal and run the command uname - response of means -bitand means -bit on windowsdownload the python installer (the filename will end with msiand double-click it follow the instructions the installer displays on the screen to install pythonas listed here select install for all users and click next accept the default options for the next several windows by clicking next on macosdownload the dmg file that' right for your version of macos and double-click it follow the instructions the installer displays on the screen to install pythonas listed here when the dmg package opens in new windowdouble-click the python mpkg file you may have to enter the administrator password accept the default options for the next several windows by clicking continue and click agree to accept the license on the final windowclick install if you're running ubuntuyou can install python from the terminal by following these steps open the terminal window enter sudo apt-get install python enter sudo apt-get install idle enter sudo apt-get install python -pip downloading and installing mu while the python interpreter is the software that runs your python programsthe mu editor software is where you'll enter your programsmuch the way you type in word processor you can download mu from on windows and macosdownload the installer for your operating system and then run it by double-clicking the installer file if you are on macosrunning the installer opens window where you must drag the mu icon to the applications folder icon to continue the installation if you are on ubuntuyou'll need to install mu as python package in that caseclick the instructions button in the python package section of the download page starting mu once it' installedlet' start mu xxxiv introduction on windows or laterclick the start icon in the lower-left corner of your screenenter mu in the search boxand select it
2,483
on macosopen the finder windowclick applicationsand then click mu-editor on ubuntuselect applicationsaccessories terminal and then enter python - mu the first time mu runsa select mode window will appear with options adafruit circuitpythonbbc micro:bitpygame zeroand python select python you can always change the mode later by clicking the mode button at the top of the editor window note you'll need to download mu version or later in order to install the third-party modules featured in this book as of this writingis an alpha release and is listed on the download page as separate link from the main download links starting idle this book uses mu as an editor and interactive shell howeveryou can use any number of editors for writing python code the integrated development and learning environment (idlesoftware installs along with pythonand it can serve as second editor if for some reason you can' get mu installed or working let' start idle now on windows or laterclick the start icon in the lower-left corner of your screenenter idle in the search boxand select idle (python guion macosopen the finder windowclick applicationsclick python and then click the idle icon on ubuntuselect applicationsaccessories terminal and then enter idle (you may also be able to click applications at the top of the screenselect programmingand then click idle the interactive shell when you run muthe window that appears is called the file editor window you can open the interactive shell by clicking the repl button shell is program that lets you type instructions into the computermuch like the terminal or command prompt on macos and windowsrespectively python' interactive shell lets you enter instructions for the python interpreter software to run the computer reads the instructions you enter and runs them immediately in muthe interactive shell is pane in the lower half of the window with the following textjupyter qtconsole python ( : fed oct : : [msc bit (amd )type 'copyright''creditsor 'licensefor more information introduction xxxv
2,484
in [ ]if you run idlethe interactive shell is the window that first appears it should be mostly blank except for text that looks something like thispython (tags/vb : deb jun : : [msc bit (amd )on win type "help""copyright""creditsor "licensefor more information in [ ]and are called prompts the examples in this book will use the prompt for the interactive shell since it' more common if you run python from the terminal or command promptthey'll use the promptas well the in [ ]prompt was invented by jupyter notebookanother popular python editor for exampleenter the following into the interactive shell next to the promptprint('helloworld!'after you type that line and press enterthe interactive shell should display this in responseprint('helloworld!'helloworldyou've just given the computer an instructionand it did what you told it to doinstalling third-party modules some python code requires your program to import modules some of these modules come with pythonbut others are third-party modules created by developers outside of the python core dev team appendix has detailed instructions on how to use the pip program (on windowsor pip program (on macos and linuxto install third-party modules consult appendix when this book instructs you to install particular third-party module how to find help programmers tend to learn by searching the internet for answers to their questions this is quite different from the way many people are accustomed to learning--through an in-person teacher who lectures and can answer questions what' great about using the internet as schoolroom is that there are whole communities of folks who can answer your questions xxxvi introduction
2,485
answers are waiting online for you to find them if you encounter an error message or have trouble making your code workyou won' be the first person to have your problemand finding solution is easier than you might think for examplelet' cause an error on purposeenter ' into the interactive shell you don' need to know what this instruction means right nowbut the result should look like this' traceback (most recent call last)file ""line in ' typeerrorcan' convert 'intobject to str implicitly the error message appears because python couldn' understand your instruction the traceback part of the error message shows the specific instruction and line number that python had trouble with if you're not sure what to make of particular error messagesearch for it online enter "typeerrorcan' convert 'intobject to str implicitly(including the quotesinto your favorite search engineand you should see tons of links explaining what the error message means and what causes itas shown in figure - figure - the google results for an error message can be very helpful introduction xxxvii
2,486
that some other helpful person has already answered it no one person can know everything about programmingso an everyday part of any software developer' job is looking up answers to technical questions asking smart programming questions if you can' find the answer by searching onlinetry asking people in web forum such as stack overflow (programmingsubreddit at in mind there are smart ways to ask programming questions that help others help you to begin withbe sure to read the faq sections at these websites about the proper way to post questions when asking programming questionsremember to do the followingexplain what you are trying to donot just what you did this lets your helper know if you are on the wrong track specify the point at which the error happens does it occur at the very start of the program or only after you do certain actioncopy and paste the entire error message and your code to comor these websites make it easy to share large amounts of code with people onlinewithout losing any text formatting you can then put the url of the posted code in your email or forum post for examplehere some pieces of code 've postedexplain what you've already tried to do to solve your problem this tells people you've already put in some work to figure things out on your own list the version of python you're using (there are some key differences between version python interpreters and version python interpreters alsosay which operating system and version you're running if the error came up after you made change to your codeexplain exactly what you changed say whether you're able to reproduce the error every time you run the program or whether it happens only after you perform certain actions if the latterthen explain what those actions are always follow good online etiquette as well for exampledon' post your questions in all caps or make unreasonable demands of the people trying to help you you can find more information on how to ask for programming help in the blog post at frequently asked questions about programming at / /learnprogramming/wiki/faqand similar list about getting job in software development at indexxxxviii introduction
2,487
on my blog at with questions at al@inventwithpython com althoughyou may get faster response by posting your questions to summary for most peopletheir computer is just an appliance instead of tool but by learning how to programyou'll gain access to one of the most powerful tools of the modern worldand you'll have fun along the way programming isn' brain surgery--it' fine for amateurs to experiment and make mistakes this book assumes you have zero programming knowledge and will teach you quite bitbut you may have questions beyond its scope remember that asking effective questions and knowing how to find answers are invaluable tools on your programming journey let' beginintroduction xxxix
2,488
py thon progr amming basics
2,489
py thon basics the python programming language has wide range of syntactical constructionsstandard library functionsand interactive development environment features fortunatelyyou can ignore most of thatyou just need to learn enough to write some handy little programs you willhoweverhave to learn some basic programming concepts before you can do anything like wizard in trainingyou might think these concepts seem arcane and tediousbut with some knowledge and practiceyou'll be able to command your computer like magic wand and perform incredible feats this has few examples that encourage you to type into the interactive shellalso called the repl (read-evaluate-print loop)which lets you run (or executepython instructions one at time and instantly shows you the results using the interactive shell is great for learning what basic python instructions doso give it try as you follow along you'll remember the things you do much better than the things you only read
2,490
you can run the interactive shell by launching the mu editorwhich you should have downloaded when going through the setup instructions in the preface on windowsopen the start menutype "mu,and open the mu app on macosopen your applications folder and double-click mu click the new button and save an empty file as blank py when you run this blank file by clicking the run button or pressing it will open the interactive shellwhich will open as new pane that opens at the bottom of the mu editor' window you should see prompt in the interactive shell enter at the prompt to have python do some simple math the mu window should now look like this in python is called an expressionwhich is the most basic kind of programming instruction in the language expressions consist of values (such as and operators (such as +)and they can always evaluate (that isreducedown to single value that means you can use expressions anywhere in python code that you could also use value in the previous example is evaluated down to single value single value with no operators is also considered an expressionthough it evaluates only to itselfas shown here rrors re ok ay programs will crash if they contain code the computer can' understandwhich will cause python to show an error message an error message won' break your computerthoughso don' be afraid to make mistakes crash just means the program stopped running unexpectedly if you want to know more about an erroryou can search for the exact error message text online for more information you can also check out the resources at python error messages and their meanings
2,491
exampletable - lists all the math operators in python table - math operators from highest to lowest precedence operator operation example evaluates to *exponent * modulus/remainder /integer division/floored quotient / division multiplication subtraction addition the order of operations (also called precedenceof python math operators is similar to that of mathematics the *operator is evaluated firstthe *///and operators are evaluated nextfrom left to rightand the and operators are evaluated last (also from left to rightyou can use parentheses to override the usual precedence if you need to whitespace in between the operators and values doesn' matter for python (except for the indentation at the beginning of the line)but single space is convention enter the following expressions into the interactive shell ( * / ( (( ( ) python basics
2,492
python does the hard part of evaluating it down to single value python will keep evaluating parts of the expression until it becomes single valueas shown here( (( ( ) (( ( ) ( these rules for putting operators and values together to form expressions are fundamental part of python as programming languagejust like the grammar rules that help us communicate here' an examplethis is grammatically correct english sentence this grammatically is sentence not english correct the second line is difficult to parse because it doesn' follow the rules of english similarlyif you enter bad python instructionpython won' be able to understand it and will display syntaxerror error messageas shown here file ""line syntaxerrorinvalid syntax file ""line syntaxerrorinvalid syntax you can always test to see whether an instruction works by entering it into the interactive shell don' worry about breaking the computerthe worst that could happen is that python responds with an error message professional software developers get error messages while writing code all the time
2,493
remember that expressions are just values combined with operatorsand they always evaluate down to single value data type is category for valuesand every value belongs to exactly one data type the most common data types in python are listed in table - the values - and for exampleare said to be integer values the integer (or intdata type indicates values that are whole numbers numbers with decimal pointsuch as are called floating-point numbers (or floatsnote that even though the value is an integerthe value would be floating-point number table - common data types data type examples integers - - floating-point numbers - - - strings ' ''aa''aaa''hello!'' catspython programs can also have text values called stringsor strs (pronounced "stirs"always surround your string in single quote ('characters (as in 'helloor 'goodbye cruel world!'so python knows where the string begins and ends you can even have string with no characters in it''called blank string or an empty string strings are explained in greater detail in if you ever see the error message syntaxerroreol while scanning string literalyou probably forgot the final single quote character at the end of the stringsuch as in this example'helloworldsyntaxerroreol while scanning string literal string concatenation and replication the meaning of an operator may change based on the data types of the values next to it for exampleis the addition operator when it operates on two integers or floating-point values howeverwhen is used on two string valuesit joins the strings as the string concatenation operator enter the following into the interactive shell'alice'bob'alicebobpython basics
2,494
string and an integer valuepython will not know how to handle thisand it will display an error message 'alice traceback (most recent call last)file ""line in 'alice typeerrorcan only concatenate str (not "int"to str the error message can only concatenate str (not "int"to str means that python thought you were trying to concatenate an integer to the string 'aliceyour code will have to explicitly convert the integer to string because python cannot do this automatically (converting data types will be explained in "dissecting your programon page when we talk about the str()int()and float(functions the operator multiplies two integer or floating-point values but when the operator is used on one string value and one integer valueit becomes the string replication operator enter string multiplied by number into the interactive shell to see this in action 'alice 'alicealicealicealicealicethe expression evaluates down to single string value that repeats the original string number of times equal to the integer value string replication is useful trickbut it' not used as often as string concatenation the operator can be used with only two numeric values (for multiplication)or one string value and one integer value (for string replicationotherwisepython will just display an error messagelike the following'alice'bobtraceback (most recent call last)file ""line in 'alice'bobtypeerrorcan' multiply sequence by non-int of type 'str'alice traceback (most recent call last)file ""line in 'alice typeerrorcan' multiply sequence by non-int of type 'floatit makes sense that python wouldn' understand these expressionsyou can' multiply two wordsand it' hard to replicate an arbitrary string fractional number of times
2,495
variable is like box in the computer' memory where you can store single value if you want to use the result of an evaluated expression later in your programyou can save it inside variable assignment statements you'll store values in variables with an assignment statement an assignment statement consists of variable namean equal sign (called the assignment operator)and the value to be stored if you enter the assignment statement spam then variable named spam will have the integer value stored in it think of variable as labeled box that value is placed inas in figure - figure - spam is like telling the program"the variable spam now has the integer value in it for exampleenter the following into the interactive shellspam spam eggs spam eggs spam eggs spam spam spam spam python basics
2,496
after thatyou can use it in expressions with other variables and values when variable is assigned new value the old value is forgottenwhich is why spam evaluated to instead of at the end of the example this is called overwriting the variable enter the following code into the interactive shell to try overwriting stringspam 'hellospam 'hellospam 'goodbyespam 'goodbyejust like the box in figure - the spam variable in this example stores 'hellountil you replace the string with 'goodbyefigure - when new value is assigned to variablethe old one is forgotten variable names good variable name describes the data it contains imagine that you moved to new house and labeled all of your moving boxes as stuff you' never find anythingmost of this book' examples (and python' documentationuse generic variable names like spameggsand baconwhich come from the monty python "spamsketch but in your programsa descriptive name will help make your code more readable
2,497
have some naming restrictions table - has examples of legal variable names you can name variable anything as long as it obeys the following three rulesit can be only one word with no spaces it can use only lettersnumbersand the underscore (_character it can' begin with number table - valid and invalid variable names valid variable names invalid variable names current_balance current-balance (hyphens are not allowedcurrentbalance current balance (spaces are not allowedaccount account (can' begin with number_ (can' begin with numbertotal_sum total_$um (special characters like are not allowedhello 'hello(special characters like are not allowedvariable names are case-sensitivemeaning that spamspamspamand spam are four different variables though spam is valid variable you can use in programit is python convention to start your variables with lowercase letter this book uses camelcase for variable names instead of underscoresthat isvariables looklikethis instead of looking_like_this some experienced programmers may point out that the official python code stylepep says that underscores should be used unapologetically prefer camelcase and point to the " foolish consistency is the hobgoblin of little mindssection in pep itselfconsistency with the style guide is important but most importantlyknow when to be inconsistent--sometimes the style guide just doesn' apply when in doubtuse your best judgment your first program while the interactive shell is good for running python instructions one at timeto write entire python programsyou'll type the instructions into the file editor the file editor is similar to text editors such as notepad or textmatebut it has some features specifically for entering source code to open new file in muclick the new button on the top row the window that appears should contain cursor awaiting your inputbut it' different from the interactive shellwhich runs python instructions python basics
2,498
the interactive shell window will always be the one with the prompt the file editor window will not have the prompt now it' time to create your first programwhen the file editor window opensenter the following into itthis program says hello and asks for my name print('helloworld!'print('what is your name?'ask for their name myname input(print('it is good to meet youmynameprint('the length of your name is:'print(len(myname)print('what is your age?'ask for their age myage input(print('you will be str(int(myage in year 'once you've entered your source codesave it so that you won' have to retype it each time you start mu click the save buttonenter hello py in the file name fieldand then click save you should save your programs every once in while as you type them that wayif the computer crashes or you accidentally exit muyou won' lose the code as shortcutyou can press ctrl- on windows and linux or - on macos to save your file once you've savedlet' run our program press the key your program should run in the interactive shell window rememberyou have to press from the file editor windownot the interactive shell window enter your name when your program asks for it the program' output in the interactive shell should look something like thispython (vb :eb may : : [msc bit (amd )on win type "copyright""creditsor "license()for more information ===============================restart ===============================helloworldwhat is your nameal it is good to meet youal the length of your name is what is your age you will be in year
2,499
terminatesthat isit stops running (you can also say that the python program exits you can close the file editor by clicking the at the top of the window to reload saved programselect file open from the menu do that nowand in the window that appearschoose hello py and click the open button your previously saved hello py program should open in the file editor window you can view the execution of program using the python tutor visualization tool at particular program at to move through each step of the program' execution you'll be able to see how the variablesvalues and the output change dissecting your program with your new program open in the file editorlet' take quick tour of the python instructions it uses by looking at what each line of code does comments the following line is called comment this program says hello and asks for my name python ignores commentsand you can use them to write notes or remind yourself what the code is trying to do any text for the rest of the line following hash mark (#is part of comment sometimesprogrammers will put in front of line of code to temporarily remove it while testing program this is called commenting out codeand it can be useful when you're trying to figure out why program isn' working you can remove the later when you are ready to put the line back in python also ignores the blank line after the comment you can add as many blank lines to your program as you want this can make your code easier to readlike paragraphs in book the print(function the print(function displays the string value inside its parentheses on the screen print('helloworld!'print('what is your name?'ask for their name the line print('helloworld!'means "print out the text in the string 'helloworld!when python executes this lineyou say that python is calling the print(function and the string value is being passed to the function value that is passed to function call is an argument notice that python basics