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.

Quiz Answers1. The output here is 'Spam', because the function references a global variable inthe enclosing module (because it is not assigned in the function, it is consideredglobal).2. The output here is 'Spam' again because assigning the variable inside the functionmakes it a local and effectively hides the global of the same name. The printstatement finds the variable unchanged in the global (module) scope.3. It prints 'NI' on one line, and 'Spam' on another because the reference to the variablewithin the function finds the assigned local, and the reference in the printfinds the global.4. This time it just prints 'NI' because the global declaration forces the variableassigned inside the function to refer to the variable in the enclosing global scope.5. The output in this case is again 'NI' on one line, and 'Spam' on another becausethe print statement in the nested function finds the name in the enclosing function’slocal scope, and the print at the end finds the variable in the global scope.6. The output here is "1564": 1 matches a by position, 5 and 6 match b and c by*name positionals (6 overrides c’s default), and d defaults to 4 because it was notpassed a value.7. Although the values of local variables go away when a function returns, stateinformation can be retained by a <strong>Python</strong> function by using global variables,enclosing function scope references in nested functions, or default argument values.Another alternative, using OOP with classes, supports state retention betterthan any of the prior three techniques because it makes it explicit with attributeassignments.8. Functions can send back results with return statements, by changing passed-inmutable arguments, and by setting global variables. Globals are generallyfrowned upon (except for very special cases, like multithreaded programs)because they can make code harder to understand and use. return statementsare usually best, but changing mutables is fine, if expected. Functions may alsocommunicate with system devices such as files and sockets, but these are beyondour scope here.Chapter Quiz | 343

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

Saved successfully!

Ooh no, something went wrong!