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 w... |
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 placin... |
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 pe... |
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 yess... |
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... |
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 ... |
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 re... |
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 oper... |
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... |
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 ret... |
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... |
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 b... |
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 pos... |
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 ... |
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 w... |
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 ... |
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 functions... |
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 insertio... |
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 ... |
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 functio... |
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 thi... |
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 ... |
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... |
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... |
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 ... |
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 crea... |
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 t... |
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 coul... |
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 comp... |
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 ... |
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 conditio... |
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 ho... |
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 py... |
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 en... |
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 -... |
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 choo... |
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... |
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(inp... |
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 defaul... |
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 langua... |
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 pancake... |
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 grea... |
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("choos... |
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 selectio... |
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 per... |
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 pro... |
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 op... |
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 c... |
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 t... |
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... |
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 ... |
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... |
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 ... |
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... |
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 t... |
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 conditi... |
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 thir... |
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( = thi... |
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... |
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 applic... |
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 (interpretprocessandw... |
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... |
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 p... |
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 sou... |
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 ... |
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 ... |
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 fl... |
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 th... |
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 ap... |
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 s... |
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 ex... |
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 va... |
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 ope... |
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 pro... |
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 o... |
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... |
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 aft... |
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 hierarch... |
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 keyboa... |
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 ... |
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 ... |
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 exc... |
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 modu... |
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 ho... |
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 pa... |
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 ... |
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 m... |
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 ... |
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 appl... |
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 excep... |
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 s... |
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... |
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 u... |
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... |
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 mor... |
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 director... |
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 elemen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.