Assignment 3
Assignment 3
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown(n - 1)
def countup(n):
if n >= 0:
print(n)
countup(n + 1)
else:
print('Blastoff!')
if user_input > 0:
countdown(user_input)
countup(user_input)
else:
We have two functions, countdown and countup, both of which are recursive. countdown counts
down from a positive number until it reaches 0 or below, printing "Blastoff!" at the end. countup
counts up from a negative number until it reaches 0 or above, also printing "Blastoff!" at the end.
We use input to get a number from the user, which is stored in the user_input variable.
We then use conditional statements to decide which function to call based on the value of
user_input:
If user_input is zero, we choose to call countdown (but you could choose countup as well; the
choice is somewhat arbitrary).
The program executes the chosen function, producing the respective output based on the user's
input.
Blastoff!
-3
-2
-1
Blastoff!
For zero:
Blastoff!
Question 2:
try:
if math.isnan(result):
print(f"Result: {result}")
except ZeroDivisionError as e:
except ValueError as e:
print(f"Error: {e}")
except Exception as e:
We use a try...except block to capture potential exceptions that may occur during the program's
execution.
We get two numbers from the user, the numerator and the denominator.
If there is any other exception (which would be unexpected), we catch it with the generic
Exception class and print a general error message.
By intentionally introducing the division by zero error, this program demonstrates the
importance of error handling. Junior developers can learn how to identify different types of
errors and implement appropriate error-handling techniques to gracefully handle exceptional
cases. The program also provides clear error messages to help users understand and correct their
input mistakes.