0

I have a very brief familiarity with coding in general, though a majority of my experience thus far has been with Python. Which is why it's upsetting that I can't seem to figure out how to do this...

I have an assignment in my Python class where I am required to compute the area of a right triangle. I have completed the assignment successfully, but I wanted to take it a step further and restrict the user from inputting anything but an integer as input. I've tried multiple ideas from what I learned on Codecademy, though I can't seem to figure it out. Any help would be greatly appreciated!

Here is the code I've written so far; it works fine for what it is, but I would like to have it return a string that says something like "Please enter a valid number" if the user were to type anything besides a number:

from time import sleep
import math

print("Let\'s find the area of a right triangle!")
sleep(2)

triangleBase = float(input("Enter the base value for the triangle: "))
print("Great!")

triangleHeight = float(input("Enter the height value for the triangle: "))
print("Great!")
sleep(2)

print("Calculating the area of your triangle...")
sleep(2)

def triangleEquation():
    areaString = str("The area of your triangle is: ")
    triangleArea = float(((triangleBase * triangleHeight) / 2))
    print('{}{}'.format(areaString, triangleArea))

triangleEquation()
2
  • I really don't know enough about this sort of stuff in general... Hence the need for a class. Is there another way to capture user input then that would allow what I seek? Commented Apr 13, 2017 at 4:25
  • Check this... How can I limit the user input to only integers in Python Commented Apr 13, 2017 at 4:26

2 Answers 2

1

You are close. You noticed that your code raised an exception. All you need to do is catch that exception and prompt again. In the spirit of "don't repeat yourself", that can be its own function. I cleanup up a couple of other things, like your calculation function using global variables and converting things that don't need converting (e.g. 'foo' is a str, you don't need str('foo')) and got

from time import sleep
import math

def input_as(prompt, _type):
    while True:
        try:
            # better to ask forgiveness... we just try to return the
            # right stuff
            return _type(input(prompt.strip()))
        except ValueError:
            print("Invalid. Lets try that again...")

def triangleEquation(base, height):
    area = base * height / 2
    print('The area of your triangle is: {}'.format(areaString, area))


print("Let\'s find the area of a right triangle!")
sleep(2)

triangleBase = input_as("Enter the base value for the triangle: ", float)
print("Great!")

triangleHeight = input_as("Enter the height value for the triangle: ", float)
print("Great!")
sleep(2)

print("Calculating the area of your triangle...")
sleep(2)

triangleEquation(triangleBase, triangleHeight)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! This is exactly what was needed! So it would seem I need to become familiarized with how to use Try and Except. This worked perfectly for what was needed :)
There is a theory in python called duck-typing that says your code should assume operations are going to work and to catch exceptions when everything blows up in your face.
0

This should get you started. I'll leave the rest for you (if you'd like to also allow floats, hint, hint), since you said you wanted to take it a step further, that way you'll still retain the sense of accomplishment.

def triangleEquation(triangleBase, triangleHeight):
    if type(triangleHeight) == int and type(triangleBase) == int:
        areaString = "The area of your triangle is: "
        triangleArea = float(((triangleBase * triangleHeight) / 2))
        return '{}{}'.format(areaString, triangleArea)
    else:
        return 'Integers only.'

Note: You could also use the is idiom: if type(triangleHeight) is int...

8 Comments

I wish I had enough rep to be able to upvote your answer, your answer really helped open my eyes to new terms and concepts that I will definitely now begin looking into!
Thanks. It's good that you wanted to take the solution to the problem a step further. That's a good habit to get into. I hope you enjoy programming with Python. I do! Good luck! Also, notice that I took your call to the print() function out of the triangleEquation() function. That's another good habit to get into: making your functions "fruitful" (having a return value other than None which is the default if nothing is returned, and is considered a void function. Then do your printing elsewhere, in the main() function.
Here's a resource I found useful when I first started with Python, which was only a couple of months ago; it was one of the books recommended on python.org: openbookproject.net/thinkcs/python/english3e/…
A thousand thanks! I appreciate the referral, I could really use all the help I can get; sometimes it feels like I'm trying to learn how to use a computer all over again. I genuinely appreciate the help.
This might be an even better resource, but I haven't worked through it all yet: diveintopython3.net But, so far, I think it's fantastic, though maybe a little faster paced.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.