问题描述
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
解决方法
我尝试使用稍有不同的逻辑来测试输入的有效性,从而完全避免try
except
的问题。
此外,我使用了规范的解决方案在运行时将字符串映射到函数,即使用映射(在Python中为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]:
,
- 您应该有一个
doubleSize
块,甚至void doubleSize(char ***list,size_t *size) { size_t new_size = *size * 2; char **new_list = realloc(*list,new_size); if (!new_list) [ // Ignoring out-of-memory errors. } *list = new_list; *size = new_size; }
至少也要进行错误处理 -
void doubleSize(char ***list,size_t *size) { *list = realloc(*list,( *size *= 2 )); }
实际上是功能,需要不同的输入
try
{
SqlDataAdapter da = new SqlDataAdapter();
sqlcon.Open();
da.DeleteCommand = new SqlCommand("delete from tbl_registerStudent where rfidno = '" + rfidno + "'",sqlcon);
da.DeleteCommand.ExecuteNonQuery();
MessageBox.Show("" + rfidno);
MessageBox.Show("Delete Successfull");
sqlcon.Close();
bindGrid();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
,
-
您需要添加
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