Python Forum

Full Version: Exception handler problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Hello everyone. This is my first post so forgive me if I do something wrong.

Here's the problem given to me by my professor:

The coefficient of restitution of a ball, a number between 0 and 1, specifies how much energy is
conserved when the ball hits a rigid surface. A coefficient of 0.9 for instance, means a bouncing ball will
rise to 90% of its previous height after each bounce.
Write a program to input a coefficient of restitution and an initial height in meters, and report how many
times a ball bounces when dropped from its initial height before it rises to a height of less than 10
centimeters. Also report the total distance traveled by the ball before this point.

This is my code:

dis = 0
num = 0

try:
    coif_res = float(input("Enter the Coefficient of restitution "))
    h = float(input("Enter Height in meters: "))
    if coif_res < 0 or coif_res > 1:
        print("Coefficient of restitution must be between 0 and 1!")
    else:
        while h > .1:
            dis = dis + h
            h = coif_res * h
            num = num + 1
except (NameError, ValueError):
    print("Invalid Entry")

if h < .1:
        print("Total distance in meters: ", "{:,.5f}".format(dis), "\nNumber of times bounced: ", "{:,.0f}".format(num))
I have two problems. First, my math is wrong. The number of bounces is correct, but for some reason it isn't adding the height correctly. Second, my exception handler isn't working and I have no idea why. I've been working on this for a couple of hours now, any help is greatly appreciated.
Thanks
Please wrap code in python tags.

To check for multiple exception types use this:
except (NameError, ValueError):
Do not use eval to convert input to floats. Use float().
coif_res = float(input("Enter the Coefficient of restitution "))
You should start using f string formatting.
print("Total distance in meters: ", "{:,.5f}".format(dis), "\nNumber of times bounced: ", "{:,.0f}".format(num))
print(f"Total distance in meters: {dis:0.5f}\nNumber of times bounced {num}")
This is awkward.
if h < .1:
    print("Total distance in meters: ", "{:,.5f}".format(dis), "\nNumber of times bounced: ", "{:,.0f}".format(num))
The purpose of the if is to prevent printing a result if there was an error in the input, but it is not successful doing that, and this purpose is unclear from the code. What happens if there is an error entering coif_res or h? h will be undefined and you will get an error when testing if h < 0.1.

There is a better test. try/except can have 4 parts. One of these parts is a good location for the code that prints your results.
try:
    Code that might raise an XXX exception
except XXX:
    Code to clean up after an XXX exception
else:
    Code that runs if no exception occurred
finally:
    Code that runs no matter what, even if an uncaught exception occurred
I can't help you with the distance calculation. I don't know what the calculation should be. Things to check: Should the initial height be included? Should the last height be included? Do you count the ball bouncing up distance as well as the drop distance?
(Feb-23-2022, 11:31 PM)deanhystad Wrote: [ -> ]Please wrap code in python tags.

To check for multiple exception types use this:
except (NameError, ValueError):
Do not use eval to convert input to floats. Use float().
coif_res = float(input("Enter the Coefficient of restitution "))
You should start using f string formatting.
print("Total distance in meters: ", "{:,.5f}".format(dis), "\nNumber of times bounced: ", "{:,.0f}".format(num))
print(f"Total distance in meters: {dis:0.5f}\nNumber of times bounced {num}")
This is awkward.
if h < .1:
    print("Total distance in meters: ", "{:,.5f}".format(dis), "\nNumber of times bounced: ", "{:,.0f}".format(num))
The purpose of the if is to prevent printing a result if there was an error in the input, but it is not successful doing that, and this purpose is unclear from the code. What happens if there is an error entering coif_res or h? h will be undefined and you will get an error when testing if h < 0.1.

There is a better test. try/except can have 4 parts. One of these parts is a good location for the code that prints your results.
try:
    Code that might raise an XXX exception
except XXX:
    Code to clean up after an XXX exception
else:
    Code that runs if no exception occurred
finally:
    Code that runs no matter what, even if an uncaught exception occurred
I can't help you with the distance calculation. I don't know what the calculation should be. Things to check: Should the initial height be included? Should the last height be included? Do you count the ball bouncing up distance as well as the drop distance?

