python - 输入运算符以执行数学运算
问题描述
我想输入一个运算符 +, -, , /, //, %,在 python 中使用这个程序执行数学运算。如何编码这些字符串:“s = str(n) + " " + str(i) + "= " + str(n * i)" 用于 .txt 文件功能和 "print(n, "*", i, "=", n * i)" 包括我选择的运算符?我不知道如何让它工作。谢谢你的时间。
#!/usr/bin/python
def tablep():
n=int(input("Enter Number of .txt Files to Create:")) # number of txt files
for x in range(0, n):
n=int(input("Enter a Number to Create Multiples of: "))
import operator
operatorlookup = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv}
o=int(input("Enter Calculation Symbols for Calculation You Want to Perform: "))
m=operatorlookup.get(o)
start=int(input("Enter a Start Range Number: "))
end=int(input("Enter an End Range Number: "))
f=int(input("Enter Table Number to Name .txt File: "))
f_path = "table_" + str(f) + ".txt" # this will numerate each table
file = open(f_path, 'a') # 'a' tag will create a file if it doesn't exist
if start<end:
for i in range(start,end+1):
s = str(n) + "*" + str(i) + "= " + str(n * i) # I want to put the math operation of my choosing here in this "str(n * i)".
file.write(s)
file.write("\n")
print(n,"*",i,"=", n * i) # I want to put the math operation of my choosing here in this "n * i)".
elif start>end:
for i in range(start,end,-1):
s = str(n) + "*" + str(i) + "= " + str(n * i) # I want to put the math operation of my choosing here in this "str(n * i)".
file.write(s)
file.write("\n")
print(n, "*", i, "=", n * i) # I want to put the math operation of my choosing here in this "n * i)".
file.close()
print("\nYou are done creating files now. Run the program again if you want to create more. Thank you for using this program and have a nice day!\n")
w = tablep()
解决方案
您可以使用字典查找:
def evaluate(a: int, b: int, operation: str):
oper = {
"+": a+b, "-": a-b, "*": a*b, "/": a/b, "%": a%b, "//": a//b
}
return oper.get(operation)
通过一些测试运行:
>>> evaluate(2, 5, "+")
7
>>> evaluate(2, 5, "-")
-3
>>> evaluate(2, 5, "*")
10
>>> evaluate(2, 5, "bananas")
None
推荐阅读
- laravel-5 - 何将日期从 mysql 转换为 gijgo datepicker
- android - Android Studio 中两个不同的 .xml 文件出现相同的“Android 资源链接”错误
- javascript - 在服务器端渲染 (Node/Express) 中反应 Cookie
- slack - 清除机制/从松弛中批量删除消息
- android - 如何为每个父级更改可扩展列表视图中的图像?
- javascript - 多个 3 列布局的目标中间子级
- c# - 使用 c#、NPOI 和 XSSF 工作簿计算 .xlsx 工作簿工作表的最简单方法是什么?
- symfony - 基于用户角色的登录后重定向
- c# - 实体框架 6:删除具有多对多关系的实体
- docker - 用户定义的 docker 网络中的 Docker 容器 - 只能从主机访问