首页 > 解决方案 > 输入运算符以执行数学运算

问题描述

我想输入一个运算符 +, -, , /, //, %,在 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()

标签: python

解决方案


您可以使用字典查找:

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

推荐阅读