开始创建
简单格式
def function():
return 'Charles'
print(function())
摄氏度转化公式
def fahrenheit_converter(C):
fahrenheit = C * 9 / 5 + 32
return str(fahrenheit) + 'F'
C2F = fahrenheit_converter(35)
print(C2F)
重量转换器
def g2kg(g):
kg = g / 1000
return str(kg) + 'kg'
print(g2kg(666))
求直角三角形斜边长的函数
def cal_tri(i,j):
k = (i*i + j*j) ** 0.5
return 'The right triangle third side\'s length is ' + str(k)
print(cal_tri(3,4))
传递参数与参数类型
def trapezoid_area(base_up,base_down,height):
return (base_up + base_down) * height * 1/2
分为位置参数,关键词参数
trapezoid_area(1,2,3)
trapezoid_area(base_up=1,base_down=2,height=3)
trapezoid_area(height = 3,base_down = 2, base_up = 1)
trapezoid_area(base_up = 1, base_down = 2,3)
trapezoid_area(height = 3,base_down = 2,1) #Wrong
设计敏感词过滤的函数(win10)
def text_create(name,msg):
desktop_path = 'C:/Users/ASUS/Desktop/'
full_path = desktop_path + name + '.txt'
file = open(full_path,'w')
file.write(msg)
file.close()
print('Done!')
# text_create('text','hello Mr.Charles') #调用函数
def text_filter(word,censored_word = 'ugly',changed_word = 'handsome'):
return word.replace(censored_word,changed_word)
text_filter('Python is lame!')
def censored_text_create(name,msg):
clean_msg = text_filter(msg) #调用前两个函数 text_create() 和 text_filter()
text_create(name,clean_msg)
censored_text_create('try','ugly!ugly!ugly!')