Analogies are often the best tools to connect a program’s “functional logic” with the “abstract tools” of the programming language. Here, we outline the logical differences between common if-statement structures using a “Driving Analogy” drawn in parallel to a “Flow-Chart” and “Model Python Code.” We choose Python because it is one of the most intuitive and commonly used programming languages in biology.
IF-IF STATMENTS: choose any “pit-stops” or none
In our first example, we use “a car which has enough time to choose any available pit-stops” to model “sequential if-statements” in Python code. Here, each pit-stop/if-statement is ordered sequentially and any number of options can be chosen if they fit the “if” test/criteria. An outline of the code structure follows:
- lines 11-12: user inputs fuel-guage reading and stomach fullness info for if-statements tests
- lines 13: if gas tank is less than 25% full then take gas-station pitstop
- lines 14: calculate “empty percentage” of tank from “full percentage”
- lines 15: caculated/buy exact “gas needed” by multiplying “tank volume” by “empty percentage”
- lines 16: refill/redefine gas tank with “gas needed”
- lines 17-20: very similar logic/calculations to 13-16
IF-EIF STATMENTS: choose one “pit-stop” or none
In our second example, we use “a car which only has time to visit one pit-stop” to model “if-eif statements” in Python code. As shown in the “driving analogy,” functionally, you can only choose one pit-stop/option even though if and eif statements are ordered sequentially in the “flow-chart” and “Python code.” Here, aside form replacing the second “if” with an “eif” the code is identical to the code in the first example.
IF-ELSE STATMENTS: choose “detour”(if) or “default”(else)
In our third example, we use “a car which might need to take a detour due to inclement weather” to model “if-else statements” in Python code. As shown in the “driving analogy”, the else-statement reflects the default path and the if-statement reflects a detour which is taken under special circumstances (defined by the if test). An outline of the code structure follows:
- lines 51-53: user inputs “speed limit,” “snow height,” and “rain height” info needed
- lines 54: if snow height is greater than 6 inches or rain height is greater than 12 inches take detour
- lines 55: take detour by turning car west
- lines 56: take detour by adjust speed to speed limit
- lines 57: if you don’t take detour
- lines 58: take default by turning car south
- lines 59: take default but slow car speed by amount of rain on the road
REFERENCES:
- Shapiro, B.E. Scientific Computation: Python Hacking for Math JunkiesSherwood Forest Books 2015
- Horstmann, C.; Necaise, R.D. Python for Everyone Wiley 2014
This work by Eugene Douglass and Chad Miller is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.