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

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


一只甜甜圈
浏览 93回答 3
3回答

紫衣仙女

我试图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: retYou input a non-valid floating point number.Please try againYour Number: 1.57sin/cos/tan: ertYou input a non-valid trig function.Please try againsin/cos/tan: tanThe value of tan of 1.57 is: 1255.7655915007897In [7]:         

30秒到达战场

你应该有一个except块,它至少可以处理错误passways实际上是函数,采用不同的输入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: {number}')except:    pass    # anything else?? handle errors??

波斯汪

您需要添加except用于处理异常的块,以防代码中出现问题。您可以编写这样的代码来实现您想要的任务:import mathnumber = 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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python