将函数值返回为float Python 3.6.1 [英] Returning function values as float Python 3.6.1

查看:34
本文介绍了将函数值返回为float Python 3.6.1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误,似乎无法弄清楚如何解决.按照逻辑,我将3个函数和所有3个返回值都调用为float,然后对存储的返回值执行一些数学运算并将其打印为float.那么哪里出了问题?我在A面输入4,在B面输入5.

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.

错误消息:

输入A边的长度:4.0输入B边的长度:5.0

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!')

Python中的

推荐答案

^

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

^运算符会产生其参数的按位XOR(异或),该值必须是整数

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)

这篇关于将函数值返回为float Python 3.6.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