pythonweek3
pythonweek3
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:
# For input of zero, I chose to call countdown function,
# as it counts down to zero and then prints "Blastoff!"
countdown(num)
if __name__ == "__main__":
main()
Output for respective inputs:
1. Positive number:
When the user inputs the positive number 5, the program initiates the countdown
function. Initially, since 5 is greater than 0, the program proceeds to the else block within
the countdown function. It prints the current value of 5 and then recursively calls
countdown(4). Inside this recursive call, the process repeats: it prints 4 and then calls
countdown(3). This recursive chain continues until the argument reaches 0. At this point,
the function prints "Blastoff!" and returns, causing the program to unwind the recursion.
Finally, the program exits from the recursive calls, leading to the output "5 4 3 2 1
Blastoff!", as it counts down from 5 to 1 and then prints "Blastoff!" when it reaches zero.
2 Negative number:
When the user inputs the negative number -6, the program calls the countup function. Since
-6 is less than 0, the program enters the else block within the countup function. It prints the
current value of -6 and then recursively calls countup(-5). Inside this recursive call, the
process continues: it prints -5 and then calls countup(-4). This recursive chain persists until
the argument reaches 0. At this juncture, the function prints "Blastoff!" and returns, causing
the program to unwind the recursion. Finally, the program exits from the recursive calls,
resulting in the output "-6 -5 -4 -3 -2 -1 Blastoff!". In this manner, it counts up from -6 to -1
and then prints "Blastoff!" when it reaches zero.
3. Zero:
Explanation of choice for input of zero: I chose to call the countdown function for input of zero
because it fits the natural progression of counting down from a positive number to zero and then
printing "Blastoff!". This maintains consistency with the behavior of the countdown function.
Alternatively, one could choose to call the countup function for zero as well, as counting up
from zero also eventually leads to "Blastoff!". However, I decided to stick with the countdown
approach for zero for simplicity and consistency with the original function's behavior.
Q 2: code
def divide_numbers(a, b):
if b == 0:
raise ZeroDivisionError("Error: Division by zero is not allowed")
return a / b
def main():
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = divide_numbers(num1, num2)
print("Result of division:", result)
except ZeroDivisionError as e:
print(e)
if __name__ == "__main__":
main()
Output: