Written code all know, according to the previous study, the method can encapsulate some of the functions they need on their own:
For example, I created three files in the same directory
Wherein defmath is specifically defined by the function calculated from
defjudge custom function determination
test test call these functions file
Look for the file method, we can learn from each other:
defmath.py:
import math
#求和
def addMath(n,*vartuple):
temp = 0
temp = temp+n
for var in vartuple:
temp = temp+var
return temp
#求平方根
def sqrtMath(n):
temp = n ** 0.5
return temp
#计算三角形的面积
#flag为计算类型,后面传入相应的参数即可
'''
1.已知三角形底a,高h,则 S=ah/2
2.已知三角形三边a,b,c,则
(海伦公式)(p=(a+b+c)/2)
S=sqrt[p(p-a)(p-b)(p-c)]
=sqrt[(1/16)(a+b+c)(a+b-c)(a+c-b)(b+c-a)]
=1/4sqrt[(a+b+c)(a+b-c)(a+c-b)(b+c-a)]
3.设三角形三边分别为a、b、c,内切圆半径为r
则三角形面积=(a+b+c)r/2
'''
def triangleAreaMath(flag,*vartuple):
if(flag==1):
s = vartuple[0]*vartuple[1]/ 2
return s
elif(flag==2):
p = (vartuple[0]+vartuple[1]+vartuple[2])/ 2
s=(p*(p-vartuple[0])*(p-vartuple[1])*(p-vartuple[2]))**0.5
return s
elif(flag==3):
s = (vartuple[0]+vartuple[1]+vartuple[2])*vartuple[3]/ 2
return s
else:
return "暂时不提供该方案计算"
#计算圆的面积
#传入圆的半径
def circularAreaMath(r):
s = math.pi*(r*r)
return s
#计算两个数的最大公约数
def hcf(x, y):
#获取最小值
if x > y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if((x % i == 0) and (y % i == 0)):
temp = i
return temp
#计算两个数的最小公倍数
def lcm(x, y):
#获取最大的数
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
temp = greater
break
greater += 1
return temp
#摄氏温度转华氏温度
def TemperConve(celsius):
fahrenheit = (celsius * 1.8) + 32
print('%0.1f 摄氏温度转为华氏温度为 %0.1f ' %(celsius,fahrenheit))
return fahrenheit
defjudge.py:
#判断字符串是否为数字
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
#判断奇数偶数
def is_oddOrEven(num):
if (num % 2) == 0:
print("{0} 是偶数".format(num))
else:
print("{0} 是奇数".format(num))
#判断闰年
def is_leapyear(year):
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} 是闰年".format(year)) # 整百年能被400整除的是闰年
return True
else:
print("{0} 不是闰年".format(year))
return False
else:
print("{0} 是闰年".format(year))# 非整百年能被4整除的为闰年
return True
else:
print("{0} 不是闰年".format(year))
return False
#判断质数
def is_prime(num):
flag=False
# 质数大于 1
if num > 1:
if(num==2):
flag=True
print(num,"是质数")
return flag
# 查看因子
for i in range(2,num):
if (num % i) == 0:
print(num,"不是质数")
print(i,"乘于",num//i,"是",num)
flag=False
return flag
print(num,"是质数")
flag=True
# 如果输入的数字小于或等于 1,不是质数
else:
print(num,"不是质数")
flag=False
return flag
#判断字符串是否存在子字符串
def check(string, sub_str):
if (string.find(sub_str) == -1):
print("不存在!")
return False
else:
print("存在!")
return True
Call the method only requires the use of test.py in:
import defmath
You can call
More ways in the future will gradually supplement