基本计算器/未来温度转换器/未来科学计算器

时间:2016-08-07 03:36:57

标签: python

我将尝试添加temp.converters和其他数学用途但是当我测试它时,代码无法识别我输入的数字以选择操作。 还有一种方法可以使用列表同时添加多个数字

#Returns the sum of num1 and num2
def add(num1, num2):
    return num1 + num2

#Returns the result of subtracting num1 - num2
def sub(num1, num2):
    return num1 - num2

#Returns the result of multiplying num1 * num2
def mul(num1, num2):
    return num1 * num2

#Returns the result of dividing num1 / num2
def div(num1, num2):
    return num1 / num2

#Returns the result of dividing num1 / num2
def exp(num1, num2):
    return num1 ** num2

from math import *


print("1: ADDITION")
print("2: SUBTRACTION")
print("3: MULTIPLICATION")
print("4: DIVISION")
print("5: Exponent")
print("6: Square root")
print("7: ")
print("8:")
print("9:")
print("10:")

def main():
    operation = int(input("operation:"))

    if(operation == '1'):
        a = var1("input a:")
        b = var2("input b:")
        print(add(var1, var2))

    elif(operation == '2'):
        a = var1("input a:")
        b = var2("input b:")
        print(sub(var1, var2))

    elif(operation == '3'):
        a = var1("input a:")
        b = var2("input b:")
        print(div(var1, var2))

    elif(operation == '4'):
        a = var1("input a:")
        b = var2("input b:")
        print(mul(var1, var2))

    elif(operation == '5'):
        a = var1("input a:")
        b = var2("input b:")
        print(exp(var1, var2))

    elif(operation == '6'):
        a = var1("input:")
        print(sqrt(var1,))

    elif(operation == '7'):
        a = var1("input a:")
        b = var2("input b:")
        print(add(var1, var2))

    else:
        main()

main()

1 个答案:

答案 0 :(得分:0)

您可以利用Python中的operator模块并使用字典调度方法,例如:

import operator
from math import sqrt

operations = {
    '1': operator.add,
    '2': operator.sub,
    '3': operator.mul,
    '4': operator.truediv,
    '6': sqrt,
    '99': lambda c: c * 1.8 + 32 # convert C -> F
}

for operation in iter(lambda: input('Operation: '), 'quit'):
    if operation not in operations:
        print('Sorry - not sure what {} is'.format(operation))
        continue
    args = map(int, input('Enter values: ').split())
    print('Result is', operations[operation](*args))