【问题标题】:Error in solving trigonometric functions using python使用python求解三角函数时出错
【发布时间】:2020-10-25 07:48:50
【问题描述】:
import math

number = input('Your Number: ')
ways = input('sin/cos/tan: ')

try:
    problem = ways(number)
    answer = math.problem
    print(f'The value of {ways} of {number} is: {problem}')


这是我的代码。

我想在 python 中使用数学模块解决三角函数,但每次运行它都会给我一个错误SyntaxError: unexpected EOF while parsing

【问题讨论】:

  • ways 是字符串,不是函数
  • try 不能没有伴随的except 声明
  • 那我能做什么,把它转换成函数
  • 我认为可变ways是字符串类型..你可以使用if else语句,并检查如果ways == sin,使用sin,同样......

标签: python python-3.x trigonometry


【解决方案1】:

我尝试使用稍微不同的逻辑来测试输入的有效性,从而完全避免您对 try except 的问题。

另外,我使用规范的解决方案在运行时将字符串映射到函数,即使用映射(在 Python 中,dict)。

这是我的解决方案,通过小试运行完成。

In [6]: import math 
   ...: trigs = {'sin':math.sin, 'cos':math.cos, 'tan':math.tan} 
   ...: while True: 
   ...:     try:
   ...:         number = input('Your Number: ')
   ...:         fnumber = float(number) 
   ...:         break 
   ...:     except ValueError: 
   ...:         print('You input a non-valid floating point number.\nPlease try again') 
   ...:         continue 
   ...: while True: 
   ...:     trig = input('sin/cos/tan: ') 
   ...:     if trig in trigs: break 
   ...:     print('You input a non-valid trig function.\nPlease try again') 
   ...:  
   ...: print(f'The value of {trig} of {number} is: {trigs[trig](fnumber)}')              
Your Number: ret
You input a non-valid floating point number.
Please try again
Your Number: 1.57
sin/cos/tan: ert
You input a non-valid trig function.
Please try again
sin/cos/tan: tan
The value of tan of 1.57 is: 1255.7655915007897

In [7]:                                                                                   

【讨论】:

    【解决方案2】:
    • 你应该有一个except 块,它至少可以处理pass 的错误
    • ways其实是函数,取不同的输入
    import math
    
    number = input('Your Number: ')
    ways_ = input('sin/cos/tan: ')
    
    try:
        problem = ways(number)
        answer = math.problem
        print(f'The value of {ways} of {number} is: {number}')
    except:
        pass
        # anything else?? handle errors??
    

    【讨论】:

      【解决方案3】:
      1. 您需要添加except 块来处理异常,以防您的代码出现问题。

      2. 你可以编写这样的代码来完成你想要的任务:

      import math
      number = input('Your Number: ')
      ways = input('sin/cos/tan: ')
      
      def math_func(num, type_func):
          func = {'sin': lambda: math.sin(num),
                  'cos': lambda: math.cos(num),
                  'tan': lambda: math.tan(num)}
          return func.get(type_func)()
      
      try:
          answer = math_func(float(number), ways)
          print(f'The value of {ways} of {number} is: {answer}')
      except:
          pass
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-21
        • 1970-01-01
        • 2022-12-11
        • 2020-05-14
        • 1970-01-01
        • 2012-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多