Programming Assignment Unit 3
Programming Assignment Unit 3
Assignment Instructions:
In this unit, we explored the overview of the Conditionals and Recursion, which are the prime
requirements for the decision control process in a program. Before completing this assignment,
review the reading material below:
Q 1. The following is the countdown function copied from Section 5.8 of your textbook.
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown(n-1)
Write a new recursive function countup that expects a negative argument and counts “up” from
that number. Output from running the function should look something like this:
>>> countup(-3)
-3
-2
-1
Blastoff!
Write a Python program that gets a number using keyboard input. (Remember to use input for
Python 3 but raw_input for Python 2.)
If the number is positive, the program should call countdown. If the number is negative, the
program should call countup. Choose for yourself which function to call (countdown or countup)
for input of zero.
Provide the following.
The code of your program.
Respective output for the following inputs: a positive number, a negative number, and
zero.
An explanation of your choice for what to call for input of zero.
Answer of Q1:
Code:
import time
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
time.sleep(1) # Pause for one second
countdown(n - 1)
def countup(n):
if n >= 0:
print('Blastoff!')
else:
print(n)
time.sleep(1) # Pause for one second
countup(n + 1)
def main():
try:
num = int(input("Enter a number: "))
if num > 0:
countdown(num)
elif num < 0:
countup(num)
else:
print("Input is zero. Let's just blast it now ^^.")
countdown(num)
Explanation:
The following Python code defines two functions, countdown and countup, which perform a
countdown and a countup, respectively, from a given integer down to zero (or vice versa). Here
is a step-by-step explanation of how it works:
The time module is used to introduce a one-second delay between each successive count via the
function time.sleep(1).
This function accepts an integer n as input and executes a countdown sequence from n down to
zero.
If n is less than or equal to zero, it prints "Blastoff!" to signal the end of the countdown.
If n is greater than zero, it prints the current value of n, pauses for one second, and then
recursively calls itself with n - 1 to continue the countdown.
This function does the opposite of countdown. It counts up from a given number n to zero (or
from zero to n if n is negative).
If n is greater than or equal to zero, it prints "Blastoff!" to indicate the end of the countup.
If n is less than zero, it prints the current value of n, pauses for one second, and then calls itself
recursively with n + 1 to proceed with the countup.
4. The Principal Function:
The main function allows the user to interact with the program. It asks the user to input a
number:
If the input number is more than zero, it starts a countdown with countdown(num).
If the input number should be smaller than zero a countup is started with the function
countup(num).
If the input number is precisely zero, it prints "Input is zero. Let's blast it now." and then calls
countdown(num).
The conditional expression if __name__ == "__main__": checks if the script is being run as the
main program.
Fundamentally, this code provides an interactive way of counting up or down from a specified
number. The one-second pause adds an element of drama. Depending on the user's input, it will
call either the countdown or countup function to perform the right action.
References: Think Python: How to Think Like a Computer Scientist, Chapter 5, Section
5.8 (Recursion)
Q 2. You are developing a program that performs a division operation on two numbers provided
by the user. However, there is a situation where a runtime error can occur due to a division by
zero. To help junior developers learn about error handling in expressions and conditions, you
want to create a program deliberately containing this error and guide them in diagnosing and
fixing it.
Instructions:
Create a Python program that prompts the user to enter two numbers.
Implement a division operation on the entered numbers.
Introduce a condition that raises a runtime error if the second number is zero.
Provide an error message that clearly indicates the cause of the error.
Guide the junior developers in identifying the error message and implementing error
handling techniques to handle the division by zero scenario.
Questions:
Answer of Q2:
try:
# Prompt the user to enter two numbers
num1 = float(input("Enter the first number: ") )
num2 = float(input("Enter the second number: ") )
1. A try block is used to enclose the code that might throw exceptions.
2. We prompt the user to input two numeric values and try to convert those to floating-point
numbers using float(input()). If the user enters non-numeric input, a ValueError is raised.
3. We check if the second number (num2) is zero. If so, we raise a ZeroDivisionError along with
a custom error message indicating zero division is not allowed.
4. When the division operation succeeds, the resultant value is computed and displayed.
5. Except blocks are used to catch and handle particular types of exceptions. Here, the we catch
ValueError(for invalid input) and ZeroDivision Error(for division by zero). Output because of a
division by zero:
By handling errors, programs can provide informative error messages and take alternative
actions, or exit the program cleanly. It makes the code more robust and reliable. thus improving
its usability and reducing the probability of system failures.
If the division by zero error is not handled, the program will throw an unhandled
exception and conclude unexpectedly when a user inputs a zero as the divisor. Such occurrences
can lead to user frustration and may result in data loss or other undesirable outcomes, particularly
in more advanced situations applications. Proper error handling makes it possible to respond to
such situations in an organized manner. improving the user experience while preventing
unexpected program breaks.
References: