I l@ve RuBoard |
Before we turn you lose on some programming exercises, we'd like to point out some of the most common mistakes beginners seem to make when coding Python statements and programs. You'll learn to avoid these once you've gained a bit of Python coding experience (in fact, Mark commonly gets into trouble because he uses Python syntax in C++ code!); but a few words might help you avoid falling into some of these traps initially.
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.
We mentioned this in Chapter 1, but as a reminder: 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 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 Return key at the ... prompt until you're really done.
Avoid mixing tabs and spaces in indentation, unless you're sure what your editor 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.
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): print X), but you can if you like; any expression can be enclosed in parentheses. And remember, you can't use { } around blocks; indent nested code blocks instead.
Another reminder: in-place change operations like the list.append() and list.sort() methods in Chapter 2 don't return a value (really, they return None ); call them without assigning the result. It's common for beginners to say something like list=list.append(X) to try to get the result of an append; instead, this assigns list to None, rather than the modified list (in fact, you'll lose a reference to the list altogether).
Two final reminders: you must add parentheses after a function name to call it, whether it takes arguments or not (e.g., function(), not function), and you shouldn't include the file suffix in import statements (e.g., import mod, not import mod.py). In Chapter 4, we'll see that functions are simply objects that have a special operation—a call you trigger with the parentheses. And in Chapter 5, we'll see that modules may have other suffixes besides .py (a .pyc, for instance); hard-coding a particular suffix is not only illegal syntax, it doesn't make sense.
I l@ve RuBoard |