自定义一个简易的模块,使这个模块能计算平方根(包括负数的平方根计算),还能计算加减乘。
首先先定义一个模块命名为count.py。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
import cmath
def sqrt(x, y):
try:
y = math.sqrt(y)
print(y)
except ValueError:
y = cmath.sqrt(y)
print(y)
def add(x, y):
return print(x + y)
def subduction(x, y):
return print(x - y)
def Multiplication(x, y):
return print(x * y)
然后再编写一个程序进行计算的处理
import count
n = input('请输入你要进行的运算(如果计算平方根输入格式为:2 @ 3):')
m = n.split(' ')
operator = m[1]
x = m[0]
y = m[2]
operatordict = {'+': count.add, '-': count.subduction, '@': count.sqrt, '*': count.Multiplication}
#注意一下如果要引用模块里的函数要用count.***#
operatordict[operator](int(x), int(y))
请输入你要进行的运算(如果计算平方根输入格式为:2 @ 3):2 @ 2
1.4142135623730951
请输入你要进行的运算(如果计算平方根输入格式为:2 @ 3):2 * 3
6
请输入你要进行的运算(如果计算平方根输入格式为:2 @ 3):2 @ -1
1j