Python Forum
Exception handler problem
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Exception handler problem
#11
I think the code is organized wrong.
try:
    height = float(input("Enter Height in meters: "))
    rcoef = float(input("Enter the Coefficient of restitution "))
    if rcoef < 0 or rcoef > 1:
        print("Coefficient of restitution must be between 0 and 1!")
    else:
        distance = height
        bounces = 1
        while True:
            height = height * rcoef
            if height >= 0.1:
                bounces += 1
                distance += 2 * height
            else:
                break
        print(f"Total distance in meters: {distance}\nNumber of times bounced: {bounces}")
except ValueError:
    print("Invalid Entry")
Though I wonder what is the purpose of the try/except block. A nicer message when the code doesn't produce any results? Seems like overkill for something like this. I would remove the exception handling and add even more unhandled exceptions.
height = float(input("Enter Height in meters: "))
assert(height >= 0)
rcoef = float(input("Enter the Coefficient of restitution (0.0..1.0) "))
assert(0 <= rcoef <= 1)
distance = height
bounces = 1
while (height := height * rcoef) > 0.1:
    bounces += 1
    distance += 2 * height
print(f"Total distance in meters: {distance}\nNumber of times bounced: {bounces}")
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Exception handler problem part 2 Leo 3 1,599 Feb-27-2022, 12:33 AM
Last Post: Larz60+
  updating collision handler for pymunk 5.3.2 pythony 5 5,571 Oct-27-2017, 09:49 AM
Last Post: pythony

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020