我想输入一个运算符,+、-、、/、//、%,以在 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()
答案 0 :(得分:1)
这是一个选项:
operator = input('Enter an operator: ')
operators = '+-**/'
if operator in operators:
executable = f'print(2{operator}3)'
exec(executable)
程序将要求用户输入,然后检查输入是否在运算符中,如果是,它将打印出使用 2 和 3 以及该运算符的任何结果。您几乎可以在该 f string
中放入任何代码。
关于安全:
正如评论中有人提到的那样不安全(使用 exec()
)?因为我只能假设这是因为可以运行任何代码(包括恶意代码)您可以过滤用户输入的内容。
这里可能是你的代码的一个实现(应该使用 python 3.6 或更高版本或类似支持 f strings
的东西):
n = 5
i = 3
operator = '*'
# main part ========================
result = None
exec(f"""result = {n}{operator}{i}""", globals())
s = f'''{n} * {i} = {result}'''
print(s)
然而,这似乎不像我一开始想的那么有效,所以你可能最好使用另一个答案来使用字典和定义一个函数。
答案 1 :(得分:1)
您可以使用字典查找:
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
答案 2 :(得分:0)
为了让它工作,我使用了我的代码:"s = str(n) + "*" + str(i) + "= " + str(n * i)" 并使用灵感修改了这一行来自@Matiiss 提供的代码:"exec(f"""result = {n}{operator}{i}""", globals())"。我的新行是这样的:"str(n) + str(operator) + str(i) + "= " + str(n + i)"。然后我用它做了4行。每行执行一个数学运算:+、-、*、/。然后我在调用@JacobLee 提供的字典的四行下为每个单独的操作做了一个嵌套的 if 语句。结合用户输入的选择运算符的代码,用户选择的运算符将调用相应的嵌套 if 语句。最后,嵌套 if 语句中的代码将执行数学运算并将其写入 .txt 文件。谢谢大家的回答,帮了大忙。祝你有美好的一天。