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]:
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??
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
添加回答
举报