As programmers, we continuously read, modify, and add to our programs. We want our code to work, but we also want our code to be easy to work with. Otherwise, every change we make takes time and risks bugs.
Fortunately, the programming community has developed design patterns to recommend best practices for structuring programs. We can apply these reusable solutions to make our code easier to understand, modify, and debug!
Referencing a value in multiple places
Programs may use a value in several different places. We can hardcode that value by just typing it into every place we need it, but if we want to change that value later, we now have to find every place we typed "Shakira" and update it.
print("You're listening to Shakira")
print("----------")
print("> Shakira official playlist")
print("> Featuring Shakira")
print("Shakira has 31,234,123 monthly listeners")
Instead, we can store the artist in a variable and access that variable everywhere we use the artist name. To change the artist later, we only need to update the assignment statement on line 1 and assign artist a new value. When we re-run the program, the rest of the output updates with it!
Press the Run button to execute the program below. On line 1, change "Shakira" to a different value, and run the program again. How does the console output change?
[[โ python-program 6]]
Reusing a result
Programs often need to use the result of an operation in multiple places. We can repeat the calculation everywhere we need its result, but if we want to change the calculation later, we need to remember to update every location. If we forget one, we now have a hard-to-find bug where our results are out-of-sync!
print("Subtotal (including fees):")
print(41.89 + 41.89 + 41.89 + 2.95 + 3.25 + 3.25 + 3.25)
print("----------")
print("Ticket price x3:")
print(41.89 + 41.89 + 41.89)
print("Venue fee x3:")
print(3.25 + 3.25 + 3.25)
print("Order processing fee:")
print(2.95)
Instead, we can do the calculation once and store the result in a variable. Then, the computer can access the result anywhere it needs it. We also save the computer time by avoiding redundant calculations. For example, it can take the computer a few seconds to add a few million numbers, so doing that calculation one time versus three times is much more efficient!
Press the Run button to execute the program below. On line 1, update the calculation to use a ticket price of $47 instead of $41.89, and run the program again. How do the totals change?
[[โ python-program 4]]
Generalizing code
In programming, we want to develop generalized solutions. Maybe we need search results for the term 'python' right now, but our program will be a lot more useful later if it can return search results for any search term. Then, we've not only solved for a single specialized problem, we've solved for a whole class of similar problems.
print("Your search results are at:")
print("https://www.khanacademy.org/search?page_search_query=python&content_kinds=Video")
The program below better generalizes our code to work for any search term. We make the search term a variable and access its value when we construct the URL. To change the search term later, we don't need to re-understand all of the code and figure out which part of the URL string corresponds to the search term. We can just assign a different value to search_term and move on!
Press the Run button to execute the program below. On line 1, replace "python" with a different search term, and run the program again. How does the final URL change?
[[โ python-program 7]]
Naming variables
Computers don't understand English, so the actual variable names don't mean anything to them. The computer doesn't care if we name every variable like x1 and x2, or if we store the oldest post in the variable newest_post and the newest post in the variable oldest_post.
Humans, however, also read programs! For our benefit, a variable name should describe the purpose of that variable, so we can easily understand how it fits into the program.
Naming rules
In Python, variable names must follow a few rules.
- Names can contain only letters, numbers, and underscores.
- Names cannot start with a number.
- Names are case-sensitive.
- Names cannot be Python keywords, like
printorfloat.
By convention, we format Python variable names in snake case. We use all lowercase letters and separate words with underscores, like volume or high_score.
๐ Look out!
If we access a variable that doesn't exist, we get a NameError. This is a type of runtime error, because the computer only realizes it's stuck when it tries to find the name in its short-term memory and can't.
NameErrors are often the result of a typo in the variable name. They also happen if we access a variable before it's defined. The first assignment to that variable must execute before any lines of code that access it.
Press the Run button to execute the program below. What error do you see? Use the linter and error messages to debug and fix the NameErrors.
[[โ python-program 1]]
[[โ explanation 1]]