Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Question 1

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)

def main():
num = int(input("Enter a number: "))
if num > 0:
countdown(num)
elif num < 0:
countup(num)
else:
print("Blastoff!")

if __name__ == "__main__":
main()

For an input of zero, both functions countdown and countup will result in
printing "Blastoff!" since they both check for values less than or equal to zero.
Therefore, the choice of which function to call for an input of zero is arbitrary.
In this implementation, I chose to call countdown, but you could choose
countup as well, as both functions produce the same output for zero.

Question 2

Handle the division by zero error

def divide_numbers():
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if num2 == 0:
raise ZeroDivisionError("Error: Division by zero is not allowed")
result = num1 / num2
print("Result of division:", result)
except ValueError:
print("Error: Please enter valid numbers")
except ZeroDivisionError as e:
print(e)

divide_numbers()

Output demonstrating the runtime error, including the error message :

Enter the first number: 5


Enter the second number: 0
Error: Division by zero is not allowed

Error handling is crucial in programming to gracefully manage unexpected


situations or errors that may occur during the execution of a program. In the case
of division by zero, if this error is not handled properly, it can lead to program
termination or unexpected behavior, potentially causing data loss or incorrect
results.
By implementing error handling techniques like try-except blocks, developers
can anticipate potential errors and provide appropriate responses or fallback
mechanisms. In the division by zero scenario, error handling allows the program
to detect when the denominator is zero and handle this situation gracefully, such
as by displaying an informative error message to the user.
Failure to handle the division by zero error can lead to various negative
consequences, including:
1. Program termination: Without error handling, encountering a division by
zero error would cause the program to crash abruptly, leading to a poor
user experience and potential loss of unsaved data.
2. Incorrect results: If the division by zero error is not caught and handled,
the program may continue execution with incorrect results, leading to
inaccurate computations and potentially misleading output.
3. Poor user experience: Failing to handle errors properly can confuse users
and erode trust in the software. Users expect programs to handle errors
gracefully and provide informative feedback to help them understand and
resolve issues.

You might also like