python中的嵌套ifs无法正常工作且数学模块出错

问题描述 投票:-2回答:2

在这段代码中,我首先向用户询问三角函数,然后询问弧度或度数的角度。根据代码,控制台应该打印错误,但是在运行代码时,第一个if语句接受任何输入为true。最终的coputed值也是worng。请提出建议以及可以对代码进行的任何其他相关更改。

from math import *
trigFunc = str(input("What function do you want to use? Sine, Cosine or Tangent: "))
if trigFunc.lower == "sine" :
    radOrDeg = str(input("Do you want to input the value as radians or degrees? "))
    if radOrDeg.lower == "radians" :
        angle = int(input("Please input the value of the angle: "))
        print(math.sin(angle))
    elif radOrDeg.lower == "degrees" :
        angle = int(input("Please input the value of the angle: "))
        radAngle = int(math.radians(angle))
        print(math.sin(radAngle))
    else:
        print("error")
elif trigFunc.lower == "cosine" :
    radOrDeg = str(input("Do you want to input the value as radians or degrees? "))
    if radOrDeg.lower == "radians" :
        angle = int(input("Please input the value of the angle: "))
        print(math.cos(angle))
    elif radOrDeg.lower == "degrees" :
        angle = int(input("Please input the value of the angle: "))
        radAngle = int(math.radians(angle))
        print(math.cos(radAngle))
    else:
        print("error")
elif trigFunc.lower == "tangent" :
    radOrDeg = str(input("Do you want to input the value as radians or degrees? "))
    if radOrDeg.lower == "radians" :
        angle = int(input("Please input the value of the angle: "))
        print(math.tan(angle))
    elif radOrDeg.lower == "degrees" :
        angle = int(input("Please input the value of the angle: "))
        radAngle = int(math.radians(angle))
        print(math.tan(radAngle))
    else:
        print("error")
else:
    print("ERROR, the function cannot be used")
input("press enter to exit")
python python-3.x trigonometry nested-if
2个回答
2
投票

.lower是一个函数,你需要调用它来返回一个字符串。现在,您正在将函数与将返回False的字符串进行比较。

trigFunc.lower改为trigFunc.lower()

https://docs.python.org/3/library/stdtypes.html#str.lower


0
投票

您的代码中存在多个错误。以下是为了让您的代码正常工作而更改的内容:

  1. 使用trigFunc.lower()而不是trigFunc.lower。您需要调用方法来获得所需的结果。
  2. 使用import math而不是from math import *,因为你始终引用math库。
  3. 使用math.radians(int(angle))而不是int(math.radians(angle)),因为math.radians不接受字符串作为输入。
© www.soinside.com 2019 - 2024. All rights reserved.