Thank you for all of your input. I realize that I didn't really give enough information for the distance calculation. The goal is to take in the original distance and add 90% of it every time. So, if the first distance is 10, add 9 making it 19. Then you would add 17 making it 36. You do this until it gets to 10cm drop distance. Each time the drop distance is reduced to 90% of what it was before as stated previously. So once again if it was 10, it will then be 9, and then 8.1. You do this until it is .1 or smaller. I hope that's not too confusing. Once again thank you for all of your advice.
Your description of the distance calculation sounds wrong because that is what you are doing right now (assuming coif_res == 0.9). You might want to re-evaluate. Do you have a test case? What are the inputs and outputs.
(Feb-24-2022, 12:51 AM)deanhystad Wrote: [ -> ]Your description of the distance calculation sounds wrong because that is what you are doing right now (assuming coif_res == 0.9). You might want to re-evaluate. Do you have a test case? What are the inputs and outputs.

I do have a test case actually which I now realize I also should have posted. Here it is:
output:
Enter Coefficient of restitution = 0.7
Enter initial height in meters = 8
Number of bounces = 13
meters traveled = 44.81659

I thought my math was right, but I know it isn't because every time I run the program with these numbers being 0.7 and 8, I get a different answer. The number of bounces is 13, but for the distance I get just over 26.
Just a little under half. That is a pretty good hint.
Counting the drop and the bounce I get 44.89410 which is close but still not correct. Perhaps someone else can show us where this is off.
dis = 0
num = 0
 
try:
	coif_res = float(input("Enter the Coefficient of restitution "))
	h = float(input("Enter Height in meters: "))
	if coif_res < 0 or coif_res > 1:
		print("Coefficient of restitution must be between 0 and 1!")
	else:
		while h > .1:
			dis = dis + h 
			h = coif_res * h
			dis = dis + h
			num = num + 1
except (NameError, ValueError):
	print("Invalid Entry")
 
if h < .1:
        print("Total distance in meters: ", "{:,.5f}".format(dis), "\nNumber of times bounced: ", "{:,.0f}".format(num))
Output:
Enter the Coefficient of restitution .7 Enter Height in meters: 8 Total distance in meters: 44.89410 Number of times bounced: 13
Got it. You have to subtract the last drop.
dis = 0
num = 0
 
try:
	coif_res = float(input("Enter the Coefficient of restitution "))
	h = float(input("Enter Height in meters: "))
	if coif_res < 0 or coif_res > 1:
		print("Coefficient of restitution must be between 0 and 1!")
	else:
		while h > .1:
			dis = dis + h 
			h = coif_res * h
			if h > 0 : last_drop = h
			dis = dis + h
			num = num + 1
		dis = dis - last_drop
except (NameError, ValueError):
	print("Invalid Entry")
 
if h < .1:
        print("Total distance in meters: ", "{:,.5f}".format(dis), "\nNumber of times bounced: ", "{:,.0f}".format(num))
Output:
Press ENTER or type command to continue Enter the Coefficient of restitution 0.7 Enter Height in meters: 8 Total distance in meters: 44.81659 Number of times bounced: 13
(Feb-24-2022, 02:19 AM)BashBedlam Wrote: [ -> ]Got it. You have to subtract the last drop.
dis = 0
num = 0
 
try:
	coif_res = float(input("Enter the Coefficient of restitution "))
	h = float(input("Enter Height in meters: "))
	if coif_res < 0 or coif_res > 1:
		print("Coefficient of restitution must be between 0 and 1!")
	else:
		while h > .1:
			dis = dis + h 
			h = coif_res * h
			if h > 0 : last_drop = h
			dis = dis + h
			num = num + 1
		dis = dis - last_drop
except (NameError, ValueError):
	print("Invalid Entry")
 
if h < .1:
        print("Total distance in meters: ", "{:,.5f}".format(dis), "\nNumber of times bounced: ", "{:,.0f}".format(num))
Output:
Press ENTER or type command to continue Enter the Coefficient of restitution 0.7 Enter Height in meters: 8 Total distance in meters: 44.81659 Number of times bounced: 13

You my friend, are a life saver. Thank you guys for your help.
Always happy to help. Smile
Pages: 1 2