Search code examples
pythonfunctionmathhypotenuse

Returning function values as float Python 3.6.1


I get the following error and can't seem to figure out how to fix. Following the logic, i'm calling 3 functions and all 3 return values as float and then I'm performing some math operation on the stored returned values and print it as float. So where did it go wrong? I enter 4 for side A and 5 for side B.

The error message:

Enter the length of side A: 4.0 Enter the length of side B: 5.0

Traceback (most recent call last):
  File "python", line 26, in <module>
  File "python", line 9, in main
  File "python", line 24, in calculateHypotenuse
TypeError: unsupported operand type(s) for ^: 'float' and 'float'

import math

def main():
  #Call get length functions to get lengths.
  lengthAce = getLengthA()
  lengthBee = getLengthB()

  #Calculate the length of the hypotenuse
  lengthHypotenuse = calculateHypotenuse(float(lengthAce),float(lengthBee))

  #Display length of C (hypotenuse)
  print()
  print("The length of side C 'the hypotenuse' is {}".format(lengthHypotenuse))

#The getLengthA function prompts for and returns length of side A  
def getLengthA():
  return float(input("Enter the length of side A: "))

#The getLengthA function prompts for and returns length of side B
def getLengthB():
  return float(input("Enter the length of side B: "))

def calculateHypotenuse(a,b):
  return math.sqrt(a^2 + b^2)

main()

print()
print('End of program!')

Solution

  • ^ in Python is the bitwise XOR operator, not the power operator:

    The ^ operator yields the bitwise XOR (exclusive OR) of its arguments, which must be intege

    You need to use ** instead, which is the power operator:

    def calculateHypotenuse(a,b):
      return math.sqrt(a**2 + b**2)