Unit 3: Programming Assignment: Conditionals and Recursion
BUS 3305-01 Business Law and Ethics - AY2025-T5
Question 1: Recursive Countup and Countdown Function
Explanation
Recursive functions are valuable programming resources, particularly for problems
involving repetitive or sequential logic. A good example is the countdown function in Think
Python (Downey, 2015), which is a model of recursion where a function continues to call
itself with a modified argument until a base case is reached.
Along with countdown, we have a countup function. While countdown operates on
positive numbers by decrementing to zero, countup operates on negative numbers by
incrementing to zero. Both have uses of conditional statements and recursion in controlling
flow.
For symmetry, if we input zero, we prefer to invoke the countdown function directly
because it leads directly to the base case (n <= 0) and prints out "Blastoff!". The option
avoids unnecessary branching in the code and follows the textbook example (Downey, 2015,
p. 46).
Code: countup and countdown
Output Examples
Input: 3
Input: -3
Input: 0
Question 2: Handling Division by Zero in Python
Explanation
Division by zero is also one of the most common runtime programming faults. If left
unhandled, it causes program crash, hence leading to an inferior quality of user experience
and even system crash. This necessitates error handling through techniques such as try-except
blocks.
In Python, attempting to divide an integer by zero raises a ZeroDivisionError. These
endless exceptions can be put in such a "try" block, and, in case they occur, the program
gracefully responds with an error message rather than crashing.
Proper error handling is even more important for user interface programs and
applications that manipulate critical data. If left unhandled, it can cause data loss, strange
behavior, or security holes (Downey, 2015, p. 52).
Code: Division with Error Handling
Runtime Error Demonstration (Without Handling)
Code Without Try-Except:
Input:
Output:
Traceback (most recent call last):
File "division.py", line 3, in <module>
result = numerator / denominator
ZeroDivisionError: float division by zero
Significance of Error Handling
Division by zero cases probably best exemplify a great need for error handling in
programming. Left unhandled, these errors will cause abrupt termination of the execution,
something that is unacceptable in production. In foreseeing scenarios that may arise and using
structured exception handling, programmers make software more reliable, usable, and
maintainable.
Clear error messages help the user understand what went wrong and how to fix it,
thereby creating a better user experience. According to Downey (2015), programming is act
of dealing with inputs that are correct and those that are not, and steering the flow of the
program accordingly.
Reference
Downey, A. (2015). Think Python: How to think like a computer scientist. Green Tree Press.