What I Learned In Python This Week #4-5 (Part II): Conditionals, Loops, And Some Other Stuff

Tools I Used:

  • Geany
    • Still my favorite mini-IDE!
  • Python shell / bash shell
    • I use the Python shell to learn functions interactively, and the bash shell to execute the scripts I write (though I now use Geany’s F5 shortcut more often).

Accomplishments:

  • No new code, but cleaned up much of my old code and added some new features

Functions/Concepts I Learned:

  • Assignments
    • You can use sequences together with assignments to speed things up (e.g., instead of x = 1, y = 2, z = 3, etc. you can use x, y, z = 1, 2, 3).
    • You can also chain together assignments (e.g., x = y = z = foo()), which as far as I can tell makes each assignment point to the same exact thing in memory (kinda like a hard link).
    • Augmented assignments are a shorthand that let you simultaneously perform operations on an assigned value (e.g., instead of x = x + 2 you could use x += 2, which is rather easier on the eyes).
  • Blocks are Python’s way of both making you indent neatly, but also to assign subroutines in your code. Instead of a foo { ... code ... }-style subroutine/block, Python makes you type foo:, then type the subroutine/block underneath foo:, indenting each line of by (canonically) four extra spaces. You can also nest multiple levels of subroutines/blocks. This looks much neater than I make it sound.
  • Conditionals
    • Booleans are the core of conditional statements in Python. False, None, 0, and empty containers ("", [], {}, ()) are all considered false, and every other value is true. You can use bool() to explicitly convert a value to a Boolean True/False, but since Python lets you use any value as a Boolean, you will rarely (if ever) need it.
    • if foo: executes its code block only if the Boolean value of foo is True, otherwise its code block is skipped.
    • else: executes if no other condition activates. It is useful for things like catching errors, specifying default behaviors, or providing a response when nothing else would trigger an end to your loop.
    • elif bar: works like both else and if, because it lets you specify conditions for executing an else clause.
    • There are multiple comparison operators to use for those else/if/elif clauses! They are as follows: ==, <, >, <=, >=, !=, is, is not, in, and not in. Note: == is not equivalent to is! == means equal in value; is means referring to the exact same object (points to the same spot in memory).
    • assert lets you crash your program at a point you want to, which is useful for debugging at the earliest point of failure. It’s sort of like an if with attitude. You can pass a custom crash message as well (e.g., assert 0 < slices < 8, "Need a realistic number of pie slices").
  • Loops
    • Loops let you run portions of your program (or even the whole program) multiple times until the conditions of your choosing are met.
    • while lets you loop parts of a program while any condition is true.
    • for lets you loop parts of a program when a specific condition is true. This is useful for things like iterating over dictionaries. You can also dynamically generate lists using for loops (e.g., [x + x for x in range(10)] results in [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]).
    • range() is a function that automagically generates a range of numbers. xrange() functions similarly, but creates the numbers one at a time, rather than all at once as in range().
    • zip() combines items in a pair of lists and returns them as a tuple.
    • enumerate() lets you easily iterate over a string without having to manually specify index numbers.
    • break lets you choose a point to break out of a loop. while True/break is a common Python-ism that lets you have a continually executing loop until no input is provided (or so goes my understanding). The frequent use of break can make reading loop code difficult, but this idiom is an acceptable use of break.
    • continue lets you skip the rest of the loop like break, but unlike break, continue then returns you to the beginning of the same loop for the next iteration. Usually if works just as well.
    • pass does nothing in itself, but is a useful placeholder for code you haven’t yet written (so the program doesn’t throw an error).
  • del removes the name of an object (which automatically removes the value of the object as well, so long as no other object names refer to it).
  • exec lets a user enter a string that is executed as Python code. eval lets a user enter a string that is evaluated as a expression and returned. These are both potential security risks, but are also potentially useful.

I celebrated my 24th birthday yesterday, so this post is later than I expected — my wife planned ahead to get the day off for me as a surprise, and as a further surprise had my friend Mike come over to visit. I do feel loads better after an extra day off, and I plan to get right back into the swing of things.

There is certainly a lot about conditionals/loops/etc. in this chapter that I need to digest, but I think I may just run more quickly through Hetland several times in a row rather than once through slowly. I’ve been finding that after awhile, I run out of obvious (or useful) ideas of what to code with the concepts I’ve learned before I fully grasp all the details of how they are used.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s