id
int64
0
25.6k
text
stringlengths
0
4.59k
9,500
understanding the need for multiple number types lot of new developers (and even some older oneshave hard time understanding why there is need for more than one numeric type after allhumans can use just one kind of number to understand the need for multiple number typesyou have to understand little about how computer works with numbers an integer is stored in the computer as simply series of bits that the computer reads directly value of in binary equates to value of in decimal on the other handnumbers that have decimal points are stored in an entirely different manner think back to all those classes you slept through on exponents in school -they actu ally come in handy sometimes floating-point number is stored as sign bit (plus or minus)mantissa (the fractional part of the number)and exponent (the power of (some texts use the term significand in place of mantissa -the terms are interchangeable to obtain the floating-point valueyou use the equationvalue mantissa ^exponent at one timecomputers all used different floating-point representationsbut they all use the ieee- standard now you can read about this standard at ieee org/groups/ full explana tion of precisely how floating-point numbers work is outside the scope of this bookbut you can read fairly understandable descrip tion at com/tutorial/floating_pointunderstanding_floating_point_ representation html nothing helps you understand concept like playing with the values you can find really interesting float ing-point number converter at -schmidt net/floatconverterieee htmlwhere you can click the individual bits (to turn them off or onand see the floating-point number that results as you might imaginefloating-point num bers tend to consume more space in memory because of their complexity in additionthey use an entirely different area of the processor -one that works more slowly than the part used for integer math finallyintegers are preciseas contrasted to floating-point numberswhich can' precisely represent some numbersso you get an approximation instead howeverfloatingpoint variables can store much larger numbers the bottom line is that decimals are unavoid able in the real worldso you need floating-point numbersbut using integers when you can reduces the amount of memory your application consumes and helps it work faster there are many trade-offs in computer systemsand this one is unavoidable understanding boolean values it may seem amazingbut computers always give you straight answera computer will never provide "maybeas output every answer you get is either true or false in factthere is an entire branch of mathematics called boolean algebra that was originally defined by george boole ( super-geek of his timethat computers rely upon to make decisions contrary to common beliefboolean algebra has existed since -long before the time of computers
9,501
part iitalking the talk determining variable' type sometimes you might want to know the vari able type perhaps the type isn' obvious from the code or you've received the information from source whose code isn' accessible whenever you want to see the type of vari ableuse the type(method for exampleif you start by placing value of in myint by typing myint and pressing enteryou can find the type of myint by typing type(myintand pressing enter the output will be <class 'int'>which means that myint contains an int value when using boolean value in pythonyou rely on the bool type variable of this type can contain only two valuestrue or false you can assign value by using the true or false keywordsor you can create an expression that defines logical idea that equates to true or false for exampleyou could saymybool which would equate to false because is most definitely not greater than you see the bool type used extensively in the bookso don' worry about understanding this concept right now understanding strings of all the data typesstrings are the most easily understood by humans and not understood at all by computers if you have read the previous in this bookyou have already seen strings used quite for exampleall the example code in relies on strings string is simply any grouping of characters you place within double quotes for examplemystring "python is great language assigns string of characters to mystring the computer doesn' see letters at all every letter you use is represented by number in memory for examplethe letter is actually the number to see this for yourselftype ord(" "at the python prompt and press enter you see as output it' possible to convert any single letter to its numeric equivalent using the ord(command because the computer doesn' really understand stringsbut strings are so useful in writing applicationsyou sometimes need to convert string to number you can use the int(and float(commands to perform this conversion for exampleif you type myint int(" "and press enter at the python promptyou create an int named myint that contains the value figure - shows how you can perform this task and validate the content and type of myint
9,502
figure - converting string to number is easy using the int(and float(commands you can convert numbers to string as well by using the str(command for exampleif you type mystr str( and press enteryou create string containing the value " and assign it to mystr figure - shows this type of conversion and the test you can perform on it the point is that you can go back and forth between strings and numbers with great ease later demonstrate how these conversions make lot of seemingly impossible tasks quite doable figure - it' possible to convert numbers to strings as well working with dates and times dates and times are items that most people work with quite bit society bases almost everything on the date and time that task needs to be or was completed we make appointments and plan events for specific dates and times most of our day revolves around the clock because of the timeoriented nature of humansit' good idea to look at how python deals with interacting with dates and time (especially storing these values for later useas with everything elsecomputers understand only numbers -the date and time don' really exist to work with dates and timesyou need to perform special task in python when writing computer bookschicken-and-egg scenarios always ariseand this is one of them to use dates and timesyou must issue special import
9,503
part iitalking the talk datetime command technicallythis act is called importing moduleand you learn more about it in don' worry how the command works right now -just use it whenever you want to do something with date and time computers do have clocks inside thembut the clocks are for the humans using the computer yessome software also depends on the clockbut againthe emphasis is on human needs rather than anything the computer might require to get the current timeyou can simply type datetime datetime nowand press enter you see the full date and time information as found on your computer' clock (see figure - figure - get the cur rent date and time using the now(command you may have noticed that the date and time are little hard to read in the existing format say that you want to get just the current datein readable format it' time to combine few things you discovered in previous sections to accomplish that task type str(datetime datetime nowdate)and press enter figure - shows that you now have something little more usable figure - make the date and time more readable using the str(command interestingly enoughpython also has time(commandwhich you can use to obtain the current time you can obtain separate values for each of the components that make up date and time using the daymonthyearhourminutesecondand microsecond values later help you understand how to use these various date and time features to keep application users informed about the current date and time on their system
9,504
managing information in this understanding the python view of data using operators to assignmodifyand compare data organizing code using functions interacting with the user hether you use the term information or data to refer to the content that applications managethe fact is that you must provide some means of working with it or your application really doesn' have purpose throughout the rest of the bookyou see information and data used interchangeably because they really are the same thingand in real-world situationsyou'll encounter them bothso getting used to both is good idea no matter which term you useyou need some means of assigning data to variablesmodifying the content of those variables to achieve specific goalsand comparing the result you receive with desired results this addresses all three requirements so that you can start to control data within your applications it' also essential to start working through methods of keeping your code understandable yesyou could write your application as really long procedurebut trying to understand such procedure is incredibly hardand you' find yourself repeating some steps because they must be done more than once functions are one way for you to package code so that it' easier to understand and reuse as needed applications also need to interact with the user yessome perfectly usable applications are out there that don' really interact with the userbut they're extremely rare and don' really do muchfor the most part in order to provide useful servicemost applications interact with the user to discover how the user wants to manage data you get an overview of this process in this of courseyou visit the topic of user interaction quite often throughout the book because it' an important topic
9,505
part iitalking the talk controlling how python views data as discussed in all data on your computer is stored as and the computer doesn' understand the concept of lettersboolean valuesdatestimesor any other kind of information except numbers in additiona computer' capability to work with numbers is both inflexible and relatively simplistic when you work with string in pythonyou're depending on python to translate the concept of string into form the computer can understand the storage containers that your application creates and uses in the form of variables tell python how to treat the and that the computer has stored soit' important to understand that the python view of data isn' the same as your view of data or the computer' view of data -python acts as an intermediary to make your applications functional to manage data within an applicationthe application must control the way in which python views the data the use of operatorspackaging methods such as functionsand the introduction of user input all help applications control data all these techniques relyin parton making comparisons determining what to do next means understanding what state the data is in now as compared to some other state if the variable contains the name john nowbut you really want it to contain mary insteadthen you first need to know that it does in fact contain john only then can you make the decision to change the content of the variable to mary making comparisons python' main method for making comparisons is through the use of operators in factoperators play major role in manipulating data as well the upcoming "working with operatorssection discusses how operators work and how you can use them in applications to control data in various ways later use operators extensively as you discover techniques for creating applications that can make decisionsperform tasks repetitivelyand interact with the user in interesting ways howeverthe basic idea behind operators is that they help applications perform various types of comparisons in some casesyou use some fancy methods for performing comparisons in an application for exampleyou can compare the output of two functions (as described in the "comparing function outputsectionlater in this with pythonyou can perform comparisons at number of levels so that you can manage data without problem in your application using these techniques hides detail so that you can focus on the point of the comparison and define how to react to that comparison rather than become mired in detail
9,506
your choice of techniques for performing comparisons affects the manner in which python views the data and determines the sorts of things you can do to manage the data after the comparison is made all this functionality might seem absurdly complex at the momentbut the important point to remember is that applications require comparisons in order to interact with data correctly understanding how computers make comparisons computers don' understand packagingsuch as functionsor any of the other structures that you create with python all this packaging is for your benefitnot the computer' howevercomputers do directly support the concept of operators most python operators have direct corollary with command that the computer understands directly for examplewhen you ask whether one number is greater than another numberthe computer can actually perform this computation directlyusing an operator (the upcoming section explains operators in detail some comparisons aren' direct computers work only with numbers sowhen you ask python to compare two stringswhat python actually does is compare the numeric value of each character in the string for examplethe letter is actually the number in the computer lowercase letter has different numeric value - as resulteven though you might see abc as being equal to abcthe computer doesn' agree -it sees them as different because the numeric values of their individual letters are different working with operators operators are the basis for both control and management of data within applications you use operators to define how one piece of data is compared to another and to modify the information within single variable in factoperators are essential to performing any sort of math-related task and to assigning data to variables in the first place when using an operatoryou must supply either variable or an expression you already know that variable is kind of storage box used to hold data an expression is an equation or formula that provides description of mathematical concept in most casesthe result of evaluating an expression is boolean (true or falsevalue the following sections describe operators in detail because you use them everywhere throughout the rest of the book
9,507
part iitalking the talk understanding python' one ternary operator ternary operator requires three elements python supports just one such operatorand you use it to determine the truth value of an expression this operator takes the following formtruevalue if expression else falsevalue when the expression is truethe operator outputs truevalue when the expression is falseit outputs falsevalue as an exampleif you type "helloif true else "goodbyethe operator outputs response of 'hellohoweverif you type "helloif false else "goodbyethe operator outputs response of 'goodbyethis is handy operator for times when you need to make quick decision and don' want to write lot of code to do it one of the advantages of using python is that it normally has more than one way to do things python has an alternative form of this ternary operator -an even shorter shortcut it takes the following form(falsevaluetruevalue[expressionas beforewhen expression is truethe oper ator outputs truevalueotherwiseit outputs falsevalue notice that the truevalue and falsevalue elements are reversed in this case an example of this version is ("hello""goodbye")[truein this casethe output of the operator is 'goodbyebecause that' the value in the truevalue position of the two formsthe first is little clearerwhile the second is shorter defining the operators an operator accepts one or more inputs in the form of variables or expressionsperforms task (such as comparison or addition)and then provides an output consistent with that task operators are classified partially by their effect and partially by the number of elements they require for examplea unary operator works with single variable or expressiona binary operator requires two the elements provided as input to an operator are called operands the operand on the left side of the operator is called the left operandwhile the operand on the right side of the operator is called the right operand the following list shows the categories of operators that you use within pythonunary arithmetic relational
9,508
logical bitwise assignment membership identity each of these categories performs specific task for examplethe arithmetic operators perform math-based taskswhile relational operators perform comparisons the following sections describe the operators based on the category in which they appear unary unary operators require single variable or expression as input you often use these operators as part of decision-making process for exampleyou might want to find something that isn' like something else table - shows the unary operators table - python unary operators operator description example inverts the bits in number so that all the bits become bits and vice versa ~ results in value of - negates the original value so that positive becomes negative and vice versa -(- results in and - results in - is provided purely for the sake of completeness this operator returns the same value that you provide as input + results in value of arithmetic computers are known for their capability to perform complex math howeverthe complex tasks that computers perform are often based on much simpler math taskssuch as addition python provides access to libraries that help you perform complex math tasksbut you can always create your own libraries of math functions using the simple operators found in table -
9,509
part iitalking the talk table - python arithmetic operators operator description example adds two values together + = subtracts the right operand from the left operand - = multiplies the right operand by the left operand divides the left operand by the right operand divides the left operand by the right operand and returns the remainder % = *calculates the exponential value of the right operand by the left operand * /performs integer divisionin which the left operand is divided by the right operand and only the whole number is returned (also called floor division / relational the relational operators compare one value to another and tell you when the relationship you've provided is true for example is less than but is never greater than the truth value of relations is often used to make decisions in your applications to ensure that the condition for performing specific task is met table - describes the relational operators table - python relational operators operator description example =determines whether two values are equal notice that the relational operator uses two equals signs mistake many developers make is using just one equals signwhich results in one value being assigned to another = is false !determines whether two values are not equal some older versions of python allowed you to use the oper ator in place of the !operator using the operator results in an error in current versions of python ! is true verifies that the left operand value is greater than the right operand value is false
9,510
operator description example verifies that the left operand value is less than the right operand value is true >verifies that the left operand value is greater than or equal to the right operand value > is false <verifies that the left operand value is less than or equal to the right operand value < is true logical the logical operators combine the true or false value of variables or expressions so that you can determine their resultant truth value you use the logical operators to create boolean expressions that help determine whether to perform tasks table - describes the logical operators table - python logical operators operator description example and determines whether both operands are true true and true is true true and false is false false and true is false false and false is false or determines when one of two operands is true true or true is true true or false is true false or true is true false or false is false not negates the truth value of single operand true value becomes false and false value becomes true not true is false not false is true bitwise the bitwise operators interact with the individual bits in number for examplethe number is actually in binary
9,511
if your binary is little rustyyou can use the handy binary to decimal to hexadecimal converter at to make the site work bitwise operator would interact with each bit within the number in specific way when working with logical bitwise operatora value of counts as false and value of counts as true table - describes the bitwise operators table - python bitwise operators operator description example (anddetermines whether both individual bits within two operators are true and sets the resulting bit to true when they are (ordetermines whether either of the indi vidual bits within two operators is true and sets the resulting bit to true when one of them is (exclusive ordetermines whether just one of the indi vidual bits within two operators is true and sets the resulting bit to true when one is when both bits are true or both bits are falsethe result is false (one' complementcalculates the one' complement value of number ~ - ~ - <(left shiftshifts the bits in the left operand left by the value of the right operand all new bits are set to and all bits that flow off the end are lost < >(right shiftshifts the bits in the left operand right by the value of the right operand all new bits are set to and all bits that flow off the end are lost >
9,512
assignment the assignment operators place data within variable the simple assignment operator appears in previous of the bookbut python offers number of other interesting assignment operators that you can use these other assignment operators can perform mathematical tasks during the assignment processwhich makes it possible to combine assignment with math operation table - describes the assignment operators for this particular tablethe initial value of myvar in the example column is table - python assignment operators operator description example assigns the value found in the right oper and to the left operand myvar results in myvar containing +adds the value found in the right operand to the value found in the left operand and places the result in the left operand myvar + results in myvar contain ing -subtracts the value found in the right operand from the value found in the left operand and places the result in the left operand myvar - results in myvar contain ing *multiplies the value found in the right oper and by the value found in the left operand and places the result in the left operand myvar * results in myvar contain ing /divides the value found in the left operand by the value found in the right operand and places the result in the left operand myvar / results in myvar contain ing %divides the value found in the left operand by the value found in the right operand and places the remainder in the left operand myvar % results in myvar contain ing **determines the exponential value found in the left operand when raised to the power of the value found in the right operand and places the result in the left operand myvar ** results in myvar contain ing //divides the value found in the left operand by the value found in the right operand and places the integer (whole numberresult in the left operand myvar // results in myvar contain ing
9,513
membership the membership operators detect the appearance of value within list or sequence and then output the truth value of that appearance think of the membership operators as you would search routine for database you enter value that you think should appear in the databaseand the search routine finds it for you or reports that the value doesn' exist in the database table - describes the membership operators table - python membership operators operator description example in determines whether the value in the left operand appears in the sequence found in the right operand "helloin "hello goodbyeis true not in determines whether the value in the left operand is missing from the sequence found in the right operand "hellonot in "hello goodbyeis false identity the identity operators determine whether value or expression is of certain class or type you use identity operators to ensure that you're actually working with the sort of information that you think you are using the identity operators can help you avoid errors in your application or determine the sort of processing value requires table - describes the identity operators table - python identity operators operator description example is evaluates to true when the type of the value or expression in the right operand points to the same type in the left operand type( is int is true is not evaluates to true when the type of the value or expression in the right operand points to differ ent type than the value or expression in the left operand type( is not int is false
9,514
understanding operator precedence when you create simple statements that contain just one operatorthe order of determining the output of that operator is also simple howeverwhen you start working with multiple operatorsit becomes necessary to determine which operator to evaluate first for exampleit' important to know whether evaluates to (where the multiplication is done firstor (where the addition is done firstan order of operator precedence tells you that the answer is unless you use parentheses to override the default order in this case( would evaluate to because the parentheses have higher order of precedence than multiplication does table - defines the order of operator precedence for python table - python operator precedence operator description (you use parentheses to group expressions and to override the default precedence so that you can force an operation of lower precedence (such as additionto take pre cedence over an operation of higher prece dence (such as multiplication*exponentiation raises the value of the left operand to the power of the right operand unary operators interact with single vari able or expression /multiplydividemoduloand floor division addition and subtraction ><right and left bitwise shift bitwise and bitwise exclusive or and standard or >comparison operators =!%///-+***equality operators is identity operators assignment operators is not in membership operators not in not or and logical operators
9,515
creating and using functions to manage information properlyyou need to organize the tools used to perform the required tasks each line of code that you create performs specific taskand you combine these lines of code to achieve desired result sometimes you need to repeat the instructions with different dataand in some cases your code becomes so long that it' hard to keep track of what each part does functions serve as organization tools that keep your code neat and tidy in additionfunctions make it easy to reuse the instructions you've created as needed with different data this section of the tells you all about functions more importantin this section you start creating your first serious applications in the same way that professional developers do viewing functions as code packages you go to your closetopen the doorand everything spills out in factit' an avalancheand you're lucky that you've survived that bowling ball in the top shelf could have done some severe damagehoweveryou're armed with storage boxes and soon you have everything in the closet in neatly organized boxes the shoes go in one boxgames in anotherand old cards and letters in yet another after you're doneyou can find anything you want in the closet without fear of injury functions are just like that -they take messy code and place it in packages that make it easy to see what you have and understand how it works commentaries abound on just what functions are and why they're necessarybut when you boil down all that textit comes down to single ideafunctions provide means of packaging code to make it easy to find and access if you can think of functions as organizersyou find that working with them is much easier for exampleyou can avoid the problem that many developers have of stuffing the wrong items in function all your functions will have single purposejust like those storage boxes in the closet understanding code reusability you go to your closettake out pants and shirtremove the labelsand put them on at the end of the dayyou take everything off and throw it in the trash hmmm that really isn' what most people do most people take the clothes offwash themand then put them back into the closet for reuse functions are reusabletoo no one wants to keep repeating the same taskit becomes monotonous and boring when you create function
9,516
you define package of code that you can use over and over to perform the same task all you need to do is tell the computer to perform specific task by telling it which function to use the computer faithfully executes each instruction in the function absolutely every time you ask it to do so when you work with functionsthe code that needs services from the function is named the callerand it calls upon the function to perform tasks for it much of the information you see about functions refers to the caller the caller must supply information to the functionand the function returns information to the caller at one timecomputer programs didn' include the concept of code reusability as resultdevelopers had to keep reinventing the same code it didn' take long for someone to come up with the idea of functionsthoughand the concept has evolved over the years until functions have become quite flexible you can make functions do anything you want code reusability is necessary part of applications to reduce development time reduce programmer error increase application reliability allow entire groups to benefit from the work of one programmer make code easier to understand improve application efficiency in factfunctions do whole list of things for applications in the form of reusability as you work through the examples in this bookyou see how reusability makes your life significantly easier if not for reusabilityyou' still be programming by plugging and into the computer by hand defining function creating function doesn' require much work python tends to make things fast and easy for you the following steps show you the process of creating function that you can later access open python shell window you see the familiar python prompt type def hello()and press enter
9,517
this step tells python to define function named hello the parentheses are important because they define any requirements for using the function (there aren' any requirements in this case the colon at the end tells python that you're done defining the way in which people will access the function notice that the insertion pointer is now indentedas shown in figure - this indentation is reminder that you must give the function task to perform figure - define the name of your function type print("this is my first python function!"and press enter you should notice two thingsas shown in figure - firstthe insertion pointer is still indented because idle is waiting for you to provide the next step in the function secondpython hasn' executed the print(function because it' part of function and is not in the main part of the window figure - idle is waiting for your next instruction press enter the function is now complete you can tell because the insertion point is now to the left sideas shown in figure - in additionthe python prompt (has returned
9,518
figure - the function is completeand idle waits for you to pro vide another instruction even though this is really simple functionit demonstrates the pattern you use when creating any python function you define nameprovide any requirements for using the function (none in this case)and provide series of steps for using the function function ends when an extra line is added (you press enter twiceworking with functions in the edit window is the same as working with them in the python shell windowexcept that you can save the edit window content to disk this example also appears with the downloadable source code as firstfunction py try loading the file into an edit window using the same technique you use in the "using the edit windowsection of accessing functions after you define functionyou probably want to use it to perform useful work of coursethis means knowing how to access the function in the previous sectionyou create new function named hello(to access this functionyou type helloand press enter figure - shows the output you see when you execute this function figure - whenever you type the func tion' nameyou get the output the function provides
9,519
every function you create will provide similar pattern of usage you type the function namean open parenthesisany required inputand close parenthesisthen you press enter in this caseyou have no inputso all you type is helloas the progressesyou see other examples for which input is required sending information to functions the firstfunction py example is nice because you don' have to keep typing that long string every time you want to say hello(howeverit' also quite limited because you can use it to say only one thing functions should be flexible and allow you to do more than just one thing otherwiseyou end up writing lot of functions that vary by the data they use rather than the functionality they provide using arguments helps you create functions that are flexible and can use wealth of data understanding arguments the term argument doesn' mean that you're going to have fight with the functionit means that you supply information to the function to use in processing request perhaps better word for it would be inputbut the term input has been used for so many other purposes that developers decided to use something bit differentargument although the purpose of an argument might not be clear from its nameunderstanding what it does is relatively straightforward an argument makes it possible for you to send data to the function so that the function can use it when performing task using arguments makes your function more flexible the hello(function is currently inflexible because it prints just one string adding an argument to the function can make it lot more flexible because you can send strings to the function to say anything you want to see how arguments workcreate new function in the python shell window (or open the arguments py file of the downloadable sourcesee the introduction for the urlthis version of hello()hello ()requires an argumentdef hello greeting )print(greetingnotice that the parentheses are no longer empty they contain wordgreetingwhich is the argument for hello (the greeting argument is actually variable that you can pass to print(in order to see it onscreen sending required arguments you have new functionhello (this function requires that you provide an argument to use it at leastthat' what you've heard so far type hello and press enter in the python shell window you see an error messageas shown in figure - telling you that hello (requires an argument
9,520
figure - you must supply an argument or you get an error message not only does python tell you that the argument is missingit tells you the name of the argument as well creating function the way you have done so far means that you must supply an argument type hello ("this is an interesting function "and press enter this timeyou see the expected output howeveryou still don' know whether hello (is flexible enough to print multiple messages type hello ("another message "and press enter you see the expected output againas shown in figure - so hello (is indeed an improvement over hello(figure - use hello (to print any message you desire
9,521
you might easily to assume that greeting will accept only string from the tests you have performed so far type hello ( )press enterand you see as the output likewisetype hello ( and press enter this time you see the result of the expressionwhich is sending arguments by keyword as your functions become more complex and the methods to use them do as wellyou may want to provide little more control over precisely how you call the function and provide arguments to it up until nowyou have positional argumentswhich means that you have supplied values in the order in which they appear in the argument list for the function definition howeverpython also has method for sending arguments by keyword in this caseyou supply the name of the argument followed by an equals sign (=and the argument value to see how this worksopen python shell window and type the following function (which is also found in the arguments py file)def addit(value value )print(value "value "(value value )notice that the print(function argument includes list of items to print and that those items are separated by commas in additionthe arguments are of different types python makes it easy to mix and match arguments in this manner time to test addit(of courseyou want to try the function using positional arguments firstso type addit( and press enter you see the expected output of now type addit(value value and press enter againyou receive the output even though the position of the arguments has been reversed giving function arguments default value whether you make the call using positional arguments or keyword argumentsthe functions to this point have required that you supply value sometimes function can use default values when common value is available default values make the function easier to use and less likely to cause errors when developer doesn' provide an input to create default valueyou simply follow the argument name with an equals sign and the default value to see how this worksopen python shell window and type the following function (which you can also find in the arguments py file)def hello (greeting "no value supplied")print(greeting
9,522
this is yet another version of the original hello(and updated hello (functionsbut hello (automatically compensates for individuals who don' supply value when someone tries to call hello (without an argumentit doesn' raise an error type hello and press enter to see for yourself type hello ("this is string "to see normal response lest you think the function is now unable to use other kinds of datatype hello ( and press enterthen hello ( and press enter figure - shows the output from all these tests figure - supply default arguments when possi ble to make your func tions easier to use creating functions with variable number of arguments in most casesyou know precisely how many arguments to provide with your function it pays to work toward this goal whenever you can because functions with fixed number of arguments are easier to troubleshoot later howeversometimes you simply can' determine how many arguments the function will receive at the outset for examplewhen you create python application that works at the command linethe user might provide no argumentsthe maximum number of arguments (assuming there is one)or any number of arguments in between fortunatelypython provides technique for sending variable number of arguments to function you simply create an argument that has an asterisk in front of itsuch as *varargs the usual technique is to provide second argument that contains the number of arguments passed as an input here is an example (also found in the varargs py fileof function that can print variable number of elements (don' worry too much if you don' understand it completely now -you haven' seen some of these techniques used before
9,523
def hello (argcount*varargs)print("you passed "argcountarguments "for arg in varargsprint(argthis example uses something called for loop you meet this structure in for nowall you really need to know is that it takes the arguments out of varargs one at timeplaces the individual argument into argand then prints arg using print(what should interest you most is seeing how variable number of arguments can work after you type the function into new python shell windowtype hello ( " test string "and press enter you should see the number of arguments and the test string as output -nothing too exiting there howevernow type hello ( "one""two""three"and press enter as shown in figure - the function handles the variable number of arguments without any problem at all figure - variable argument func tions can make your applica tions more flexible returning information from functions functions can display data directly or they can return the data to the caller so that the caller can do something more with it in some casesa function displays data directly as well as returns data to the callerbut it' more common for function to either display the data directly or to return it to the caller
9,524
just how functions work depends on the kind of task the function is supposed to perform for examplea function that performs math-related task is more likely to return the data to the caller than certain other functions to return data to callera function needs to include the keyword returnfollowed by the data to return you have no limit on what you can return to caller here are some types of data that you commonly see returned by function to callervaluesany value is acceptable you can return numberssuch as or stringssuch as "hello there!"or boolean valuessuch as true or false variablesthe content of any variable works just as well as direct value the caller receives whatever data is stored in the variable expressionsmany developers use expressions as shortcut for exampleyou can simply return rather than perform the calculationplace the result in variableand then return the variable to the caller using the expression is faster and accomplishes the same task results from other functionsyou can actually return data from another function as part of the return of your function it' time to see how return values work open python shell window and type the following code (or open the returnvalue py file instead)def doadd(value value )return value value this function accepts two values as input and then returns the sum of those two values yesyou could probably perform this task without using functionbut this is how many functions start to test this functiontype print("the sum of is "doadd( )and press enter you see the expected output shown in figure - figure - return values can make your functions even more useful
9,525
comparing function output you use functions with return values in number of ways for examplethe previous section of this shows how you can use functions to provide input for another function you use functions to perform all sorts of tasks one of the ways to use functions is for comparison purposes you can actually create expressions from them that define logical output to see how this might workuse the doadd(function from the previous section type print(" equals is "(doadd( =doadd( ))and press enter you see the truth value of the statement that equals as shown in figure - the point is that functions need not provide just one use or that you view them in just one way functions can make your code quite versatile and flexible figure - use your functions to perform wide variety of tasks getting user input very few applications exist in their own world -that isapart from the user in factmost applications interact with users in major way because computers are designed to serve user needs to interact with useran application must provide some means of obtaining user input fortunatelythe most commonly used technique for obtaining input is also relatively easy to implement you simply use the input(function to do it
9,526
the input(function always outputs string even if user types numberthe output from the input(function is string this means that if you are expecting numberyou need to convert it after receiving the input the input(function also lets you provide string prompt this prompt is displayed to tell the user what to provide in the way of information the input py file contains an example of using the input(function in simple way here' the code for that examplename input("tell me your name"print("hello "namein this casethe input(function asks the user for name after the user types name and presses enterthe example outputs customized greeting to the user try running this example at the command prompt or the python shell window figure - shows typical results when you input john as the username figure - provide username and see greeting as output you can use input(for other kinds of dataall you need is the correct conversion function for examplethe code in the input py file provides one technique for performing such conversionas shown hereanumber float(input("type number")print("you typed"anumberwhen you run this examplethe application asks for numeric input the call to float(converts the input to number after the conversionprint(outputs the result when you run the example using value such as you obtain the desired result
9,527
it' important to understand that data conversion isn' without risk if you attempt to type something other than numberyou get an error messageas shown in figure - helps you understand how to detect and fix errors before they cause system crash figure - data con version changes the input type to whatever you needbut could cause errors
9,528
making decisions in this using the if statement to make simple decisions performing more advanced decision making with the if else statement creating multiple decision levels by nesting statements he ability to make decisionto take one path or anotheris an essential element of performing useful work math gives the computer the capability to obtain useful information decisions make it possible to do something with the information after it' obtained without the capability to make decisionsa computer would be useless so any language you use will include the capability to make decisions in some manner this explores the techniques that python uses to make decisions think through the process you use when making decision you obtain the actual value of somethingcompare it to desired valueand then act accordingly for examplewhen you see signal light and see that it' redyou compare the red light to the desired green lightdecide that the light isn' greenand then stop most people don' take time to consider the process they use because they use it so many times every day decision making comes naturally to humansbut computers must perform the following tasks every time obtain the actual or current value of something compare the actual or current value to desired value perform an action that corresponds to the desired outcome of the comparison
9,529
making simple decisions using the if statement the if statement is the easiest method for making decision in python it simply states that if something is truepython should perform the steps that follow the following sections tell you how you can use the if statement to make decisions of various sorts in python you may be surprised at what this simple statement can do for you understanding the if statement you use if statements regularly in everyday life for exampleyou may say to yourself"if it' wednesdayi'll eat tuna salad for lunch the python if statement is little less verbosebut it follows precisely the same pattern say you create variabletestmeand place value of in itlike thistestme you can then ask the computer to check for value of in testmelike thisif testme = print("testme does equal !"every python if statement beginsoddly enoughwith the word if when python sees ifit knows that you want it to make decision after the word if comes condition condition simply states what sort of comparison you want python to make in this caseyou want python to determine whether testme contains the value notice that the condition uses the relational equality operator==and not the assignment operatora common mistake that developers make is to use the assignment operator rather than the equality operator you can see list of relational operators in the condition always ends with colon (:if you don' provide colonpython doesn' know that the condition has ended and will continue to look for additional conditions on which to base its decision after the colon come any tasks you want python to perform in this casepython prints statement saying that testme is equal to
9,530
using the if statement in an application it' possible to use the if statement in number of ways in python howeveryou immediately need to know about three common ways to use ituse single condition to execute single statement when the condition is true use single condition to execute multiple statements when the condition is true combine multiple conditions into single decision and execute one or more statements when the combined condition is true the following sections explore these three possibilities and provide you with examples of their use you see additional examples of how to use the if statement throughout the book because it' such an important method of making decisions working with relational operators relational operator determines how value on the left side of an expression compares to the value on the right side of an expression after it makes the determinationit outputs value of true or false that reflects the truth value of the expression for example = is truewhile = is false table - contains listing of the relational operators the following steps show how to create and use an if statement this example also appears with the downloadable source code as simpleif py open python shell window you see the familiar python prompt type testme and press enter this step assigns value of to testme notice that it uses the assignment operator and not the equality operator type if testme = and press enter this step creates an if statement that tests the value of testme using the equality operator you should notice two features of the python shell at this pointthe word if is highlighted in different color than the rest of the statement the next line is automatically indented
9,531
type print("testme does equal !"and press enter notice that python doesn' execute the if statement yet it does indent the next line the word print appears in special color because it' function name in additionthe text appears in another color to show you that it' string value color coding makes it much easier to see how python works press enter the python shell outdents this next line and executes the if statementas shown in figure - notice that the output is in yet another color because testme contains value of the if statement works as expected figure - simple if statements can help your appli cation know what to do in certain conditions performing multiple tasks sometimes you want to perform more than one task after making decision python relies on indentation to determine when to stop executing tasks as part of an if statement as long as the next line is indentedit' part of the if statement when the next line is outdentedit becomes the first line of code outside the if block code block consists of statement and the tasks associated with that statement the same term is used no matter what kind of statement you're working withbut in this caseyou're working with an if statement that is part of code block this example also appears with the downloadable source code as simpleif py open python shell window you see the familiar python prompt type the following code into the window -pressing enter after each linetestme if testme = print("testme does equal !"print("all done!"
9,532
notice that the shell continues to indent lines as long as you continue to type code each line you type is part of the current if statement code block when working in the shellyou create block by typing one line of code after another if you press enter twice in row without entering any textthe code block is endedand python executes the entire code block at one time press enter python executes the entire code block you see the output shown in figure - figure - code block can contain mul tiple lines of code -one for each task making multiple comparisons using logical operators so farthe examples have all shown single comparison real life often requires that you make multiple comparisons to account for multiple requirements for examplewhen baking cookiesif the timer has gone off and the edges are brownit' time to take the cookies out of the oven in order to make multiple comparisonsyou create multiple conditions using relational operators and combine them using logical operators (see table - logical operator describes how to combine conditions for exampleyou might say = and = as two conditions for performing one or more tasks the and keyword is logical operator that states that both conditions must be true one of the most common uses for making multiple comparisons to determine when value is within certain range in factrange checkingthe act of determining whether data is between two valuesis an important part of making your application secure and user friendly the following steps help
9,533
you see how to perform this task in this caseyou create file so that you can run the application multiple times this example also appears with the downloadable source code as simpleif py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linevalue int(input("type number between and ")if (value and (value < )print("you typed"valuethe example begins by obtaining an input value you have no idea what the user has typed other than that it' value of some sort the use of the int(function means that the user must type whole number (one without decimal portionotherwisethe application will raise an exception (an error indication describes exceptionsthis first check ensures that the input is at least of the correct type the if statement contains two conditions the first states that value must be greater than you could also present this condition as value > the second condition states that value must be less than or equal to only when value meets both of these conditions will the if statement succeed and print the value the user typed choose runrun module you see python shell window open with prompt to type number between and type and press enter the application determines that the number is in the right range and outputs the message shown in figure - repeat steps and but type instead of the application doesn' output anything because the number is in the wrong range whenever you type value that' outside the programmed rangethe statements that are part of the if block aren' executed repeat steps and but type instead of python displays the error message shown in figure - even though you may think of and as both being numberspython sees the first number as floating-point value and the second as an integer
9,534
repeat steps and but type hello instead of python displays about the same error message as before python doesn' differentiate between types of wrong input it only knows that the input type is incorrect and therefore unusable figure - the applica tion verifies the value is in the right range and outputs message figure - typing the wrong type of informa tion results in an error message the best applications use various kinds of range checking to ensure that the application behaves in predictable manner the more predictable an application becomesthe less the user thinks about the application and the more time the user spends on performing useful work productive users tend to be lot happier than those who constantly fight with their applications
9,535
choosing alternatives using the if else statement many of the decisions you make in an application fall into category of choosing one of two options based on conditions for examplewhen looking at signal lightyou choose one of two optionspress on the brake to stop or press the accelerator to continue the option you choose depends on the conditions green light signals that you can continue on through the lighta red light tells you to stop the following sections describe how python makes it possible to choose between two alternatives understanding the if else statement with pythonyou choose one of two alternatives using the else clause of the if statement clause is an addition to code block that modifies the way in which it works most code blocks support multiple clauses in this casethe else clause enables you to perform an alternative taskwhich increases the usefulness of the if statement most developers refer to the form of the if statement that has the else clause included as the if else statementwith the ellipsis implying that something happens between if and else sometimes developers encounter problems with the if else statement because they forget that the else clause always executes when the conditions for the if statement aren' met it' important to think about the consequences of always executing set of tasks when the conditions are false sometimes doing so can lead to unintended consequences using the if else statement in an application the simpleif py example is little less helpful than it could be when the user enters value that' outside the intended range even entering data of the wrong type produces an error messagebut entering the correct type of data outside the range tells the user nothing in this exampleyou discover the means for correcting this problem by using an else clause the following steps demonstrate just one reason to provide an alternative action when the condition for an if statement is false this example also appears with the downloadable source code as ifelse py
9,536
open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linevalue int(input("type number between and ")if (value and (value < )print("you typed"valueelseprint("the value you typed is incorrect!"as beforethe example obtains input from the user and then determines whether that input is in the correct range howeverin this casethe else clause provides an alternative output message when the user enters data outside the desired range notice that the else clause ends with colonjust as the if statement does most clauses that you use with python statements have colon associated with them so that python knows when the clause has ended if you receive coding error for your applicationmake sure that you check for the presence of the colon as needed choose runrun module you see python shell window open with prompt to type number between and type and press enter the application determines that the number is in the right range and outputs the message shown previously in figure - repeat steps and but type instead of this time the application outputs the error message shown in figure - the user now knows that the input is outside the desired range and knows to try entering it again using the if elif statement in an application you go to restaurant and look at the menu the restaurant offers eggspancakeswafflesand oatmeal for breakfast after you choose one of the itemsthe server brings it to you creating menu selection requires something like an if else statementbut with little extra oomph in this caseyou use the elif clause to create another set of conditions the elif clause is combination of the else clause and separate if statement the following steps describe how to use the if elif statement to create menu this example also appears with the downloadable source code as ifelif py
9,537
figure - it' always good idea to provide feedback for incorrect input open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each lineprint(" red"print(" orange"print(" yellow"print(" green"print(" blue"print(" purple"choice int(input("select your favorite color")if (choice = )print("you chose red!"elif (choice = )print("you chose orange!"elif (choice = )print("you chose yellow!"elif (choice = )print("you chose green!"elif (choice = )print("you chose blue!"elif (choice = )print("you chose purple!"elseprint("you made an invalid choice!"the example begins by displaying menu the user sees list of choices for the application it then asks the user to make selectionwhich it places inside choice the use of the int(function ensures that the user can' type anything other than number
9,538
after the user makes choicethe application looks for it in the list of potential values in each casechoice is compared against particular value to create condition for that value when the user types the application outputs the message "you chose red!if none of the options is correctthe else clause is executed by default to tell the user that the input choice is invalid choose runrun module you see python shell window open with the menu displayed the application asks you to select your favorite color type and press enter the application displays the appropriate output messageas shown in figure - repeat steps and but type instead of the application displays different output message -the one associated with the requested color repeat steps and but type instead of the application tells you that you made an invalid choice repeat steps and but type red instead of the application displays the expected error messageas shown in figure - any application you create should be able to detect errors and incorrect inputs shows you how to handle errors so that they're user friendly figure - menus let you choose one option from list of options
9,539
figure - every application you create should include some means of detecting errant input no switch statementif you've worked with other languagesyou might notice that python lacks switch state ment (if you haven'tthere is no need to worry about it with pythondevelopers commonly use the switch statement in other languages to create menu-based applications the if elif statement is generally used for the same purpose in python howeverthe if elif statement doesn' provide quite the same functionality as switch statement because it doesn' enforce the use of single variable for comparison purposes as resultsome developers rely on python' dic tionary functionality to stand in for the switch statement describes how to work with dictionaries
9,540
using nested decision statements the decision-making process often happens in levels for examplewhen you go to the restaurant and choose eggs for breakfastyou have made first-level decision now the server asks you what type of toast you want with your eggs the server wouldn' ask this question if you had ordered pancakesso the selection of toast becomes second-level decision when the breakfast arrivesyou decide whether you want to use jelly on your toast this is third-level decision if you had selected kind of toast that doesn' work well with jellyyou might not have had to make this decision at all this process of making decisions in levelswith each level reliant on the decision made at the previous levelis called nesting developers often use nesting techniques to create applications that can make complex decisions based on various inputs the following sections describe several kinds of nesting you can use within python to make complex decisions using multiple if or if else statements the most commonly used multiple selection technique is combination of if and if else statements this form of selection is often called selection tree because of its resemblance to the branches of tree in this caseyou follow particular path to obtain desired result the example in this section also appears with the downloadable source code as multipleifelse py open python file window you see an editor where you can type the example code type the following code into the window -pressing enter after each lineone int(input("type number between and ")two int(input("type number between and ")if (one > and (one < )if (two > and (two < )print("your secret number is"one twoelseprint("incorrect second value!"elseprint("incorrect first value!"this is simply an extension of the ifelse py example you see in the "using the if else statement in an applicationsection of the howevernotice that the indentation is different the second if else statement is indented within the first if else statement the indentation tells python that this is second-level statement
9,541
choose runrun module you see python shell window open with prompt to type number between and type and press enter the shell asks for another number between and type and press enter you see the combination of the two numbers as outputas shown in figure - figure - adding mul tiple levels lets you per form tasks with greater complexity this example has the same input features as the ifelse py example for exampleif you attempt to provide value that' outside the requested rangeyou see an error message the error message is tailored for either the first or second input value so that the user knows which value was incorrect providing specific error messages is always useful because users tend to become confused and frustrated otherwise in additiona specific error message helps you find errors in your application much faster combining other types of decisions it' possible to use any combination of ifif elseand if elif statements to produce desired outcome you can nest the code blocks as many levels deep as needed to perform the required checks for examplelisting - shows what you might accomplish for breakfast menu this example also appears with the downloadable source code as multipleifelif py
9,542
listing - creating breakfast menu print(" eggs"print(" pancakes"print(" waffles"print(" oatmeal"mainchoice int(input("choose breakfast item")if (mainchoice = )meal "pancakeselif (mainchoice = )meal "wafflesif (mainchoice = )print(" wheat toast"print(" sour dough"print(" rye toast"print(" pancakes"bread int(input("choose type of bread")if (bread = )print("you chose eggs with wheat toast "elif (bread = )print("you chose eggs with sour dough "elif (bread = )print("you chose eggs with rye toast "elif (bread = )print("you chose eggs with pancakes "elseprint("we have eggsbut not that kind of bread "elif (mainchoice = or (mainchoice = )print(" syrup"print(" strawberries"print(" powdered sugar"topping int(input("choose topping")if (topping = )print ("you chose meal with syrup "elif (topping = )print ("you chose meal with strawberries "elif (topping = )print ("you chose meal with powdered sugar "elseprint ("we have meal "but not that topping "elif (mainchoice = )print("you chose oatmeal "elseprint("we don' serve that breakfast item!"
9,543
this example has some interesting features for one thingyou might assume that an if elif statement always requires an else clause this example shows situation that doesn' require such clause you use an if elif statement to ensure that meal contains the correct valuebut you have no other options to consider the selection technique is the same as you saw for the previous examples user enters number in the correct range to obtain desired result three of the selections require secondary choiceso you see the menu for that choice for examplewhen ordering eggsit isn' necessary to choose toppingbut you do want topping for pancakes or waffles notice that this example also combines variables and text in specific way because topping can apply equally to waffles or pancakesyou need some method for defining precisely which meal is being served as part of the output the meal variable that the application defines earlier is used as part of the output after the topping choice is made the best way to understand this example is to play with it try various menu combinations to see how the application works for examplefigure - shows what happens when you choose waffle breakfast with strawberry topping figure - many appli cations rely on multilevel menus
9,544
performing repetitive tasks in this performing task specific number of times performing task until completion placing one task loop within another ll the examples in the book so far have performed series of steps just one time and then stopped howeverthe real world doesn' work this way many of the tasks that humans perform are repetitious for examplethe doctor might state that you need to exercise more and tell you to do push-ups each day if you just do one push-upyou won' get much benefit from the exercise and you definitely won' be following the doctor' orders of coursebecause you know precisely how many push-ups to doyou can perform the task specific number of times python allows the same sort of repetition using the for statement unfortunatelyyou don' always know how many times to perform task for exampleconsider needing to check stack of coins for one of extreme rarity taking just the first coin from the topexamining itand deciding that it either is or isn' the rare coin doesn' complete the task insteadyou must examine each coin in turnlooking for the rare coin your stack may contain more than one only after you have looked at every coin in the stack can you say that the task is complete howeverbecause you don' know how many coins are in the stackyou don' know how many times to perform the task at the outset you only know the task is done when the stack is gone python performs this kind of repetition using the while statement most programming languages call any sort of repeating sequence of events loop the idea is to picture the repetition as circlewith the code going round and round executing tasks until the loop ends loops are an essential part of application elements such as menus in factwriting most modern applications without using loops would be impossible
9,545
in some casesyou must create loops within loops for exampleto create multiplication tableyou use loop within loop the inner loop calculates the column values and the outer loop moves between rows you see such an example later in the so don' worry too much about understanding precisely how such things work right now processing data using the for statement the first looping code block that most developers encounter is the for statement it' hard to imagine creating conventional programming language that lacks such statement in this casethe loop executes fixed number of timesand you know the number of times it will execute before the loop even begins because everything about for loop is known at the outsetfor loops tend to be the easiest kind of loop to use howeverin order to use oneyou need to know how many times to execute the loop the following sections describe the for loop in greater detail understanding the for statement for loop begins with for statement the for statement describes how to perform the loop the python for loop works through sequence of some type it doesn' matter whether the sequence is series of letters in string or items within collection you can even specify range of values to use by specifying the range(function here' simple for statement for letter in "howdy!"the statement begins with the keyword for the next item is variable that holds single element of sequence in this casethe variable name is letter the in keyword tells python that the sequence comes next in this casethe sequence is the string "howdythe for statement always ends with colonjust as the decision-making statements described in do indented under the for statement are the tasks you want performed within the for loop python considers every following indented statement part of the code block that composes the for loop againthe for loop works just like the decision-making statements in
9,546
creating basic for loop the best way to see how for loop actually works is to create one in this casethe example uses string for the sequence the for loop processes each of the characters in the string in turn until it runs out of characters this example also appears with the downloadable source code as simplefor py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each lineletternum for letter in "howdy!"print("letter "letternumis "letterletternum+= the example begins by creating variableletternumto track the number of letters that have been processed every time the loop completesletternum is updated by the for statement works through the sequence of letters in the string "howdy!it places each letterin turnin letter the code that follows displays the current letternum value and its associated character found in letter choose runrun module python shell window opens the application displays the letter sequence along with the letter numberas shown in figure - figure - use the for loop to process the characters in string one at time
9,547
controlling execution with the break statement life is often about exceptions to the rule for exampleyou might want an assembly line to produce number of clocks howeverat some pointthe assembly line runs out of needed part if the part isn' availablethe assembly line must stop in the middle of the processing cycle the count hasn' completedbut the line must be stopped anyway until the missing part is restocked interruptions also occur in computers you might be streaming data from an online source when network glitch occurs and breaks the connectionthe stream temporarily runs dryso the application runs out of things to do even though the set number of tasks isn' completed the break clause makes breaking out of loop possible howeveryou don' simply place the break clause in your code -you surround it with an if statement that defines the condition for issuing break the statement might say something like thisif the stream runs drythen break out of the loop in this exampleyou see what happens when the count reaches certain level when processing string the example is little contrived in the interest of keeping things simplebut it reflects what could happen in the real world when data element is too long to process (possibly indicating an error conditionthis example also appears with the downloadable source code as forbreak py open python file window you see an editor where you can type the example code type the following code into the window -pressing enter after each linevalue input("type less than characters"letternum for letter in valueprint("letter "letternumis "letterletternum+= if letternum print("the string is too long!"break
9,548
this example builds on the one found in the previous section howeverit lets the user provide variable-length string when the string is longer than six charactersthe application stops processing it the if statement contains the conditional code when letternum is greater than it means that the string is too long notice the second level of indentation used for the if statement in this casethe user sees an error message stating that the string is too longand then the code executes break to end the loop choose runrun module you see python shell window open with prompt asking for input type hello and press enter the application lists each character in the stringas shown in figure - perform steps and againbut type am too long instead of hello the application displays the expected error message and stops processing the string at character as shown in figure - figure - short string is successfully processed by the application this example adds length checking to your repertoire of application data error checks shows how to perform range checkswhich ensure that value meets specific limits the length check is necessary to ensure that dataespecially stringsaren' going to overrun the size of data fields in additiona small input size makes it harder for intruders to perform certain types of hacks on your systemwhich makes your system more secure
9,549
figure - long strings are trun cated to ensure that they remain certain size controlling execution with the continue statement sometimes you want to check every element in sequencebut don' want to process certain elements for exampleyou might decide that you want to process all the information for every car in database except brown cars perhaps you simply don' need the information about that particular color of car the break clause simply ends the loopso you can' use it in this situation otherwiseyou won' see the remaining elements in the sequence the break clause alternative that many developers use is the continue clause as with the break clausethe continue clause appears as part of an if statement howeverprocessing continues with the next element in the sequence rather than ending completely
9,550
the following steps help you see how the continue clause differs from the break clause in this casethe code refuses to process the letter wbut will process every other letter in the alphabet this example also appears with the downloadable source code as forcontinue py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each lineletternum for letter in "howdy!"if letter =" "continue print("encountered wnot processed "print("letter "letternumis "letterletternum+= this example is based on the one found in the "creating basic for loopsectionearlier in this howeverthis example adds an if statement with the continue clause in the if code block notice the print(function that is part of the if code block you never see this string printed because the current loop iteration ends immediately choose runrun module you see python shell window open the application displays the letter sequence along with the letter numberas shown in figure - howevernotice the effect of the continue clause -the letter isn' processed figure - use the continue clause to avoid processing specific elements
9,551
controlling execution with the pass clause the python language includes something not commonly found in other languagesa second sort of continue clause the pass clause works almost the same way as the continue clause doesexcept that it allows completion of the code in the if code block in which it appears the following steps use an example that is precisely the same as the one found in the previous section"controlling execution with the continue statement,except that it uses pass clause instead this example also appears with the downloadable source code as forpass py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each lineletternum for letter in "howdy!"if letter =" "pass print("encountered wnot processed "print("letter "letternumis "letterletternum+= choose runrun module you see python shell window open the application displays the letter sequence along with the letter numberas shown in figure - howevernotice the effect of the pass clause -the letter isn' processed in additionthe example displays the string that wasn' displayed for the continue clause example the continue clause makes it possible to silently bypass specific elements in sequence and to avoid executing any additional code for that element use the pass clause when you need to perform some sort of post processing on the elementsuch as logging the element in an error logdisplaying message to the useror handling the problem element in some other way the continue and pass clauses both do the same thingbut they're used in distinctly different situations
9,552
figure - using the pass clause allows for post process ing of an unwanted input controlling execution with the else statement python has another loop clause that you won' find with other languageselse the else clause makes executing code possible even if you have no elements to process in sequence for exampleyou might need to convey to the user that there simply isn' anything to do in factthat' what the following example does this example also appears with the downloadable source code as forelse py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linevalue input("type less than characters"letternum for letter in valueprint("letter "letternumis "letterletternum+= elseprint("the string is blank "
9,553
this example is based on the one found in the "creating basic for loopsectionearlier in the howeverwhen user presses enter without typing somethingthe else clause is executed choose runrun module you see python shell window open and prompt asking for input type hello and press enter the application lists each character in the stringas shown in figure - repeat steps and howeversimply press enter instead of entering any sort of text you see the alternative message shown in figure - that tells you the string is blank figure - the else clause makes it possible to perform tasks based on an empty sequence it' easy to misuse the else clause because an empty sequence doesn' always signify simple lack of input an empty sequence could also signal an application error or other conditions that need to be handled differently from simple omission of data make sure you understand how the application works with data to ensure that the else clause doesn' end up hiding potential error conditionsrather than making them visible so that they can be fixed
9,554
processing data using the while statement you use the while statement for situations when you're not sure how much data the application will have to process instead of instructing python to process static number of itemsyou use the while statement to tell python to continue processing items until it runs out of items this kind of loop is useful when you need to perform tasks such as downloading files of unknown size or streaming data from source such as radio station any situation in which you can' define at the outset how much data the application will process is good candidate for the while statement that is described more fully in the sections that follow understanding the while statement the while statement works with condition rather than sequence the condition states that the while statement should perform task until the condition is no longer true for exampleimagine deli with number of customers standing in front of the counter the salesperson continues to service customers until no more customers are left in line the line could (and probably willgrow as the other customers are handledso it' impossible to know at the outset how many customers will be served all the salesperson knows is that continuing to serve customers until no more are left is important here is how while statement might lookwhile sum the statement begins with the while keyword it then adds condition in this casea variablesummust be less than for the loop to continue nothing specifies the current value of sumnor does the code define how the value of sum will change the only thing that is known when python executes the statement is that sum must be less than for the loop to continue performing tasks the statement ends with colon and the tasks are indented below the statement because the while statement doesn' perform series of tasks set number of timescreating an endless loop is possiblemeaning that the loop never ends for examplesay that sum is set to when the loop beginsand the ending condition is that sum must be less than if the value of sum never increasesthe loop will continue executing forever (or at least until the computer is shut downendless loops can cause all sorts of bizarre problems on systemssuch as slowdowns and even computer freezesso it' best to avoid
9,555
them you must always provide method for the loop to end when using while loop (contrasted with the for loopin which the end of the sequence determines the end of the loopsowhen working with the while statementyou must perform three tasks create the environment for the condition (such as setting sum to state the condition within the while statement (such as sum update the condition as needed to ensure that the loop eventually ends (such as adding sum+= to the while code blockas with the for statementyou can modify the default behavior of the while statement in factyou have access to the same four clauses to modify the while statement behaviorbreakends the current loop continueimmediately ends processing of the current element passends processing of the current element after completing the statements in the if block elseprovides an alternative processing technique when conditions aren' met for the loop using the while statement in an application you can use the while statement in many waysbut this first example is straightforward it simply displays count based on the starting and ending condition of variable named sum the following steps help you create and test the example code this example also appears with the downloadable source code as simplewhile py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linesum while sum print(sumsum+=
9,556
the example code demonstrates the three tasks you must perform when working with while loop in straightforward manner it begins by setting sum to which is the first step of setting the condition environment the condition itself appears as part of the while statement the end of the while code block accomplishes the third step of coursethe code displays the current value of sum before it updates the value of sum while statement provides flexibility that you don' get with for statement this example shows relatively straightforward way to update sum howeveryou can use any update method required to meet the goals of the application nothing says that you have to update sum in specific manner in additionthe condition can be as complex as you want it to be for exampleyou can track the current value of three or four variables if so desired of coursethe more complex you make the conditionthe more likely it is that you'll create an endless loopso you have practical limit as to how complex you should make the while loop condition choose runrun module python executes the while loop and displays the numeric sequence shown in figure - figure - the simple while loop dis plays sequence of numbers nesting loop statements in some casesyou can use either for loop or while loop to achieve the same effect the manners work differentlybut the effect is the same in this exampleyou create multiplication table generator by nesting while loop within for loop because you want the output to look niceyou use little formatting as well provides you with detailed instruction in this regardthis example also appears with the downloadable source code as forelse py
9,557
open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linex print ('{:> }format(')end'for in range( )print('{:> }format( )end='print(for in range( , )print('{:> }format( )end='while < print('{:> }format( )end=' += print( = this example begins by creating two variablesx and yto hold the row and column value of the table is the row variable and is the column variable to make the table readablethis example must create heading at the top and another along the side when users see at the top and at the sideand follow these values to where they intersect in the tablethey can see the value of the two numbers when multiplied the first print(statement adds space (because nothing appears in the corner of the tablesee figure - to more easily follow this discussionall the formatting statement says is to create space characters wide and place space within it the {:> part of the code determines the size of the column the format('function determines what appears in that space the end attribute of the print(statement changes the ending character from carriage return to simple space the first for loop displays the numbers through at the top of the table the range(function creates the sequence of numbers for you when using the range(functionyou specify the starting valuewhich is in this caseand one more than the ending valuewhich is in this case
9,558
at this pointthe cursor is sitting at the end of the heading row to move it to the next linethe code issues print(call with no other information even though the next bit of code looks quite complexyou can figure it out if you look at it line at time the multiplication table shows the values from to so you need ten rows and ten columns to display the information the for statement tells python to create ten rows look again at figure - to note the row heading the first print(call displays the row heading value of courseyou have to format this informationand the code uses space of four characters that end with spacerather than carriage returnin order to continue printing information in that row the while loop comes next this loop prints the columns in an individual row the column values are the multiplied values of againthe output is formatted to take up four spaces the while loop ends when is updated to the next value using += now you're back into the for loop the print(statement ends the current row in additiony must be reset to so that it' ready for the beginning of the next rowwhich begins with choose runrun module you see the multiplication table shown in figure - figure - the multipli cation table is pleasing to the eye thanks to its formatting
9,559
9,560
dealing with errors in this defining problems in communication with python understanding error sources handling error conditions specifying that an error has occurred developing your own error indicators performing tasks even after an error occurs ost application code of any complexity has errors in it when your application suddenly freezes for no apparent reasonthat' an error seeing one of those obscure message dialog boxes is another kind of error howevererrors can occur that don' provide you with any sort of notification an application might perform the wrong computation on series of numbers you provideresulting in incorrect output that you may never know about unless someone tells you that something is wrong or you check for the issue yourself errors need not be consistenteither you may see them on some occasions and not on others for examplean error can occur only when the weather is bad or the network is overloaded in shorterrors occur in all sorts of situations and for all sorts of reasons this tells you about all sorts of errors and what to do when your application encounters them it shouldn' surprise you that errors occur -applications are written by humansand humans make mistakes most developers call application errors exceptionsmeaning that they're the exception to the rule because exceptions do occur in applicationsyou need to detect and do something about them whenever possible the act of detecting and processing an exception is called error handling or exception handling in order to properly detect errorsyou need to know about error sources and why errors occur in the first place when you do detect the erroryou must process it by catching the exception catching an exception means examining it and possibly doing something about it soanother part of this is about discovering how to perform exception handling in your own application
9,561
sometimes your code detects an error in the application when this happensyou need to raise or throw an exception you see both terms used for the same thingwhich simply means that your code encountered an error it couldn' handleso it passed the error information onto another piece of code to handle (interpretprocessandwith luckfix the exceptionin some casesyou use custom error message objects to pass on the information even though python has wealth of generic message objects that cover most situationssome situations are special for exampleyou might want to provide special support for database applicationand python won' normally cover that contingency with generic message object it' important to know when to handle exceptions locallywhen to send them to the code that called your codeand when to create special exceptions so that every part of the application knows how to handle the exception -all topics covered by this there are also times when you must ensure that your application handles an exception gracefullyeven if that means shutting the application down fortunatelypython provides the finally clausewhich always executeseven when an exception occurs you can place code to close files or perform other essential tasks in the code block associated with this clause even though you won' perform this task all the timeit' the last topic discussed in the knowing why python doesn' understand you developers often get frustrated with programming languages and omputers because they seemingly go out of their way to cause communication problems of courseprogramming languages and computers are both inanimate -there is no desire for anything on the part of either programming languages and computers also don' thinkthey accept whatever the developer has to say quite literally therein lies the problem neither python nor the computer will "know what you meanwhen you type instructions as code both follow whatever instructions you provide to the letter and literally as you provide them you may not have meant to tell python to delete data file unless some absurd condition occurred howeverif you don' make the conditions clearpython will delete the file whether the condition exists or not when an error of this sort happenspeople commonly say that the application has bug in it bugs are simply coding errors that you can remove using debugger ( debugger is special kind of tool that lets you stop or pause application executionexamine the content of variablesand generally dissect the application to see what makes it tick
9,562
errors occur in many cases when the developer makes assumptions that simply aren' true of coursethis includes assumptions about the application userwho probably doesn' care about the extreme level of care you took when crafting your application the user will enter bad data againpython won' know or care that the data is bad and will process it even when your intent was to disallow the bad input python doesn' understand the concepts of good or bad datait simply processes incoming data according to any rules you setwhich means that you must set rules to protect users from themselves python isn' proactive or creative -those qualities exist only in the developer when network error occurs or the user does something unexpectedpython doesn' create solution to fix the problem it only processes code if you don' provide code to handle the errorthe application is likely to fail and crash ungracefully -possibly taking all of the user' data with it of coursethe developer can' anticipate every potential error situationeitherwhich is why most complex applications have errors in them -errors of omissionin this case some developers out there think they can create bulletproof codedespite the absurdity of thinking that such code is even possible smart developers assume that some number of bugs will get through the code-screening processthat nature and users will continue to perform unexpected actionsand that even the smartest developer can' anticipate every possible error condition always assume that your application is subject to errors that will cause exceptionsthat wayyou'll have the mindset required to actually make your application more reliable considering the sources of errors you might be able to divine the potential sources of error in your application by reading tea leavesbut that' hardly an efficient way to do things errors actually fall into well-defined categories that help you predict (to some degreewhen and where they'll occur by thinking about these categories as you work through your applicationyou're far more likely to discover potential errors sources before they occur and cause potential damage the two principle categories are errors that occur at specific time errors that are of specific type the following sections discuss these two categories in greater detail the overall concept is that you need to think about error classifications in order to start finding and fixing potential errors in your application before they become problem
9,563
classifying when errors occur errors occur at specific times the two major time frames are compile time runtime no matter when an error occursit causes your application to misbehave the following sections describe each time frame compile time compile time error occurs when you ask python to run the application before python can run the applicationit must interpret the code and put it into form that the computer can understand computer relies on machine code that is specific to that processor and architecture if the instructions you write are malformed or lack needed informationpython can' perform the required conversion it presents an error that you must fix before the application can run fortunatelycompile-time errors are the easiest to spot and fix because the application won' run with compile-time error in placeuser never sees this error category you fix this sort of error as you write your code the appearance of compile-time error should tell you that other typos or omissions could exist in the code it always pays to check the surrounding code to ensure that no other potential problems exist that might not show up as part of the compile cycle runtime runtime error occurs after python compiles the code you write and the computer begins to execute it runtime errors come in several different typesand some are harder to find than others you know you have runtime error when the application suddenly stops running and displays an exception dialog box or when the user complains about erroneous output (or at least instabilitynot all runtime errors produce an exception some runtime errors cause instability (the application freezes)errant outputor data damage runtime errors can affect other applications or create unforeseen damage to the platform on which the application is running in shortruntime errors can cause you quite bit of griefdepending on precisely the kind of error you're dealing with at the time many runtime errors are caused by errant code for exampleyou can misspell the name of variablepreventing python from placing information in the correct variable during execution leaving out an optional but necessary
9,564
argument when calling method can also cause problems these are examples of errors of commissionwhich are specific errors associated with your code in generalyou can find these kinds of errors using debugger or by simply reading your code line by line to check for errors runtime errors can also be caused by external sources not associated with your code for examplethe user can input incorrect information that the application isn' expectingcausing an exception network error can make required resource inaccessible sometimes even the computer hardware has glitch that causes nonrepeatable application error these are all examples of errors of omissionfrom which the application might recover if your application has error-trapping code in place it' important that you consider both kinds of runtime errors -errors of commission and omission -when building your application distinguishing error types you can distinguish errors by typethat isby how they're made knowing the error types helps you understand where to look in an application for potential problems exceptions work like many other things in life for exampleyou know that electronic devices don' work without power sowhen you try to turn your television on and it doesn' do anythingyou might look to ensure that the power cord is firmly seated in the socket understanding the error types helps you locate errors fasterearlierand more consistentlyresulting in fewer misdiagnoses the best developers know that fixing errors while an application is in development is always easier than fixing it when the application is in production because users are inherently impatient and want errors fixed immediately and correctly in additionfixing an error earlier in the development cycle is always easier than fixing it when the application nears completion because less code exists to review the trick is to know where to look with this in mindpython (and most other programming languagesbreaks errors into the following typessyntactical semantic logical the following sections examine each of these error types in more detail 've arranged the sections in order of difficultystarting with the easiest to find syntactical error is generally the easiesta logical error is generally the hardest
9,565
syntactical whenever you make typo of some sortyou create syntactical error some python syntactical errors are quite easy to find because the application simply doesn' run the interpreter may even point out the error for you by highlighting the errant code and displaying an error message howeversome syntactical errors are quite hard to find python is case sensitiveso you may use the wrong case for variable in one place and find that the variable isn' quite working as you thought it would finding the one place where you used the wrong capitalization can be quite challenging most syntactical errors occur at compile time and the interpreter points them out for you fixing the error is made easy because the interpreter generally tells you what to fixand with considerable accuracy even when the interpreter doesn' find the problemsyntactical errors prevent the application from running correctlyso any errors the interpreter doesn' find show up during the testing phase few syntactical errors should make it into production as long as you perform adequate application testing semantic when you create loop that executes one too many timesyou don' generally receive any sort of error information from the application the application will happily run because it thinks that it' doing everything correctlybut that one additional loop can cause all sorts of data errors when you create an error of this sort in your codeit' called semantic error semantic errors occur because the meaning behind series of steps used to perform task is wrong -the result is incorrect even though the code apparently runs precisely as it should semantic errors are tough to findand you sometimes need some sort of debugger to find them provides discussion of tools that you can use with python to perform tasks such as debugging applications you can also find blog posts about debugging on my blog at logical some developers don' create division between semantic and logical errorsbut they are different semantic error occurs when the code is essentially correct but the implementation is wrong (such as having loop execute once too oftenlogical errors occur when the developer' thinking is faulty in many casesthis sort of error happens when the developer uses relational or logical operator incorrectly howeverlogical errors can happen in all sorts of other waystoo for examplea developer might think that data is always stored on the local hard drivewhich means that the application may behave in an unusual manner when it attempts to load data from network drive instead
9,566
logical errors are quite hard to fix because the problem isn' with the actual codeyet the code itself is incorrectly defined the thought process that went into creating the code is faultythereforethe developer who created the error is less likely to find it smart developers use second pair of eyes to help spot logical errors having formal application specification also helps because the logic behind the tasks the application performs is usually given formal review catching exceptions generally speakinga user should never see an exception dialog box your application should always catch the exception and handle it before the user sees it of coursethe real world is different -users do see unexpected exceptions from time to time howevercatching every potential exception is still the goal when developing an application the following sections describe how to catch exceptions and handle them understanding the built-in exceptions python comes with host of built-in exceptions -far more than you might think possible you can see list of these exceptions at library/exceptions html the docu mentation breaks the exception list down into categories here is brief overview of the python exception categories that you work with regularlybase classesthe base classes provide the essential building blocks (such as the exception exceptionfor other excep tions howeveryou might actually see some of these exceptionssuch as the arithmeticerror exceptionwhen working with an application concrete exceptionsapplications can experience hard errors -errors that are hard to overcome because there really isn' good way to handle them or they signal an event that the application must handle for examplewhen system runs out of memorypython generates memoryerror exception recovering from this error is hard because it isn' always possible to release memory from other uses when the user presses an interrupt key (such as ctrl+ or delete)python gener ates keyboardinterrupt exception the application must handle this exception before proceeding with any other tasks os exceptionsthe operating system can generate errors that python then passes them along to your application for exam pleif your application tries to open file that doesn' existthe operating system generates filenotfounderror exception warningspython tries to warn you about unexpected events or actions that could result in errors later for exampleif you try to inappropriately use resourcesuch as an iconpython generates resourcewarning exception it' important to remember that this particular category is warning and not an actual errorignoring it can cause you woe laterbut you can ignore it
9,567
basic exception handling to handle exceptionsyou must tell python that you want to do so and then provide code to perform the handling tasks you have number of ways in which you can perform this task the following sections start with the simplest method first and then move on to more complex methods that offer added flexibility handling single exception in the ifelse py and other examples have terrible habit of spitting out exceptions when the user inputs unexpected values part of the solution is to provide range checking howeverrange checking doesn' overcome the problem of user typing text such as hello in place of an expected numeric value exception handling provides more complex solution to the problemas described in the following steps this example also appears with the downloadable source code as basicexception py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linetryvalue int(input("type number between and ")except valueerrorprint("you must type number between and !"elseif (value and (value < )print("you typed"valueelseprint("the value you typed is incorrect!"the code within the try block has its exceptions handled in this casehandling the exception means getting input from the user using the int(input()calls if an exception occurs outside this blockthe code doesn' handle it with reliability in mindthe temptation might be to enclose all the executable code in try block so that every exception would be handled howeveryou want to make your exception handling small and specific to make locating the problem easier
9,568
the except block looks for specific exception in this casevalueerror when the user creates valueerror exception by typing hello instead of numeric valuethis particular exception block is executed if the user were to generate some other exceptionthis except block wouldn' handle it the else block contains all the code that is executed when the try block code is successful (doesn' generate an exceptionthe remainder of the code is in this block because you don' want to execute it unless the user does provide valid input when the user provides whole number as inputthe code can then range check it to ensure that it' correct choose runrun module you see python shell window open the application asks you to type number between and type hello and press enter the application displays an error messageas shown in figure - figure - typing the wrong input type generates an error instead of an exception perform steps and againbut type instead of hello the application generates the same error messageas shown in figure - perform steps and againbut type instead of hello the application outputs the expected range error messageas shown in figure - exception handling doesn' weed out range errors you must still check for them separately
9,569
figure - exception handling doesn' ensure that the value is in the cor rect range perform steps and againbut type instead of hello this timethe application finally reports that you've provided correct value of even though it seems like lot of work to perform this level of checkingyou can' really be certain that your application is working correctly without it perform steps and againbut press ctrl+ccmd+cor the alternative for your platform instead of typing anything the application generates keyboardinterrupt exceptionas shown in figure - because this exception isn' handledit' still problem for the user you see several techniques for fixing this problem later in the using the except clause without an exception you can create an exception handling block in python that' generic because it doesn' look for specific exception in most casesyou want to provide specific exception when performing exception handling for these reasonsto avoid hiding an exception you didn' consider when designing the application to ensure that others know precisely which exceptions your application will handle to handle the exceptions correctly using specific code for that exception
9,570
figure - the excep tion han dling in this example deals only with value error exceptions howeversometimes you may need generic exception-handling capabilitysuch as when you're working with third-party libraries or interacting with an external service the following steps demonstrate how to use an except clause without specific exception attached to it this example also appears with the downloadable source code as basicexception py open python file window you see an editor in which you can type the example code
9,571
type the following code into the window -pressing enter after each linetryvalue int(input("type number between and ")exceptprint("you must type number between and !"elseif (value and (value < )print("you typed"valueelseprint("the value you typed is incorrect!"the only difference between this example and the previous example is that the except clause doesn' have the valueerror exception specifically associated with it the result is that this except clause will also catch any other exception that occurs choose runrun module you see python shell window open the application asks you to type number between and type hello and press enter the application displays an error message (refer to figure - perform steps and againbut type instead of hello the application generates the same error message (againrefer to figure - perform steps and againbut type instead of hello the application outputs the expected range error message (refer to figure - exception handling doesn' weed out range errors you must still check for them separately perform steps and againbut type instead of hello this timethe application finally reports that you've provided correct value of even though it seems like lot of work to perform this level of checkingyou can' really be certain that your application is working correctly without it perform steps and againbut press ctrl+ccmd+cor the alternative for your platform instead of typing anything you see the error message that' usually associated with input erroras shown in figure - the error message is incorrectwhich might confuse users howeverthe plus side is that the application didn' crash
9,572
which means that you won' lose any data and the application can recover using generic exception handling does have some advantagesbut you must use it carefully figure - generic exception handling traps the keyboard inter rupt exception working with exception arguments most exceptions don' provide arguments ( list of values that you can check for additional informationthe exception either occurs or it doesn' howevera few exceptions do provide argumentsand you see them used later in the book the arguments tell you more about the exception and provide details that you need to correct it for the sake of completenessthis includes simple example that generates an exception with an argument you can safely skip the remainder of this section if desired because the information is covered in more detail later in the book this example also appears with the downloadable source code as exceptionwitharguments py
9,573
open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each lineimport sys tryfile open('myfile txt'except ioerror as eprint("error opening file!\ \ "error number{ }\ \nformat( errno"error text{ }format( strerror)elseprint("file opened as expected "file close()this example uses some advanced features the import statement obtains code from another file tells you how to use this python feature the open(function opens file and provides access to the file through the file variable tells you how file access works given that myfile txt doesn' exist in the application directorythe operating system can' open it and will tell python that the file doesn' exist trying to open nonexistent file generates an ioerror exception this particular exception provides access to two argumentserrnoprovides the operating system error number as an integer strerrorcontains the error information as human-readable string the as clause places the exception information into variableethat you can access as needed for additional information the except block contains print(call that formats the error information into an easily read error message if you should decide to create the myfile txt filethe else clause executes in this caseyou see message stating that the file opened normally the code then closes the file without doing anything with it choose runrun module you see python shell window open the application displays the error opening file informationas shown in figure -
9,574
figure - attempting to open nonexistent file never works obtaining list of exception arguments the list of arguments supplied with exceptions varies by exception and by what the sender pro vides it isn' always easy to figure out what you can hope to obtain in the way of additional informa tion one way to handle the problem is to simply print everything using code like this (this example also appears with the downloadable source code as getexceptionarguments py)import sys tryfile open('myfile txt'except ioerror as efor arg in argsprint(argelseprint("file opened as expected "file close()the args property always contains list of the exception arguments in string format you can use simple for loop to print each of the arguments the only problem with this approach is that you're missing the argument namesso you know the output information (which is obvious in this case)but you don' know what to call it more complex method of dealing with the issue is to print both the names and the contents of the arguments the following code displays both the names and the values of each of the arguments (this example also appears with the downloadable source as getexceptionarguments py)import sys tryfile open('myfile txt'(continued
9,575
(continuedexcept ioerror as efor entry in dir( )if (not entry startswith(" "))tryprint(entry" __getattribute__(entry)except attributeerrorprint("attribute "entrynot accessible "elseprint("file opened as expected "file close()in this caseyou begin by getting listing of the attributes associated with the error argument object using the dir(function the output of the dir(function is list of strings containing the names of the attributes that you can print only those arguments that don' start with an under score (_contain useful information about the exception howevereven some of those entries are inaccessibleso you must encase the output code in second try except block (see the "nested exception handlingsectionlater in the for detailsthe attribute name is easy because it' contained in entry to obtain the value associated with that attributeyou must use the __getattribute__(function and supply the name of the attribute you want when you run this codeyou see both the name and the value of each of the attri butes supplied with particular error argument object in this casethe actual output is as followsargs ( 'no such file or directory'attribute characters_written not accessible errno filename myfile txt strerror no such file or directory winerror none with_traceback <built-in method with_traceback of filenotfounderror object at dc handling multiple exceptions with single except clause most applications can generate multiple exceptions for single line of code this fact demonstrated earlier in the with the basicexception py example how you handle the multiple exceptions depends on your goals for the applicationthe types of exceptionsand the relative skill of your users sometimes when working with less skilled userit' simply easier to say that the application experienced nonrecoverable error and then log the details into log file in the application directory or central location using single except clause to handle multiple exceptions works only when common source of action fulfills the needs of all the exception types otherwiseyou need to handle each exception individually the following steps show how to handle multiple exceptions using single except clause this example also appears with the downloadable source code as multipleexception py
9,576
open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linetryvalue int(input("type number between and ")except (valueerrorkeyboardinterrupt)print("you must type number between and !"elseif (value and (value < )print("you typed"valueelseprint("the value you typed is incorrect!"this code is very much like the basicexception py howevernotice that the except clause now sports both valueerror and keyboardinterrupt exception in additionthese exceptions appear within parentheses and are separated by commas choose runrun module you see python shell window open the application asks you to type number between and type hello and press enter the application displays an error message (refer to figure - perform steps and againbut type instead of hello the application outputs the expected range error message (refer to figure - perform steps and againbut press ctrl+ccmd+cor the alternative for your platform instead of typing anything you see the error message that' usually associated with error input (refer to figure - perform steps and againbut type instead of hello this timethe application finally reports that you've provided correct value of handling multiple exceptions with multiple except clauses when working with multiple exceptionsit' usually good idea to place each exception in its own except clause this approach allows you to provide custom handling for each exception and makes it easier for the user to know precisely what went wrong of coursethis approach is also lot more work
9,577
the following steps demonstrate how to perform exception handling using multiple except clauses this example also appears with the downloadable source code as multipleexception py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linetryvalue int(input("type number between and ")except valueerrorprint("you must type number between and !"except keyboardinterruptprint("you pressed ctrl+ !"elseif (value and (value < )print("you typed"valueelseprint("the value you typed is incorrect!"notice the use of multiple except clauses in this case each except clause handles different exception you can use combination of techniqueswith some except clauses handling just one exception and other except clauses handling multiple exceptions python lets you use the approach that works best for the error-handling situation choose runrun module you see python shell window open the application asks you to type number between and type hello and press enter the application displays an error message (refer to figure - perform steps and againbut type instead of hello the application outputs the expected range error message (refer to figure - perform steps and againbut press ctrl+ccmd+cor the alternative for your platform instead of typing anything the application outputs specific message that tells the user what went wrongas shown in figure - perform steps and againbut type instead of hello this timethe application finally reports that you've provided correct value of
9,578
figure - using multiple except clauses makes spe cific error messages possible handling more specific to less specific exceptions one strategy for handling exceptions is to provide specific except clauses for all known exceptions and generic except clauses to handle unknown exceptions you can see the exception hierarchy that python uses at html#exception-hierarchy when viewing this chartbaseexception is the uppermost exception most exceptions are derived from exception when working through math errorsyou can use the generic arithmeticerror or more specific zerodivisionerror exception python evaluates except clauses in the order in which they appear in the source code file the first clause is examined firstthe second clause is examined secondand so on the following steps help you examine an example that demonstrates the importance of using the correct exception order in this caseyou perform tasks that result in math errors this example also appears with the downloadable source code as multipleexception py
9,579
open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linetryvalue int(input("type the first number")value int(input("type the second number")output value value except valueerrorprint("you must type whole number!"except keyboardinterruptprint("you pressed ctrl+ !"except arithmeticerrorprint("an undefined math error occurred "except zerodivisionerrorprint("attempted to divide by zero!"elseprint(outputthe code begins by obtaining two inputsvalue and value the first two except clauses handle unexpected input the second two except clauses handle math exceptionssuch as dividing by zero if everything goes well with the applicationthe else clause executeswhich prints the result of the operation choose runrun module you see python shell window open the application asks you to type the first number type hello and press enter as expectedpython displays the valueerror exception message howeverit always pays to check for potential problems choose runrun module again you see python shell window open the application asks you to type the first number type and press enter the application asks you to enter the second number
9,580
type and press enter you see the error message for the arithmeticerror exceptionas shown in figure - what you should actually see is the zerodivisionerror exception because it' more specific than the arithmeticerror exception figure - the order in which python processes exceptions is important reverse the order of the two exceptions so that they look like thisexcept zerodivisionerrorprint("attempted to divide by zero!"except arithmeticerrorprint("an undefined math error occurred " perform steps through again this timeyou see the zerodivisionerror exception message because the exceptions appear in the correct order perform steps through againbut type for the second number instead of this timethe application finally reports an output value of as shown in figure - notice that the output shown in figure - is floating-point value division results in floating-point value unless you specify that you want an integer output by using the floor division operator (//
9,581
figure - providing usable input results in usable output nested exception handling sometimes you need to place one exception-handling routine within another in process called nesting when you nest exception-handling routinespython tries to find an exception handler in the nested level first and then moves to the outer layers you can nest exception-handling routines as deeply as needed to make your code safe one of the more common reasons to use dual layer of exception-handling code is when you want to obtain input from user and need to place the input code in loop to ensure that you actually get the required information the following steps demonstrate how this sort of code might work this example also appears with the downloadable source code as multipleexception py open python file window you see an editor in which you can type the example code
9,582
type the following code into the window -pressing enter after each linetryagain true while tryagaintryvalue int(input("type whole number ")except valueerrorprint("you must type whole number!"trydoover input("try again ( / )"exceptprint("oksee you next time!"tryagain false elseif (str upper(doover=" ")tryagain false except keyboardinterruptprint("you pressed ctrl+ !"print("see you next time!"tryagain false elseprint(valuetryagain false the code begins by creating an input loop using loops for this type of purpose is actually quite common in applications because you don' want the application to end every time an input error is made this is simplified loopand normally you create separate function to hold the code when the loop startsthe application asks the user to type whole number it can be any integer value if the user types any non-integer value or presses ctrl+ccmd+cor another interrupt key combinationthe exception-handling code takes over otherwisethe application prints the value that the user supplied and sets tryagain to falsewhich causes the loop to end valueerror exception can occur when the user makes mistake because you don' know why the user input the wrong valueyou have to ask if the user wants to try again of coursegetting more input from the user could generate another exception the inner try except code block handles this secondary input notice the use of the str upper(function when getting character input from the user this function makes it possible to receive or as input and accept them both whenever you ask the user for character inputit' good idea to convert lowercase characters to uppercase so that you can perform single comparison (reducing the potential for error
9,583
the keyboardinterrupt exception displays two messages and then exits automatically by setting tryagain to false the keyboardinterrupt occurs only when the user presses specific key combination designed to end the application the user is unlikely to want to continue using the application at this point choose runrun module you see python shell window open the application asks the user to input whole number type hello and press enter the application displays an error message and asks whether you want to try again type and press enter the application asks you to input whole number againas shown in figure - figure - using loop means that the application can recover from the error type and press enter the application again displays the error message and asks whether you want to try again press ctrl+ccmd+cor another key combination to interrupt the application the application endsas shown in figure - notice that the message is the one from the inner exception the application never gets to the outer exception because the inner exception handler provides generic exception handling choose runrun module you see python shell window open the application asks the user to input whole number
9,584
figure - the inner exception handler pro vides sec ondary input support press ctrl+ccmd+cor another key combination to interrupt the application the application endsas shown in figure - notice that the message is the one from the outer exception in steps and the user ends the application by pressing an interrupt key howeverthe application uses two different exception handlers to address the problem figure - the outer exception handler provides pri mary input support
9,585
raising exceptions so farthe examples in this have reacted to exceptions something happens and the application provides error-handling support for that event howeversituations arise for which you may not know how to handle an error event during the application design process perhaps you can' even handle the error at particular level and need to pass it up to some other level to handle in shortin some situationsyour application must generate an exception this act is called raising (or sometimes throwingthe exception the following sections describe common scenarios in which you raise exceptions in specific ways raising exceptions during exceptional conditions the example in this section demonstrates how you raise simple xception -that it doesn' require anything special the following steps simply create the exception and then handle it immediately this example also appears with the downloadable source code as raiseexception py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linetryraise valueerror except valueerrorprint("valueerror exception!"you wouldn' ever actually create code that looks like thisbut it shows you how raising an exception works at its most basic level in this casethe raise call appears within try except block basic raise call simply provides the name of the exception to raise (or throwyou can also provide arguments as part of the output to provide additional information notice that this try except block lacks an else clause because there is nothing to do after the call although you rarely use try except block in this manneryou can you may encounter situations like this one sometimes and need to remember that adding the else clause is purely optional on the other handyou must add at least one except clause
9,586
choose runrun module you see python shell window open the application displays the expected exception textas shown in figure - figure - raising an excep tion only requires call to raise passing error information to the caller python provides exceptionally flexible error handling in that you can pass information to the caller (the code that is calling your codeno matter which exception you use of coursethe caller may not know that the information is availablewhich leads to lot of discussion on the topic if you're working with someone else' code and don' know whether additional information is availableyou can always use the technique described in the "obtaining list of exception argumentssidebar earlier in this to find it you may have wondered whether you could provide better information when working with valueerror exception than with an exception provided natively by python the following steps show that you can modify the output so that it does include helpful information this example also appears with the downloadable source code as raiseexception py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each linetryex valueerror(ex strerror "value must be within and raise ex except valueerror as eprint("valueerror exception!" strerror
9,587
the valueerror exception normally doesn' provide an attribute named strerror ( common name for string error)but you can add it simply by assigning value to it as shown when the example raises the exceptionthe except clause handles it as usual but obtains access to the attributes using you can then access the strerror member to obtain the added information choose runrun module you see python shell window open the application displays an expanded valueerror exceptionas shown in figure - figure - it' possible to add error informa tion to any exception creating and using custom exceptions python provides wealth of standard exceptions that you should use whenever possible these exceptions are incredibly flexibleand you can even modify them as needed (within reasonto meet specific needs for examplethe "passing error information to the callersection of this demonstrates how to modify valueerror exception to allow for additional data howeversometimes you simply must create custom exception because none of the standard exceptions will work perhaps the exception name just doesn' tell the viewer the purpose that the exception serves you may need custom exception for specialized database work or when working with service the example in this section is going to seem little complicated for now because you haven' worked with classes before introduces you to classes and helps you understand how they work if you want to skip this section until after you read you can do so without any problem
9,588
the example in this section shows quick method for creating your own exceptions to perform this taskyou must create class that uses an existing exception as starting point to make things little easierthis example creates an exception that builds upon the functionality provided by the valueerror exception the advantage of using this approach rather than the one shown in the "passing error information to the callersectionthe preceding section in this is that this approach tells anyone who follows you precisely what the addition to the valueerror exception isadditionallyit makes the modified exception easier to use this example also appears with the downloadable source code as customexception py open python file window you see an editor in which you can type the example code type the following code into the window -pressing enter after each lineclass customvalueerror(valueerror)def __init__(selfarg)self strerror arg self args {argtryraise customvalueerror("value must be within and "except customvalueerror as eprint("customvalueerror exception!" strerrorthis example essentially replicates the functionality of the example in the "passing error information to the callersection of the howeverit places the same error in both strerror and args so that the developer has access to either (as would normally happenthe code begins by creating the customvalueerror class that uses the valueerror exception class as starting point the __init__(function provides the means for creating new instance of that class think of the class as blueprint and the instance as the building created from the blueprint notice that the strerror attribute has the value assigned directly to itbut args receives it as an array the args member normally contains an array of all the exception valuesso this is standard procedureeven when args contains just one value as it does now the code for using the exception is considerably easier than modifying valueerror directly all you do is call raise with the name of the exception and the arguments you want to passall on one line
9,589
choose runrun module you see python shell window open the application displays the letter sequencealong with the letter numberas shown in figure - figure - custom exceptions can make your code easier to read using the finally clause normally you want to handle any exception that occurs in way that doesn' cause the application to crash howeversometimes you can' do anything to fix the problemand the application is most definitely going to crash at this pointyour goal is to cause the application to crash gracefullywhich means closing files so that the user doesn' lose data and performing other tasks of that nature anything you can do to keep damage to data and the system to minimum is an essential part of handling data for crashing application the finally clause is part of the crashing-application strategy you use this clause to perform any required last-minute tasks normallythe finally clause is quite short and uses only calls that are likely to succeed without further problem it' essential to close the fileslog the user offand perform other required tasksand then let the application crash before something terrible happens (such as total system failurewith this necessity in mindthe following steps show simple example of using the finally clause this example also appears with the downloadable source code as exceptionwithfinally py open python file window you see an editor in which you can type the example code
9,590
type the following code into the window -pressing enter after each lineimport sys tryraise valueerror print("raising an exception "except valueerrorprint("valueerror exception!"sys exit(finallyprint("taking care of last minute details "print("this code will never execute "in this examplethe code raises valueerror exception the except clause executes as normal when this happens the call to sys exit(means that the application exits after the exception is handled perhaps the application can' recover in this particular instancebut the application normally endswhich is why the final print(function call won' ever execute the finally clause code always executes it doesn' matter whether the exception happens or not the code you place in this block needs to be common code that you always want to execute for examplewhen working with fileyou place the code to close the file into this block to ensure that the data isn' damaged by remaining in memory rather than going to disk choose runrun module you see python shell window open the application displays the except clause message and the finally clause messageas shown in figure - the sys exit(call prevents any other code from executing figure - use the finally clause to ensure spe cific actions take place before the application ends
9,591
comment out the raise valueerror call by preceding it with two pound signslike this##raise valueerror removing the exception will demonstrate how the finally clause actually works save the file to disk to ensure that python sees the change choose runrun module you see python shell window open the application displays series of messagesincluding the finally clause messageas shown in figure - this part of the example shows that the finally clause always executesso you need to use it carefully figure - it' essential to remem ber that the finally clause always executes
9,592
performing common tasks see an example of how you can named arguments in format strings at www dummies com/extras/beginningprogrammingwithpython
9,593
gain access to python modules slice and dice strings to meet your output needs create lists of objects you want to manage use collections to organize data efficiently develop classes to make code reusable
9,594
interacting with modules in this organizing your code adding code from outside sources to your application locating code libraries on disk looking at the library code obtaining and reading the python library documentation he examples in this book are smallbut the functionality of the resulting applications is extremely limited as well even tiny real-world applications contain thousands of lines of code in factapplications that contain millions of lines of code are somewhat common imagine trying to work with file large enough to contain millions of lines of code -you' never find anything in shortyou need some method to organize code into small pieces that are easier to managemuch like the examples in this book the python solution is to place code in separate code groupings called modules commonly used modules that contain source code for generic needs are called libraries modules are contained in separate files in order to use the moduleyou must tell python to grab the file and read it into the current application the process of obtaining code found in external files is called importing you import module or library to use the code it contains few examples in the book have already shown the import statement in usebut this explains the import statement in detail so that you know how to use it as part of the initial setuppython created pointer to the general-purpose libraries that it uses that' why you can simply add an import statement with the name of the library and python can find it howeverit pays to know how to locate the files on disk in case you ever need to update them or you want to add your own modules and libraries to the list of files that python can use
9,595
the library code is self-contained and well documented (at least in most cases it issome developers might feel that they never need to look at the library codeand they're right to some degree -you never have to look at the library code in order to use it you might want to view the library codethoughto ensure that you understand how the code works in additionthe library code can teach you new programming techniques that you might not otherwise discover soviewing the library code is optionalbut it can be helpful the one thing you do need to know how to do is obtain and use the python library documentation this shows you how to obtain and use the library documentation as part of the application-creation process creating code groupings it' important to group like pieces of code together to make the code easier to usemodifyand understand as an application growsmanaging the code found in single file becomes harder and harder at some pointthe code becomes impossible to manage because the file has become too large for anyone to work with the term code is used broadly in this particular case code groupings can includeclasses functions variables runnable code the collection of classesfunctionsvariablesand runnable code within module is known as attributes module has attributes that you access by that attribute' name later sections in this discuss precisely how module access works the runnable code can actually be written in language other than python for exampleit' somewhat common to find modules that are written in / +instead of python the reason that some developers use runnable code is to make the python application fasterless resource intensiveand better able to use particular platform' resources howeverusing runnable code comes with the downside of making your application less portable (able to run on other platformsunless you have runnable code modules for each platform
9,596
that you want to support in additiondual-language applications can be harder to maintain because you must have developers who can speak each of the computer languages used in the application the most common way to create module is to define separate file containing the code you want to group separately from the rest of the application for exampleyou might want to create print routine that an application uses in number of places the print routine isn' designed to work on its own but is part of the application as whole you want to separate it because the application uses it in numerous places and you could potentially use the same code in another application the ability to reuse code ranks high on the list of reasons to create modules to make things easier to understandthe examples in this use common module the module doesn' do anything too amazingbut it demonstrates the principles of working with modules open python file window and create new file named mylibrary py type the code found in listing - and save it to disk (this module also appears with the downloadable source code as mylibrary py listing - simple demonstration module def sayhello(name)print("hello "namereturn def saygoodbye(name)print("goodbye "namereturn the example code contains two simple functions named sayhello(and saygoodbye(in both casesyou supply name to print and the function prints it onscreen along with greeting for you at that pointthe function returns control to the caller obviouslyyou normally create more complicated functionsbut these functions work well for the purposes of this importing modules in order to use moduleyou must import it python places the module code inline with the rest of your application in memory -as if you had created one huge file neither file is changed on disk -they're still separatebut the way python views the code is different
9,597
you have two ways to import modules each technique is used in specific circumstancesimportyou use the import statement when you want to import an entire module this is the most common method that developers use to import modules because it saves time and requires only one line of code howeverthis approach also uses more memory resources than does the approach of selectively importing the attributes you needwhich the next paragraph describes from importyou use the from import statement when you want to selectively import individual module attributes this method saves resourcesbut at the cost of complexity in additionif you try to use an attribute that you didn' importpython registers an error yesthe module still contains the attributebut python can' see it because you didn' import it now that you have better idea of how to import modulesit' time to look at them in detail the following sections help you work through importing modules using the two techniques available in python changing the current python directory the directory that python is using to access code affects which modules you can load the python library files are always included in the list of locations that python can accessbut python knows nothing of the directory you use to hold your source code unless you tell it to look there the easiest method for accomplish ing this task is to change the current python directory to point to your code folder using these steps open the python shell you see the python shell window appear type import os and press enter this action imports the python os library you need to import this library to change the directory (the location python sees on diskto the working directory for this book type os chdir(" :\bp \"and press enter you need to use the directory that contains the downloadable source or your own proj ect files on your local hard drive the book uses the default book directory described in python can now use the down loadable source code directory to access modules that you create for this
9,598
using the import statement the import statement is the most common method for importing module into python this approach is fast and ensures that the entire module is ready for use the following steps get you started using the import statement open the python shell you see the python shell window appear change directories to the downloadable source code directory see the instructions found in the "changing the current python directorysidebar type import mylibrary and press enter python imports the contents of the mylibrary py file that you created in the "creating code groupingssection of the the entire library is now ready for use it' important to know that python also creates cache of the module in the __pycache__ subdirectory if you look into your source code directory after you import mylibrary for the first timeyou see the new __pycache__ directory if you want to make changes to your moduleyou must delete this directory otherwisepython will continue to use the unchanged cache file instead of your updated source code file type dir(mylibraryand press enter you see listing of the module contentswhich includes the sayhello(and saygoodbye(functionsas shown in figure - ( discussion of the other entries appears in the "viewing the module contentsection of the figure - direc tory listing shows that python imports both functions from the module
9,599
type mylibrary sayhello("josh"and press enter the sayhello(function outputs the expected textas shown in figure - figure - the say hello(function outputs the expected greeting notice that you must precede the attribute namewhich is the say hello(function in this casewith the module namewhich is mylibrary the two elements are separated by period every call to module that you import follows the same pattern type mylibrary saygoodbye("sally"and press enter the saygoodbyefunction outputs the expected text close the python shell the python shell window closes using the from import statement the from import statement has the advantage of importing only the attributes you need from module this difference means that the module uses less memory and other system resources than using the import statement does in additionthe from import statement makes the module little easier to use because some commandssuch as dir()show less informationor only the information that you actually need the point is that you get only what you want and not anything else the following steps demonstrate using the from import statement