Python statements and syntax
Chapters 10 and 11 in Learning Python, 5th edition are the first in section 3, "Statements and Syntax."
"[Y]ou can make a single statement span across multiple lines. To make this work, you simply have to enclose part of your statement in a bracketed pairāparentheses (()), square brackets ([]), or curly braces ({}). Any code enclosed in these constructs can cross multiple lines ... Parentheses are the catchall device ..." p. 32
"An older rule also allows for continuation lines when the prior line ends in a backslash ... This alternative technique is dated, though, and is frowned on today because itās difficult to notice and maintain the backslashes." (my bold)
Introducing the try statement:
while True: reply = raw_input('Enter text: ') if reply == 'stop': break try: num = int(reply) except: print 'Bad! ' * 8 else: print num ** 2 print 'Bye'
Chapter 10 is quite short! Just if, while, and try statements.
Assignments, expressions, and print are covered in chapter 11.
"Tuple assignment leads to a common coding trick in Python":
>>> nudge = 'NUDGE' >>> wink = 'WINK' >>> nudge, wink = wink, nudge >>> nudge 'WINK' >>> wink 'NUDGE'
"[W]e must generally have the same number of items on the right as we have variables on the left" -- not surprising, but this is an example of how clearly this book explains most things.
This is funky -- I had to think it out (p. 344):
>>> L = [1, 2, 3, 4] >>> while L: ... front, L = L[0], L[1:] ... print(front, L) ... 1 [2, 3, 4] 2 [3, 4] 3 [4] 4 []
Reserved words: "because module names in import statements become variables in your scripts, variable name constraints extend to your module filenames too."
Note: Names that begin with a single underscore (_X) are NOT imported by a "from module import xyz" statement.
(Python filenames may begin with an underscore.)
Expression statements: Expressions are commonly used as statements in two situations:
calls to functions and methods For functions and methods that do not return a value.
printing values at the interactive prompt i.e. in Terminal, we don't need to write "print."
"[A]lthough expressions can appear as statements in Python, statements cannot be used as expressions."
The rest of chapter 11 is about the print statement, with thorough coverage for both Python 3.x and 2.x (yay!). This is a simple thing:
print x, y # adds space between print x + y # no space
"[W]hereas file write methods write strings to arbitrary files, print writes objects to the stdout stream by default, with some automatic formatting added." p. 358











