亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用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 關注
  • 296 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號