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
添加回答
舉報