0

This is a piece of code I encountered in the 7th lecture on introduction to computer science on MIT OCW. This small program gets input for base and height then calculate the hypotenuse with Pythagoras theorem.

For some reason, it couldn't recognize entry of float.

The code is as follows:

#! /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5
import math

#Get base
inputOK = False
while not inputOK:
    base = input("Enter base: ")
    if type(base) == type(1.0):
        inputOK = True
    else:
        print("Error. Base must be a floating point number.")

#Get Height
inputOK = False
while not inputOK:
    height = input("Enter height: ")
    if type(height) == type(1.0):
        inputOK = True
    else:
        print("Error. height must be a floating point number.")

hyp = math.sqrt(base*base + height*height)

print("Base: " + str(base) + ", height: " + str(height) + ", hypotenuse:" + str(hyp))
0

2 Answers 2

6

This is one of those cases where it is easier to ask for forgiveness than permission. Instead of trying to look at the object and assert it is a float before you act, try to use it as a float and catch any exceptions.

That is, instead of using ifs use:

try:
    base = float(base)
    inputOK = True
except ValueError as e:
    print("Error. Base must be a floating point number.")

This applies similarly to the height value you're trying to get afterwards.

Regardless, input() returns a string so type(input()) will always return str. It is better to cast it to a float (note: ints are also applicable and will be made to floats) and see if it is acceptable than trying to discern its type with if checks.

Mandatory aside, if you even need to check for types, don't use type(obj_a) == type(obj_b), it is arguably always better to use isinstance(obj_a, type(obj_b)).

Sign up to request clarification or add additional context in comments.

Comments

3

The code appears to be written for Python 2, not Python 3, as it requires input() to return something other than a string. In Python 3, input() always returns a string, it never applies eval() to that result like Python 2 would.

It has other issues as well, like using type(base) == type(1.0), completely ignoring the availability of the float object and using is to test for identity, and misses out completely on the far superior isinstance() function.

Just use exception handling instead:

while True:
    try:
        base = float(input("Enter base: "))
        break
    except ValueError:
        print("Error. Base must be a floating point number.")

Note that there is no need for a inputOK boolean either.

Comments

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.