为了账号安全,请及时绑定邮箱和手机立即绑定

使用python求解三角函数时出错

使用python求解三角函数时出错

一只甜甜圈 2024-01-04 15:23:43
import mathnumber = 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
查看完整描述

3 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

我试图try except通过使用稍微不同的逻辑来测试输入的有效性来完全避免您的问题。


另外,我使用了在运行时将字符串映射到函数的规范解决方案,即使用映射(在 Python 中,a 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]:         


查看完整回答
反对 回复 2024-01-04
?
30秒到达战场

TA贡献1828条经验 获得超6个赞

你应该有一个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??


查看完整回答
反对 回复 2024-01-04
?
波斯汪

TA贡献1811条经验 获得超4个赞

您需要添加except用于处理异常的块,以防代码中出现问题。


您可以编写这样的代码来实现您想要的任务:


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


查看完整回答
反对 回复 2024-01-04
  • 3 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信