1.环境安装
1. 下载安装
2.测试是否安装成功
win+R==>cmd==》输入python
2.Pycharm安装
下载免费的 社区版PyCharm (不支持Web开发)
3.项目配置
单行注释:以#+空格开头
多行注释:以三个英文单引(‘’‘)号开头,三个英文单引号结尾(’‘’)
2.关键字和标识符
关键字:引入keyword模块,通过kwlist变量查看
标识符:区分大小写,不能以数字开头
1.变量是装各种不同类型值的容器
2.变量定义格式:变量名=变量值
4.数字类型
1.整型(int):不带小数的整数,有正负
2.浮点型(float):带有小数的数字
5.布尔类型
True和False,首字母要大写
6.输入输出
1.输入函数
str input(输入提示) #使用input函数接收用户输入的信,input函数返回用户输入的信息为字符串类型
2.输出函数
print(变量值) #结束符默认为换行 print(变量值,end='结束符') #用户自定义结束符 print("\\n") #打印转义字符\n
7.运算符
算术:加(+)、减(-)、乘(*)、除(/)、幂(**)、取模(%)、取整(//)
逻辑:非(not),与(and),或(or)
8.格式化字符串
name = '小谢' age = 21 hobby = '喜欢学习' high = 175.3 # 1.两个字符串的拼接 s = name + hobby print(s) # 2.使用格式化符号,实现对字符串的格式化 print("姓名:%s" % name) print("身高:%f 厘米" % high) print("姓名:%s,年龄:%d,身高:%.1f 厘米" % (name, age, high)) # 3.format格式化函数 print("姓名:{},年龄:{},身高:{:.1f} 厘米".format(name, age, high))
9.字符串内置方法
s = "hello world hello python" s1 = "world" s2 = "hello" # 在s中寻找s1 print(s.find(s1)) # 6 print(s.find(s1, 0, -1)) # 6 # 统计s中s2出现的次数 print(s.count(s2)) # 2 print(s.count(s2, 0, -1)) # 2 # 替换s中的"hello"为"hi" print(s.replace("hello", "hi")) # hi world hi python print(s.replace("hello", "hi", 1)) # hi world hello python # 按照指定的分割符分割字符串 print(s.split(" ")) # ['hello', 'world', 'hello', 'python'] print(s.split(" ", 2)) # ['hello', 'world', 'hello python'] # 判断s是否以hello开头或者python结尾 print(s.startswith("hello")) # True print(s.endswith("python")) # True # 将字符串大/小写化 print(s1.upper()) # WORLD print(s1.lower()) # world # 将一个序列中的多个字符串元素拼接成一个完整的字符串,序列可以是元组、列表等 print(",".join(["小谢", str(20), "北京"])) # 小谢,20,北京 # 默认可以去掉字符串开头和结尾的空白字符,也可以把要去掉的字符作为参数传入 print(" sss\n\t ".strip()) # sss print(",,,sss,,,".strip(",")) # sss
10.逻辑结构
if条件判断
degree = int(input("输入成绩:")) if 0 <= degree < 60: print('不及格') elif 60 <= degree < 85: print('良好') elif 85 <= degree <= 100: print('良好') else: print('无效成绩')
while条件循环
# 计算1+2+3+...+100 s, n = 0, 1 while n <= 100: s = s + n n += 1 print(s) # 5050
for遍历循环/break跳出循环
# 打印1到20的偶数,当遇到10的整数倍数字时,结束整个循环 i = 1 for i in range(1, 21): if i % 2 == 0: if i % 10 == 0: break print(i, end=",")
1.列表(list)
列表特点
列表元素有序
列表元素类型可同可不同
使用一对[]定义
元素之间用逗号隔开
列表元素可变
列表遍历
name_list = ["小红", "小明", "小军"] info_list = ["小明", 20, "男", 175.3, True] print(type(name_list)) #print(type(info_list)) # print(name_list) # ['小红', '小明', '小军'] print(info_list) # ['小明', 20, '男', 175.3, True] # 使用for循环遍历列表 for i in range(0, len(info_list)): print(info_list[i], end=",") # 小明,20,男,175.3,True, print() for item in info_list: print(item, end=",") # 小明,20,男,175.3,True,
列表基本操作
# 增 name_list.append("小谢") # 在列表末尾添加一个元素 name_list.insert(0, "小丁") # 在指定位置添加元素 # 删 del name_list[-1] # 删除列表中索引为-1的元素 name_list.remove("小丁") # 删除列表中所有元素值为"小丁"的元素
列表切片
list[start : end : step] :切片的截取范围是左闭右开
列表元素排序
sort():升序排列
sort(reverse = True):降序排列
2.元组(tuple)
元组特点:
类似列表,区别是一旦定义完成,只能访问,不能增,删,改元组元素
使用一对小括号表示,如tp=(1,2,3)
定义只包含一个元素的元组时,在元素的后边要多添加一个逗号
3.字典(dict)
字典特点:
存储key:value键值对
使用一对{}定义,字典中的一个元素就是一个键值对,多个元素之间用逗号隔开
user_info_dict = { "name": "小谢", "age": 21, "gender": "male"} name = user_info_dict["name"] print("name: {}".format(name)) age = user_info_dict.get("age") print("age: {}".format(age)) # 增 user_info_dict["tel"] = "119" print("tel:{}".format(user_info_dict.get("tel"))) # 改 user_info_dict["tel"] = "120" print("tel:{}".format(user_info_dict.get("tel"))) # 删 del user_info_dict["tel"] print("tel:{}".format(user_info_dict.get("tel"))) print() # for循环遍历字典 # 遍历字典的键序列,通过键获得对应的值 for key in user_info_dict.keys(): print("{}:{}".format(key, user_info_dict.get(key))) # 遍历字典的值序列 for value in user_info_dict.values(): print(value) # 遍历字典的键值对元组,key:value ==》(key,value) for item in user_info_dict.items(): print("{}:{}".format(item[0], item[1]))
4.集合(set)
集合特点:
元素无序不重复
元素类型相同或不同
使用一对{}定义,元素是独立的
元素不可变
创建集合:
id_set = { 1, 2, 3, 4, 2, 3, 4} id_list = [11, 12, 12, 12, 13, 14, 14, 15, 16, 17] id_list_set = set(id_list) name_str = "贾浅浅" name_set = set(name_str) id_tuple = (11, 12, 12, 12, 13, 14, 14, 15, 16, 17) id_tuple_set = set(id_tuple) id_name_dict = { 1: "明", 2: "慧", 3: "聪"} id_name_dict_set = set(id_name_dict) print(id_set) # {1, 2, 3, 4} print(id_list_set) # {11, 12, 13, 14, 15, 16, 17} print(name_set) # {'贾', '浅'} print(id_tuple_set) # {11, 12, 13, 14, 15, 16, 17} print(id_name_dict_set) # {1, 2, 3}
集合操作
id_set = { 1, 2, 3, 4, 5, 6} # 增 id_set.add(7) print(id_set) # {1, 2, 3, 4, 5, 6, 7} # 删 id_set.remove(1) print(id_set) # {2, 3, 4, 5, 6, 7} id_set.discard(2) print(id_set) # {3, 4, 5, 6, 7} id = id_set.pop() print(id) # 3 print(id_set) # {4, 5, 6, 7} id_set.update([6, 7, 8, 9]) print(id_set) # {4, 5, 6, 7, 8, 9}
集合运算
id1_set = { 1, 2, 3, 4, 5, 6} id2_set = { 4, 5, 6, 7, 8, 9} # 并 print(id1_set | id2_set) # {1, 2, 3, 4, 5, 6, 7, 8, 9} # 交 print(id1_set & id2_set) # {4, 5, 6} # 差 print(id1_set.difference(id2_set)) # {1, 2, 3}
1.函数定义
def 函数名(参数): 函数体 return 返回值
2.函数传参
def x_y_sum(x, y=1): s = x + y return s print(x_y_sum(2)) # 3 print(x_y_sum(2, 3)) # 5 print(x_y_sum(y=3, x=1)) # 4
3.不定长参数
def many_sum(*args): print(args) print(type(args)) rs = 0 if len(args) > 0: for arg in args: rs += arg return rs print(many_sum(1, 2, 3, 4, 5, 6)) num_list = [1, 2, 3, 4, 5, 6] print(many_sum(*num_list)) # 传递列表需要进行拆包 ''' (1, 2, 3, 4, 5, 6)21 '''
4.不定长键值对参数
def pay(basic, **kvargs): print(kvargs) print(type(kvargs)) tax = kvargs.get("tax") social = kvargs.get("social") return basic - tax - social print(pay(8000, tax=500, social=1500)) fee_dict = { "tax": 500, "social": 1500} print(pay(8000, **fee_dict)) ''' {'tax': 500, 'social': 1500}6000 '''
项目->包->模块
包=普通文件夹+_ init_ .py
模块=以“.py”结尾的Python文件
一个包中必须包含一个默认的__init__.py模块
_ init_ .py的作用:模块内可以是空白内容用于标识一个包,也可以在模块内定义关于包和模块相关的一些初始化操作
1.类的定义
class 类名: def 方法名(self[,参数列表]): 方法体
2.创建对象
class Dog: def __init__(self, name): # 类的初始化方法 self._name = name # 以下划线开头的变量为私有变量,只能在类内部访问 print("狗的名字是{}".format(self._name)) def eat(self): print("{}正在啃骨头...".format(self._name)) wc = Dog("旺财") wc.eat() ''' 狗的名字是旺财 旺财正在啃骨头... '''
3.单继承
class Animal: def __init__(self, name): self.name = name def eat(self): print("{}吃东西".format(self.name)) class Dog(Animal): # 子类可以继承父类的非私有属性和方法 # 子类无构造方法,则会调用父类的构造方法 def hand(self): print("{}与人握手".format(self.name)) wc = Dog("旺财") wc.eat() wc.hand() ''' 旺财吃东西 旺财与人握手 '''
4.super函数
实现在子类中调用父类的方法
class Animal: def __init__(self, name): self.name = name def eat(self): print("{}吃东西".format(self.name)) class Dog(Animal): def hand(self): print("{}与人握手".format(self.name)) super().eat() # 在子类方法中调用父类的方法 wc = Dog("旺财") wc.hand() ''' 旺财与人握手 旺财吃东西 '''
在子类中定义与父类同名的方法。当调用子类对象重写之后的方法时,只会调用在子类中重写的方法,不会调用父类同名的方法
class Animal: def __init__(self, name): self.name = name def eat(self): print("{}吃东西".format(self.name)) class Dog(Animal): def hand(self): print("{}与人握手".format(self.name)) def eat(self): # 重写父类中的eat方法的实现 print("{}啃骨头".format(self.name)) wc = Dog("旺财") wc.eat() ''' 旺财啃骨头 '''
6.多继承
一个类可以继承多个类的非私有方法
try: 可能产生异常的代码块 except ExceptionType as err: 异常处理 finally: 无论是否发生异常,都要执行的操作
1.time模块
import time # 获取时间戳 ts = time.time() # 时间戳 # 时间戳==>时间元组 datetime = time.localtime() # 默认将当前本地时间戳转化为时间元组 ts_tuple = time.localtime(1662095487.8619611) # 将给定时间戳转化为时间元组 # 时间元组==>格式化字符串 print(time.strftime("当前时间:%Y-%m-%d %H:%M:%S")) # 默认将当前本地时间转化为格式化格式输出 print(time.strftime("指定时间:%Y-%m-%d %H:%M:%S", time.localtime(1662095487.8619611))) # 将指定时间元组转化为格式化格式输出 # 格式化字符串==>时间元组 time_tuple = time.strptime("2022-09-02 13:25:35", "%Y-%m-%d %H:%M:%S") # 时间元组==>时间戳 ts1 = time.mktime(time.localtime())
2.datetime模块
import datetime import time # 默认格式 current_time = datetime.datetime.now() print(current_time) # 2022-09-02 14:37:12.918474 print(current_time.year) # 2022 print(current_time.month) # 9 print(current_time.day) # 2 # 默认格式==>自定义格式 format_time = current_time.strftime("%Y/%m/%d %H:%M:%S") print(format_time) # 2022/09/02 14:41:19 # 时间戳==>默认格式 ts = time.time() default_format_time = datetime.datetime.fromtimestamp(ts)
使用open函数打开文件,返回一个文件对象,就可以对文件进行操作
文件对象 = open(文件路径,操作方式)
操作方式:只读(r),覆写(w),追加(a)
写没有则创建,读没有则报错
1.写文件
f = open("1.text", "w") f.write("Hello,world!\n") f = open("1.text", "a") f.write("Hello,python!\n") f = open("1.text", "a", encoding="utf-8") f.writelines(["1\n", "2\n", "3\n"]) f.close() with open("1.text", "a", encoding="utf-8") as f: f.writelines(["4\n", "5\n", "6\n"]) # 1.txt ''' Hello,world! Hello,python! 1 2 3 4 5 6 '''
2.读文件
with open("1.text", "r", encoding="utf-8") as f: data = f.read() print(data) ''' Hello,world! Hello,python! 1 2 3 4 5 6 ''' with open("1.text", "r", encoding="utf-8") as f: list_data = f.readlines() print(list_data) # ['Hello,world!\n', 'Hello,python!\n', '1\n', '2\n', '3\n', '4\n', '5\n', '6\n']
3.文件管理
import os # 获取项目的绝对路径 p_cwd = os.getcwd() print(p_cwd) # D:\Learning\python\firstPro # 获取路径下的文件列表 print(os.listdir(p_cwd)) # ['.idea', '1.text', 'buss', 'main.py', 'tool'] # 创建一个文件夹 os.mkdir(p_cwd + "\\os") # 删除一个空文件夹 os.rmdir(p_cwd + "\\os") # 删除指定文件 os.remove(p_cwd + "\\1.txt")
import re # 按照模式从左到右进行匹配,不匹配则匹配失败 hello_str = "Hello,python!" rs = re.match("Hello", hello_str) print(rs) #print(rs.group()) # Hello
1.单字符匹配
2.数量表示
3.边界表示
点击下方名片获取更多学习知识~