要求:
编写一个程序,执行包括加法+
、减法-
、乘法*
和除法//
在内的基本算术运算。
- 定义函数
perform_arithmetic_operation()
,参数为operation_string
(字符串)。 - 在函数内,执行字符串中指定的算术运算,并将结果作为数字返回。
- 如果运算为除法,且第二个数为0,则返回**-1**。
示例输入
35 + 44
示例输出
79
解释: 在Python中,输入视为字符串。这里,输入
35 + 44
表示一个字符串。程序提取+
运算符,并在数字35和44之间执行加法运算。
- 保证输入的算术运算符为
+
、-
、*
或//
,且运算符两侧均为整数。
代码:
def perform_arithmetic_operation(operation_string):
try:
results = eval(operation_string)
if isinstance(results,int) or isinstance(results,float):
return results
else:
return -1
except ZeroDivisionError:
return -1
except:
return -1
# 获取输入
operation_string = input()
# 调用函数
print(perform_arithmetic_operation(operation_string))
关于eval()函数
python中eval()函数的作用及使用方法_eval()函数的作用是什么?-优快云博客