目录
一 注释
# coding=utf-8
_author_ = 'liuzc'
# 打印hello
print("hello")
"""
多行注释
"""
print('hello...')
二 变量
# coding=utf-8
_author_ = 'liuzc'
qq_number = '123456'
print(qq_number)
# 定义苹果的价格
price = 8.5
# 重量
weight = 7.5
#计算付款金额
money = weight * price
print(money)
三 数据类型
# coding=utf-8
_author_ = 'liuzc'
"""
姓名:小明
年龄:18 岁
性别:是男生
身高:1.75 米
体重:75.0 公斤
"""
# 在 Python 中,定义变量时是不需要指定变量的类型的
# 在运行的时候,Python 解释器,会根据赋值语句等号右侧的数据
# 自动推导出变量中保存数据的准确类型
# str表示是一个字符串类型
name = '小明'
# int表示的是一个整数类型
age = 18
# bool表示是一个布尔类型 真True或者假False
gender = False # 不是
# float表示是一个小数类型 浮点数
height = 1.75
weight = 75
print(name)
四 格式化输出
# coding=utf-8
_author_ = 'liuzc'
# 定义字符串变量 name,输出 我的名字叫 小明,请多多关照!
name = "小明"
print("我的名字叫%s,请多多关照" %name)
# 定义整数变量 student_no,输出 我的学号是 000001
student_no = 1
print("我的学号是%06d" %student_no)
# 定义小数 price、weight、money,
# 输出 苹果单价 9.00 元/斤,购买了 5.00 斤,需要支付 45.00 元
price = 8.5
weight = 7.5
money = price * weight
print("苹果单价 %.2f 元/斤,购买了 %.3f 斤,需要支付 %.4f 元" % (price, weight, money))
# 定义一个小数 scale,输出 数据比例是 10.00%
scale = 0.8
print("数据比例是 %.2f%%" % (scale * 100))
五 if判断
# coding=utf-8
_author_ = 'liuzc'
age = 15
if age >= 18:
print("成年")
else:
print("未成年")
print("hello")
# coding=utf-8
_author_ = 'liuzc'
# 定义 holiday_name 字符串变量记录节日名称
holiday_name = "生日"
if holiday_name == "情人节":
print("买玫瑰")
elif holiday_name == "平安夜":
print("买苹果")
elif holiday_name == "生日":
print("买蛋糕")
else:
print("...")
六 while
6.1 break
# coding=utf-8
_author_ = 'liuzc'
i = 1
while i <= 5:
# break 某一条件满足时,退出循环,不再执行后续重复的代码
if i == 3:
break
print("hello")
i += 1
print("循环结束后 ,i = %d" % i)
6.2 continue
# coding=utf-8
_author_ = 'liuzc'
i = 0
while i < 10:
# continue 某一条件满足时,不执行后续重复的代码
# i == 3
if i == 3:
# 注意:在循环中,如果使用 continue 这个关键字
# 在使用关键字之前,需要确认循环的计数是否修改,
# 否则可能会导致死循环
i += 1
continue
print(i)
i += 1
七 函数
7.1 定义函数和函数返回值
# coding=utf-8
_author_ = 'liuzc'
# 注意:定义好函数之后,之表示这个函数封装了一段代码而已
# 如果不主动调用函数,函数是不会主动执行的
def say_hello():
print("hello 111")
say_hello()
def sum_2_num(num1,num2):
"""两个数字的求和"""
result = num1 + num2
# print("%d + %d = %d" %(num1,num2,result))
return result
sum_res = sum_2_num(1,3)
print(sum_res)
7.2 模块
# coding=utf-8
_author_ = 'liuzc'
def print_name(name):
print("hello %s" % name)
# coding=utf-8
_author_ = 'liuzc'
import com.wedoctor.print_name
com.wedoctor.print_name.print_name("lzc")
8 列表
8.1 列表的基本使用
# coding=utf-8
_author_ = 'liuzc'
name_list = ["zhangsan","lisi","wangwu"]
# 1.取值和取索引
print(name_list[2])
#根据数据的内容 确定数据在列表中的位置
print(name_list.index("wangwu"))
#2.修改
name_list[1] = "李四"
# 3.增加 append可以向列表的末尾追加数据
name_list.append("王小二")
#insert方法可以向列表的指定索引位置插入数据
name_list.insert(1,"美女")
# # extend 方法可以把其他列表中的完整内容,追加到当前列表的末尾
temp_list = ["孙悟空", "猪二哥", "沙师弟"]
name_list.extend(temp_list)
# 4.删除
#remove方法可以从列表中删除指定的数据
name_list.remove("wangwu")
# pop 方法默认可以把列表中最后一个元素删除
name_list.pop()
# pop 方法可以指定要删除元素的索引
name_list.pop(3)
# clear 方法可以清空列表
name_list.clear()
print(name_list)
8.2 列表的数据统计
# coding=utf-8
_author_ = 'liuzc'
name_list = ["张三", "李四", "王五", "王小二", "张三"]
# len(length 长度) 函数可以统计列表中元素的总数
list_len = len(name_list)
print("列表中包含 %d 个元素" % list_len)
# count 方法可以统计列表中某一个数据出现的次数
count = name_list.count("张三")
print("张三出现了 %d 次" % count)
# 从列表中删除第一次出现的数据,如果数据不存在,程序会报错
name_list.remove("张三")
print(name_list)
8.3 列表排序与遍历
# coding=utf-8
_author_ = 'liuzc'
name_list = ["zhangsan", "lisi", "wangwu", "wangxiaoer"]
# 升序
name_list.sort()
# 降序
name_list.sort(reverse=True)
# 逆序(反转)
name_list.reverse()
print(name_list)
for name in name_list:
print("我的名字叫 %s" % name)
9 元组
# coding=utf-8
_author_ = 'liuzc'
info_tuple = ("zhangsan",18,1.75,"zhangsan")
# 1.取值和索引
print(info_tuple[0])
# 已经知道数据的内容,希望知道该数据在元组中的索引
print(info_tuple.index("zhangsan"))
# 2. 统计计数
print(info_tuple.count("zhangsan"))
# 统计元组中包含元素的个数
print(len(info_tuple))
# 遍历
for info in info_tuple:
print(info)
10 字典
10,1 定义及基本使用
# coding=utf-8
_author_ = 'liuzc'
# 字典是一个无序的数据集合,使用print函数输出字典时,通常输出的顺序和定义的顺序是不一致的!
xiaoming_dict = {"name":"xiaoming","age":18,"gender":True,"height":1.75,"weight":75.5}
print(xiaoming_dict)
# 1. 取值
print(xiaoming_dict["name"])
# 2. 增加/修改
# 如果key不存在,会新增键值对
xiaoming_dict["age"] = 18
# 如果key存在,会修改已经存在的键值对
xiaoming_dict["name"] = "小小明"
# 3. 删除
xiaoming_dict.pop("name")
# 在删除指定键值对的时候,如果指定的key不存在,程序会报错!
print(xiaoming_dict)
10.2 字典的其他操作
# coding=utf-8
_author_ = 'liuzc'
xiaoming_dict = {"name": "小明","age": 18}
# 1. 统计键值对数量
print(len(xiaoming_dict))
# 2. 合并字典
temp_dict = {"height": 1.75,"age": 20}
# 注意:如果被合并的字典中包含已经存在的键值对,会覆盖原有的键值对
xiaoming_dict.update(temp_dict)
print(xiaoming_dict)
# 3. 清空字典
xiaoming_dict.clear()
print(xiaoming_dict)
10.3 字典遍历
# coding=utf-8
_author_ = 'liuzc'
xiaoming_dict = {"name": "小明",
"qq": "123456",
"phone": "10086"}
for kk in xiaoming_dict:
print(kk)
11 字符串
# coding=utf-8
_author_ = 'liuzc'
str1 = 'hello python python'
print(str1[4])
#统计字符串长度
print(len(str1))
# 2. 统计某一个小(子)字符串出现的次数
print(str1.count("py"))
# 3. 某一个子字符串出现的位置
print(str1.index("llo"))
# 1. 判断是否以指定字符串开始
print(str1.startswith("Hello"))
# 2. 判断是否以指定字符串结束
print(str1.endswith("python"))
# 3. 查找指定字符串
# index如果指定的字符串不存在,会报错,find如果指定的字符串不存在,会返回-1
print(str1.find("abc"))
# 4. 替换字符串
# replace方法执行完成之后,会返回一个新的字符串
# 注意:不会修改原有字符串的内容
print(str1.replace("python", "word"))
#循环遍历字符串
for char in str1:
print(char)
12 面向对象
12.1 面向对象基础
# coding=utf-8
_author_ = 'liuzc'
class Cat:
def __init__(self,new_name):
print("这是一个初始化方法")
self.name = new_name
def eat(self):
print("%s爱吃鱼" % self.name)
def __del__(self):
print("%s 我去了" % self.name)
def __str__(self):
#必须返回一个字符串
return "我是小猫[%s]" % self.name
# 创建猫对象 使用类名()创建对象的时候,会自动调用初始化方法 __init__
tom = Cat("aa")
#tom.name = 'tom'
tom.eat()
print(tom)
12.2 继承
12.2.1 单继承
# coding=utf-8
_author_ = 'liuzc'
class Animal:
def eat(self):
print("吃---")
def drink(self):
print("喝---")
def run(self):
print("跑---")
def sleep(self):
print("睡---")
class Dog(Animal):
def bark(self):
print("汪汪叫")
class XiaoTianQuan(Dog):
def fly(self):
print("我会飞")
def bark(self):
print("叫得好听...")
xtq = XiaoTianQuan()
# 如果子类中,重写了父类的方法
# 在使用子类对象调用方法时,会调用子类中重写的方法
xtq.bark()
12.2.2 多继承
# coding=utf-8
_author_ = 'liuzc'
class A:
def test(self):
print("test 方法")
class B:
def demo(self):
print("demo 方法")
class C(A, B):
"""多继承可以让子类对象,同时具有多个父类的属性和方法"""
pass
# 创建子类对象
c = C()
c.test()
c.demo()
13 异常
13.1 捕获异常
# coding=utf-8
_author_ = 'liuzc'
try:
a = 1/0
except ZeroDivisionError:
print("错误。。。")
except Exception as result:
print(result)
else:
print("成功。。。")
finally:
print("无论是否出现错误都会执行的代码")
13.2 抛出异常
# coding=utf-8
_author_ = 'liuzc'
def test(num):
if num >= 8:
return num
# 1> 创建异常对象 - 可以使用错误信息字符串作为参数
ex = Exception("不符合要求")
# 2> 主动抛出异常
raise ex
# 提示用户输入密码
test(2)
14 file文件操作
14.1 一次性读取文件
# coding=utf-8
_author_ = 'liuzc'
# 打开文件
file = open("d:\\people.txt")
# 读取文件内容
text = file.read()
print(text)
# 关闭文件
file.close()
14.2 分行读取文件
file = open("README")
while True:
text = file.readline()
# 判断是否读取到内容
if not text:
break
print(text)
file.close()
14.3 写文件
# coding=utf-8
_author_ = 'liuzc'
file = open("d:\\people.txt","a")
file.write("333333333333")
file.close()
14.4 复制文件
# 1. 打开
file_read = open("README")
file_write = open("REAMDE[复件]", "w")
# 2. 读、写
text = file_read.read()
file_write.write(text)
# 3. 关闭
file_read.close()
file_write.close()
14.5 复制大文件
# 1. 打开
file_read = open("README")
file_write = open("REAMDE[复件]", "w")
# 2. 读、写
while True:
# 读取一行内容
text = file_read.readline()
# 判断是否读取到内容
if not text:
break
file_write.write(text)
# 3. 关闭
file_read.close()
file_write.close()
15 正则表达式
# coding=utf-8
_author_ = 'liuzc'
import re
def main():
names = ["age", "_age", "1age", "age1", "a_age", "age_1_", "age!", "a#123", "__________"]
for name in names:
# ret = re.match(r"[a-zA-Z_][a-zA-Z0-9_]*", name)
# ^规定开头 $规定结尾
# python中的match默认是从头开始判断的所以,在match中可以不写^,但是match不会判断结尾,所以
# 当需要以xxx结尾的时候 还需要写上$
ret = re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$", name)
if ret:
print("变量名:%s 符合要求....通过正则匹配出来的数据是:%s" % (name, ret.group()))
else:
print("变量名:%s 不符合要求...." % name)
if __name__ == "__main__":
main()