0% found this document useful (0 votes)
68 views

Programming Assignment Unit 3

Assignment

Uploaded by

htetkaungthaw27
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

Programming Assignment Unit 3

Assignment

Uploaded by

htetkaungthaw27
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Programming Assignment Unit 3

Htet Kaung Thaw


CS 1101 – Programming Fundamentals
Instructor : Safia Hirari
Deadline : 5th December 2024
Programming Assignments

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:

o Think Python: How to think like a computer scientist Chapter 5 – Conditionals


and recursion

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)

except ValueError as ve:


print(f"Error: {ve}. Please enter a valid integer.")

# Correcting the check for running the main function


if __name__ == "__main__":
main()

Result of positive number:

Result of negative number:


Result of zero input:

Result of invalid input:

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:

1. Import the time module:

The time module is used to introduce a one-second delay between each successive count via the
function time.sleep(1).

2. The Countdown Function:

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.

3. The Countup Function:

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).

5. Executing the Script:

The conditional expression if __name__ == "__main__": checks if the script is being run as the
main program.

If so, calls the main() function in order to kick-start it all.

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:

 Provide a code demonstrating how to handle the division by zero error.

 Output demonstrating the runtime error, including the error message.


 Explain the significance of error handling in expressions or conditions, using the division
by zero scenario as an example. Discuss the potential impact of not handling this error in
a program.
 Please provide detailed explanations and code snippets to guide the junior developers in
understanding and addressing the division by zero error in Python programs.

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: ") )

# Check if the second number is zero


#if num2 == 0:
#raise ZeroDivisionError("Division by zero is not allowed.")

# Perform the division


result = num1 / num2

# Display the result


print(f"The result of {num1} divided by {num2} is {result: .2f}")

except ValueError as ve:


print(f"Error: {ve}. Please enter valid numbers.")
except ZeroDivisionError as zde:
print(f"Error: {zde}")

Result of normal calculation:

Result of divisions by zero:


Explanation:

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:

Importance of Error Handling:

Error handling in programming is important because it helps you handle things


gracefully. unexpected situations, preventing the program from crashing. In the division by zero
case, if an error is not being handled, the program will terminate with an unhandled exception.
This can lead to poor user experience and make the program unreliable.

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.

Potential Repercussions for Failing to Rectify the Defect:

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:

- Rollbar.com – Explanation of how to handle ZeroDivisionError.

- Python Docs – Explanation of try and except Error Handling.

You might also like