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

Programming Assignment Unit 3

The document discusses recursion and error handling in Python, presenting two recursive functions: countup and countdown, which count numbers up and down respectively, and a blastoff function that determines which to use based on user input. It also explains error handling, particularly for division by zero, using conditional statements and try-except constructs to manage exceptions gracefully. The document includes code snippets and outputs demonstrating the functionality of these concepts.

Uploaded by

nazilaramzi25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Programming Assignment Unit 3

The document discusses recursion and error handling in Python, presenting two recursive functions: countup and countdown, which count numbers up and down respectively, and a blastoff function that determines which to use based on user input. It also explains error handling, particularly for division by zero, using conditional statements and try-except constructs to manage exceptions gracefully. The document includes code snippets and outputs demonstrating the functionality of these concepts.

Uploaded by

nazilaramzi25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

1

Understanding Recursion and Error Handling in Python

CS 1101-01 Programming Fundamentals - AY2025-T4

Programming Assignment Unit 3

Instructor: Jose Alvarado

May 1, 2025
2

Q1.

Recursive function for counting numbers up

def countup(n):

if n >= 0: #Check whether the argument is negative or not

print("Blastoff!") # If the argument is zero or positive or zero, print “Blastoff”.

else:

print(n) # Print if it is a negative number

countup(n+1) #Call the function again with +1 combined with the argument.

countup(-3)

Output

-3

-2

-1

Blastoff

The textbook example of counting the number up function

def countdown(n):

if n <= 0:
3

print('Blastoff!')

else:

print(n)

countdown(n-1)

The third function that takes an input from a user

def blastoff ():

#Take the user's input and turn it into an integer.

num = int (input ("Enter a number: "))

#If the number is positive, use the countdown () function.

if num > 0:

countdown(num)

#If the number is negative, use the countup() function.

elif num < 0:

countup (num)

#If the input is zero, we choose to use

#countdow () function to print "Blastoff".

else:

countdown(num)
4

Screenshots and results:

Output of positive number input

Enter a number: 5

Blastoff!

Output of negative number input

Enter a number: -9

-9

-8

-7
5

-6

-5

-4

-3

-2

-1

Blastoff!

Output of zero number input

Enter a number: 0

Blastoff!
6

Explanation

I created two recursive functions: countdown and countup. The countdown function takes a

number n and counts down to 0. It prints each number as it counts down. When n reaches 0 or

goes below, the function prints "Blastoff!" and stops the counting. On the other hand, the

countup function does the reverse. It starts from a given number n and counts up to 0, printing

each number along the way. When n reaches 0 or goes below, it also prints "Blastoff!" and stops.

Next, I defined a function called blastoff(). This function asks the user to input a number. Since

the input function always returns a string, I used the int() function to convert that string into an

integer and stored it in a variable named num.

After getting the number, I used if, elif, and else statements to decide which function to run

based on the value of num. If num is greater than 0, it calls the countdown function. If num is

less than 0, it calls the countup function. If num is exactly 0, it calls the countdown function. I

chose to do this for consistency and readability, as it makes more sense to count down to zero

rather than count up to zero.

Q2.

The division function that handles Zero Division Error

def division ():

#Prompt the user to enter two numbers

num1 = float (input ("Enter the first number: "))

num2 = float (input ("Enter the second number: "))


7

#Check whether num 2 is zero:

if num2 == 0:

print ("Error: Division by zero is not allowed.")

#If num2 is not zero, perform the division between num1 and num2

else:

result = num1/num2

print ("Result: ", result)

division ()

#Output demonstrating the error message.

Enter the first number: 12

Enter the second number: 0

Error: Division by zero is not allowed

The significance of error handling in expressions or conditions

Error handling is the safety procedure that programmers implement in their programs to handle

any unexpected errors or runtime errors that occur during the runtime process (TechTarget,
8

2022). Without proper error handling, the program would abruptly end when encountering a

runtime error such as a division by zero error. This situation could lead to data loss or corruption,

poor user experience, harder debugging processes, and security vulnerabilities (GeeksForGeeks,

2023).

By implementing error handling techniques, we can catch and gracefully handle errors. In the

codes above, the if conditional is used for catching the division by zero error when the second

number is zero. Instead of crashing, the program displays a meaningful error message and exits

gracefully (TechTarget, 2022).

Detailed explanations and code snippets to guide junior developer

1. Defining a function and prompting the users to enter two numbers:

def division ():

#Prompt the user to enter two numbers

num1 = float (input ("Enter the first number: "))

num2 = float (input ("Enter the second number: "))

Here, I first define a division () function that takes no argument. Then, I add two statements that

prompt the users to input two numbers. Since the input () function only returns string values, I

use the float () function to convert them into floating point values and store them in num1 and

num2 variables.
9

2. Checking whether num2 is zero

#Check whether num 2 is zero:

if num2 == 0:

print ("Error: Division by zero is not allowed.")

Here, I add a condition that if num2 is zero, the function will raise an error and print out the

error

message "Error: Division by zero is not allowed.". As division by zero is not defined, the

function will not produce any result.

3. Performing division between two inputs when there is no error.

#If num2 is not zero, perform the division between num1 and num2

else:

result = num1/num2

print ("Result: ", result)

If there is no zero by division error, the function will perform division between two inputs and

print out the results.

4.Other strategies for error handling.

Most programming languages provide mechanisms to handle runtime errors and exceptions. In
10

Python, we use the try-except construct to handle unexpected errors or exceptions that can occur

during the execution of a program. Below is an alternative example of dealing with

the division by zero error using the try-except construct.

Alternative version of division that uses try and except for handling Zero Division Error.

Codes:

def division ():

try: #For Error handling.

#Prompt the user to enter two numbers

num1 = float (input ("Enter the first number: "))

num2 = float (input ("Enter the second number: "))

#Perform the division

result = num1/num2

#Print the result

print (f 'Result: {result}')


11

except ZeroDivisionError:

#Handle the zero division exception

print ("Error: Division by zero is not allowed.")

except:

#Handle any other exceptions

print ("Please only enter a number")

division ()

Output:

Enter the first number: 12

Enter the second number: "hello"

Please only enter a number

Enter the first number: 12

Enter the second number: 0

Error: Division by zero is not allowed.


12

Explanation

This is the second version of the division function that uses try-except for error handling instead

of conditionals. The function takes two inputs and performs division. If the user enters something

that isn’t a number, it will print “Please enter only a number.” If the user enters zero as the

second input, it will print “Error: Division by zero is not allowed” using except

ZeroDivisionError. In Python, try-except is used to handle runtime errors that happen while the

program is running. We can also specify except to catch specific types of runtime errors. In this

code, we use except ZeroDivisionError to catch division by zero errors, while another except

catches other types of errors.

Word Count: 1154


13

Reference

Downey, A. (2015). Think Python: How to think like a computer scientist. Green Tree Press.

https://greenteapress.com/thinkpython2/thinkpython2.pdf

GeeksForGeeks. (2023). Error handling in programming. Retrieved from

https://www.geeksforgeeks.org/error-handling-in-c/

TechTarget. (2022). Error handling. Retrieved from

https://www.techtarget.com/whatis/definition/error-handling

You might also like