Programming Assignment: Conditionals and Recursion
Question 1: Recursive Countdown and Countup Functions
Code Implementation
The following Python program prompts the user for a number and calls
either countdown() (for positive numbers) or countup() (for negative
numbers).
def countdown(n):
if n <= 0:
print("Blastoff!")
else:
print(n)
countdown(n - 1)
def countup(n):
if n >= 0:
print("Blastoff!")
else:
print(n)
countup(n + 1)
# Get user input
num = int(input("Enter a number: "))
# Determine which function to call
if num > 0:
countdown(num)
elif num < 0:
countup(num)
else:
countdown(num) # Default choice for zero
Output:
Positive Input (e.g., 3):
Enter a number: 3
3
2
1
Blastoff!
Process finished with exit code 0
Negative Input (e.g., -4):
Enter a number: -4
-4
-3
-2
-1
Blastoff!
Process finished with exit code 0
Zero Input:
Blastoff!
Explanation for Zero Input Handling
For an input of zero, the program calls countdown() by default. This choice is
logical because zero is neither positive nor negative,
and countdown() naturally terminates when n <= 0. Since zero meets this
condition immediately, it prints "Blastoff!" without further recursion.
Question 2: Handling Division by Zero Error
Code Implementation
The following program demonstrates error handling for division by zero:
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = num1 / num2
print(f"The result of division is: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed!")
Output Demonstrating Runtime Error
If the user enters 5 and 0, the output without error handling would be:
Enter the first number: 5
Enter the second number: 0
Error: Division by zero is not allowed!
Process finished with exit code 0
Significance of Error Handling
Error handling prevents programs from crashing when unexpected conditions
arise. In this case, division by zero is mathematically undefined, so
attempting it in Python raises a ZeroDivisionError. Without handling, the
program terminates abruptly, which is undesirable in real-world applications.
Potential Impacts of Not Handling Errors:
Program Crashes: The application stops working, leading to a poor
user experience.
Unpredictable Behavior: Subsequent code may fail if dependent on
the division result.
Security Risks: In some cases, unhandled errors expose system
details, aiding malicious attacks.
By using try-except blocks, developers can gracefully manage errors, provide
meaningful feedback, and ensure program stability.
References
Downey, A. (2015). Think Python: How to think like a computer scientist (2nd
ed.). Green Tea
Press. https://greenteapress.com/thinkpython2/thinkpython2.pdf
kjdElectronics. (2017, June 9). *Python beginner tutorial 5 - Booleans and
conditionals* [Video]. YouTube. https://youtu.be/E4wbrwDpnIg