12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

A.2. Runtime errors 197A.2 Runtime errorsOnceyourprogramissyntacticallycorrect,<strong>Python</strong>cancompileitandatleaststartrunningit. Whatcould possibly gowrong?A.2.1 Myprogram doesabsolutelynothing.Thisproblemismostcommonwhenyourfileconsistsoffunctionsandclassesbutdoesnotactuallyinvoke anything to start execution. This may be intentional if you only plan to import this moduletosupply classes and functions.If it is not intentional, make sure that you are invoking a function to start execution, or execute onefrom theinteractive prompt. Alsoseethe“Flow of Execution” section below.A.2.2 Myprogram hangs.Ifaprogramstopsandseemstobedoingnothing,itis“hanging.” Oftenthatmeansthatitiscaughtinan infiniteloop or infinite recursion.• Ifthereisaparticularloopthatyoususpectistheproblem,addaprintstatementimmediatelybefore the loop that says “entering the loop” and another immediately after that says “exitingthe loop.”Run the program. If you get the first message and not the second, you’ve got an infinite loop.Go tothe“Infinite Loop” section below.• Most of the time, an infinite recursion will cause the program to run for a while and thenproduce a “RuntimeError: Maximum recursion depth exceeded” error. If that happens, go tothe “Infinite Recursion” section below.If you are not getting this error but you suspect there is a problem with a recursive method orfunction, you can stillusethe techniques inthe“Infinite Recursion” section.• If neither of those steps works, start testing other loops and other recursive functions andmethods.• Ifthatdoesn’twork,thenitispossiblethatyoudon’tunderstandtheflowofexecutioninyourprogram. Gotothe“Flow of Execution” section below.Infinite LoopIf you think you have an infinite loop and you think you know what loop is causing the problem,add a print statement at the end of the loop that prints the values of the variables in the conditionand the value of the condition.For example:while x > 0 and y < 0 :# do something to x# do something to yprint "x: ", xprint "y: ", yprint "condition: ", (x > 0 and y < 0)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!