DekGenius.com
[ Team LiB ] Previous Section Next Section

11.2 Common Coding Gotchas

Before the programming exercises for this part of the book, here are some of the most common mistakes beginners make when coding Python statements and programs. You'll learn to avoid these once you've gained a bit of Python coding experience; but a few words might help you avoid falling into some of these traps initially.

  • Don't forget the colons. Don't forget to type a : at the end of compound statement headers (the first line of an if, while, for, etc.). You probably will at first anyhow (we did too), but you can take some comfort in the fact that it will soon become an unconscious habit.

  • Start in column 1. Be sure to start top-level (unnested) code in column 1. That includes unnested code typed into module files, as well as unnested code typed at the interactive prompt.

  • Blank lines matter at the interactive prompt. Blank lines in compound statements are always ignored in module files, but, when typing code, end the statement at the interactive prompt. In other words, blank lines tell the interactive command line that you've finished a compound statement; if you want to continue, don't hit the Enter key at the ... prompt until you're really done.

  • Indent consistently. Avoid mixing tabs and spaces in the indentation of a block, unless you know what your text editor system does with tabs. Otherwise, what you see in your editor may not be what Python sees when it counts tabs as a number of spaces. It's safer to use all tabs or all spaces for each block.

  • Don't code C in Python. A note to C/C++ programmers: you don't need to type parentheses around tests in if and while headers (e.g., if (X==1):); you can if you like (any expression can be enclosed in parentheses), but they are fully superfluous in this context. Also, do not terminate all your statements with a semicolon; it's technically legal to do this in Python as well, but is totally useless, unless you're placing more than one statement on a single line (the end of a line normally terminates a statement). And remember, don't embed assignment statements in while loop tests, and don't use { } around blocks (indent your nested code blocks consistently instead).

  • Use simple for loops instead of while or range. A simple for loop (e.g., for x in seq:) is almost always simpler to code, and quicker to run than a while or range-based counter loop. Because Python handles indexing internally for a simple for, it can sometimes be twice as fast as the equivalent while.

  • Don't expect results from functions that change objects in-place . In-place change operations like the list.append( ) and list.sort( ) methods of Chapter 6 do not return a value (other than None); call them without assigning the result. It's not uncommon for beginners to say something like mylist=mylist.append(X) to try to get the result of an append; instead, this assigns mylist to None, rather than the modified list (in fact, you'll lose a reference to the list altogether).

    A more devious example of this pops up when trying to step through dictionary items in sorted fashion. It's fairly common to see this sort of code: for k in D.keys( ).sort( ):. This almost works: the keys method builds a keys list, and the sort method orders it—but since the sort method returns None, the loop fails because it is ultimately a loop over None (a nonsequence). To code this correctly, split the method calls out to statements: Ks = D.keys( ), then Ks.sort( ), and finally for k in Ks:. This, by the way is one case where you'll still want to call the keys method explicitly for looping, instead of relying on the dictionary iterators.

  • Always use parenthesis to call a function. You must add parentheses after a function name to call it, whether it takes arguments or not (e.g., use function( ), not function). In Part IV, we'll see that functions are simply objects that have a special operation—a call, that you trigger with the parentheses.

    In classes, this seems to occur most often with files. It's common to see beginners type file.close to close a file, rather than file.close( ); because it's legal to reference a function without calling it, the first version with no parenthesis succeeds silently, but does not close the file!

  • Don't use extensions or paths in imports and reloads. Omit directory paths and file suffixes in import statements (e.g., say import mod, not import mod.py). (We met module basics in Chapter 6, and will continue studying them in Part V.) Because modules may have other suffixes besides .py (a .pyc, for instance), hardcoding a particular suffix is not only illegal syntax, it doesn't make sense. And platform-specific directory path syntax comes from module search path settings, not the import statement.

    [ Team LiB ] Previous Section Next Section