Debugging Complex Expressions
For more information on concepts covered in this lesson, you can check out:
00:00 Debugging. Arguably, one of the best use cases for the walrus operator is when debugging complex expressions. Let’s say you want to find the distance between two locations along the earth’s surface. One way to do this is to use the haversine formula, which is seen onscreen. Here, ϕ (phi) represents the latitude, and λ (lambda) represents the longitude of each location. To demonstrate this formula, you can calculate the distance between Oslo and Vancouver.
01:33 As you can see, the distance between the two cities is just under 7,200 kilometers. Note that Python source code is typically written using UTF-8 Unicode, and this allows you to use Greek letters such as ϕ and λ in your code.
01:51 This Wikipedia page shows some alternatives for using Unicode on your system, and the included course files contain the characters if you want to copy and paste them into your REPL.
02:03 Let’s say you need to double-check your implementation and want to see how much the haversine terms contribute to the final result. You could copy and paste the term from your main code to evaluate it separately. However, you could also use the walrus operator to give a name to the subexpression you’re interested in.
03:03
The advantage of using the walrus operator here is that you calculate the value of the full expression and keep track of the value ϕ_hav
at the same time.
03:13 This allows you to confirm that you didn’t introduce any errors while debugging.
03:19 Now that you’ve seen the walrus operator in action in a debugging context, next you’ll see it being used with lists and dictionaries.
Become a Member to join the conversation.