Click here to Skip to main content
15,897,032 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Create a program in Python, called TA_Calculator, that uses a function to calculates the area of a triangle given the base and height measurements. Use the below function to do your calculation:def area_of_triangle(base, height):return 0.5 * base * heightThe program should receive the base and the height from the user. Once the user enter a base greater than the height the program should give the user another attempt to enter a base and a height. The program only give the user three attempts to enter the correct base and height on the third attempt the program should display the below message:"You have exhausted your 3 attempts please try again later"Expected outputlf the user enter a base less than height, the program should display the correct triangle area using the given function


What I have tried:

<pre>print("Enter the base and hight")
attempts = 0

while attempts !=3:
    base_val = float(input("base "))
    height_val = float(input("height "))
    if base_val < height_val:
        def area_of_triangle(base, height):return 0.5 * base * height
        print(area_of_triangle(base_val, height_val))
        break
        attempts += 1
    else:
        print("Try your next attemp")
        #print("You have exhausted your 3 attempts please try again later")
Posted
Updated 1-Jul-21 2:17am

You only increment the attempts variable if the inputs are valid. You should move it into the else clause:
Python
while attempts !=3:
    base_val = float(input("base "))
    height_val = float(input("height "))
    if base_val < height_val:
        def area_of_triangle(base, height):return 0.5 * base * height
        print(area_of_triangle(base_val, height_val))
        break
    else:
        attempts += 1
        if attempts == 3:
            print("You have exhausted your 3 attempts please try again later")
        else:
            print("Try your next attemp")
 
Share this answer
 
The break statement immediately exits the "closest" loop: if you are have two nested loops, then break inside the inner oen exist from that loop only, and continues from the first lane of code after it rather than exiting from both.

So your code after the break:
PHP
print(area_of_triangle(base_val, height_val))
break
attempts += 1
will never, ever get executed. Which doesn't matter too much in this case, because the loop will always exit immediately if the base is less than the height.

What you need to do is move the line:
PHP
attempts += 1
outside the if and add code to check it to the else code.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900