12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Expression Statements and In-Place ChangesThis brings up a mistake that is common in <strong>Python</strong> work. Expression statements areoften used to run list methods that change a list in-place:>>> L = [1, 2]>>> L.append(3) # Append is an in-place change>>> L[1, 2, 3]However, it’s not unusual for <strong>Python</strong> newcomers to code such an operation as anassignment statement instead, intending to assign L to the larger list:>>> L = L.append(4) # But append returns None, not L>>> print L # So we lose our list!NoneThis doesn’t quite work, though—calling an in-place change operation such asappend, sort, orreverse on a list always changes the list in-place, but these methodsdo not return the list they have changed.In fact, they return the None object. If you assign such an operation’s result back tothe variable name, you effectively lose the list (and it is probably garbage collected inthe process!).So, don’t do this. We’ll revisit this phenomenon in the “Common Coding Gotchas”warnings section at the end of this part of the book because it can also appear in thecontext of some looping statements we’ll meet in later chapters.print StatementsThe print statement prints things—it’s simply a programmer-friendly interface tothe standard output stream. Technically, it converts an object to its textual representation,and sends this to standard output.The standard output stream is the same as the C language’s stdout; it is usuallymapped to the window where you started your <strong>Python</strong> program (unless redirected toa file or pipe in your system’s shell).In Chapter 9, we looked at some file methods that write text. The print statement issimilar, but more focused: print writes objects to the stdout stream (with somedefault formatting), but file write methods write strings to arbitrary files. Because thestandard output stream is available in <strong>Python</strong> as the stdout object in the built-in sysmodule (i.e., sys.stdout), it’s possible to emulate print with file writes, but print iseasier to use.Table 11-5 lists the print statement’s forms.print Statements | 229

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

Saved successfully!

Ooh no, something went wrong!