top of page

07.26.2018: One Lesson of Python

Today's soundtrack is Phil Joel: The New Normal.

This afternoon, I'm working on the third chapter of Al Sweigart's Automate the Boring Stuff With Python, "Functions."

A function lets us define a series of code one time and then automatically run that code any time we want. We start by defining the name of the function, then we run the function by "calling" the code (typing out its name wherever we want it to run). Sweigart says that "[a] major purpose of functions is to group code that gets executed multiple times" (source). Functions can also help us when debugging, because if we've typed the same piece of code a bunch of times and find we need to fix something, we need to manually go through and fix every instance of the broken code. If, however, we've used functions, all we need to do is fix the function.

We can set up functions to accept different inputs in a standardized way. An example that Sweigart gives is that we can set up a function to say hello to a user; we can input the user name, and the function will run, saying hello to the name of the user. This way we can use functions to streamline the part of the code that will be the same every time, while letting us customize certain aspects of the code.

To prevent a new line from being inserted each time we print something, we can use the "end" keyword argument.

There are two kinds of variables: local and global. Global variables apply to the entire program; local variables are only considered within the context of the function that the variable runs within. Sweigart makes an important note: "Code in the global scope cannot use any local variables. However, a local scope can access global variables" (source), though they cannot access local variables from other functions.

To prevent Python from crashing entirely when it runs into an error, we can use a kind of elif statement, called "'try' and 'except'," where if we foresee the possibility of running into a specific error, we can tell the program to print an error message if it does generate an error, rather than crashing.

bottom of page