1,函数
# 函数, 重新认识函数
# print() # 是一个放入对象就能将结果打印的函数
# input() # 是一个可以让用户输入信息的函数
# len() # 是一个可以测量对象长度的函数
# int() # 是一个可以将字符串类型的数字转换成整数类型的数字
2,创建函数
# 创建函数,定义函数
# def (即define,定义)的含义是创建函数,即定义一个函数
# arg (即argument,参数)还会有一种写法parameter,都是参数的意思,稍有不同
# return (即返回结果)
# def function(arg1 , arg2):
# return 'Something'
# 例:定义摄氏度转换华氏度
# def c_f(c): # 定义函数
# f = c * 9 / 5 + 32
# return str(f) + '°F' # 返回结果
#
#
# C2F = c_f(35) # 调用函数
# print(C2F) # 打印结果
# 练习题1
# 输入g转换为kg
# def g_kg(a): # a为参数
# kg = a / 1000
# return str(kg) + 'kg'
#
#
# G_KG = g_kg(90) # 调用
# print(G_KG)
# 练习题2
# 直角三角形,直角边为参数,求斜边长
# def z_x(a, b): # a b 为直角边参数
# x = (a ** 2 + b ** 2) ** (1/2)
# return str(x) + '是斜边长'
#
#
# ZX = z_x(3, 4) # 调用
# print(ZX)
3,传递参数,默认参数
# 传递参数:位置参数和关键词参数
# 默认参数,定义参数的时候给参数赋值
# print(' *', ' * *', '* * *', ' | ', sep="\n") # 打印一颗圣诞树
4,设计自己的函数
# 设计自己的函数
file = open('D://桌面文件/text.txt' , 'w')
file.write('hello world')
# 定义函数,创建一个文本文件,命名,添加内容
def text_create(name, msg):
desktop_path = 'D://桌面文件/'
full_path = desktop_path + name + '.txt'
file = open(full_path, 'w')
file.write(msg)
file.close()
print('Done')
text_create('1', '123456') # 调用函数
# # 敏感词过滤
def text_filter(word, censored_word='lame', changed_word='Awesome'):
return word.replace(censored_word, changed_word) # 替换敏感词为其他字符
text_filter('Python is lame!')
print(text_filter('Python is lame!')) # 调用函数并打印结果
def censored_text_create(name, msg): # 定义函数,创建一个文本文件,命名,添加内容,并过滤敏感词
clean_msg = text_filter(msg) # 调用函数,过滤敏感词
text_create(name, clean_msg) # 调用函数,创建文本文件
censored_text_create('Try', 'lame!,lame!,lame!') # 调用函数
print(censored_text_create('Try', 'lame!,lame!,lame!')) # 调用函数并打印结果
5,python中的关键字
共有33个关键字,只有False,None,True的首字母大写,其他关键字均为小写:
6,标识符
(区分大小写,首字符可以是下划线或字母,但不能是数字,除首字符外的其他字符必须是下划线,字母和数字,关键字不能作为标识符,不要使用python的内置函数作为自己的标识符)
特殊注释:# coding = utf-8 ,告诉python解释器,该文件的编码集是UTF-8
7,实现两个模块间的代码元素访问
# 两个模块在同一文件下的Y1.py和Y2.py
# 模块一:Y1
w = '王'
b = True
y = 888.0
# 模块二:Y2
import Y1 # 导入Y1模块中所有代码元素
from Y1 import y # 导入Y1模块中的变量y
from Y1 import w as w2 # 导入Y1模块中变量w,并给它别名w2
w = 100
b = 99
print(b) # 访问当前模块变量b
print(Y1.b) # 访问Y1模块变量b
print(y) # 访问Y1模块变量y
print(w2) # w2是Y1模块w的别名
# 打印结果如下:
99
True
888.0
王