- 一、PEP 8 规范
- 二、变量和简单数据类型
- 三、列表
- 四、if和循环
- 五、元组
- 六、字典
- 七、函数
- 八、类
- 九、文件读写
- 十、异常
- 十一、测试代码
编写代码时,符合规范这对大家都好,下面仅仅是一方面,还有很多规范,更多可以参考python PEP 8文档
1、每级缩进四个空格
2、每行都不要超过80个字符
3、不要在程序文件中使用过多空行
4、注释 # 后 要有一个空格
5、采用驼峰命名法
6、单引号和双引号作用相同
7、语句结尾可省略分号
python声明变量时,不用指明数据类型,解释器会根据实际数据类型自动推导
1、变量
name = "John" number = 4 print(type(name)) print(type(number)) print(type(number2)) --------------------------------------- # 结果
2、字符串
first_name = "ada" last_name = "dddd" full_name = f"{first_name} {last_name}" message = f"Hello,{full_name.title()}!" print(message)
f:是format 简写,通过花括号内的变量替换为其值来设置字符串的格式
title() :将字符串首字母大写
rstrip() :剔除字符串两两边的空白
lstrip() :剔除字符串左边的空白
strip() : 剔除字符串右边的空白
name = " python" print(name) print(name.strip()) ------------------------------------- # 结果 python python
3、数
乘方
# 计算4的三次方 print(4**3) ------------------------ # 结果 64
使用_对数字进行 分组 使其更加清晰
number3 = 10_000_000 print(number3) ------------------------- # 结果 10000000三、列表
dogs = ["a", "d", "e", "f"] print(dogs) dogs.insert(1, "g") # 在列表下标为1增加一个元素 del dogs[0] # 删除列表中小标为0 dogs[2] = "m" # 修改 dogs.append("w") # 末尾追加 print(dogs) x = dogs.pop() # 删除末尾元素并返回 类似于栈 print(x) print(len(dogs)) # 求长度 dogs.remove("d") # 根据值删除 print(dogs) dogs.reverse() # 将列表反转 print(dogs) ------------------------------------------- # 结果 ['a', 'd', 'e', 'f'] ['g', 'd', 'm', 'f', 'w'] w 4 ['g', 'm', 'f'] ['f', 'm', 'g'] Process finished with exit code 0
2、切片
处理列表的一部分元素,称之为切片
players = ["ok", "sw", "dw", "oo", "fs"] print(players[1:3]) # 返回索引 1-2的元素 print(players[1:]) # 返回索引 1-列表末尾的元素 ''' 两边都为空表示 返回从头到尾的元素 ''' gamer = players[:] print(gamer) -------------------------- ['sw', 'dw'] ['sw', 'dw', 'oo', 'fs'] ['ok', 'sw', 'dw', 'oo', 'fs']
3、复制列表
四、if和循环elif 就相当于 else if
b = eval(input("请输入:")) # 类型转换成 输入的类型 自动转换 if b >= 18: print("hello") elif b >= 13: print("Yes") elif b >= 8: print("happy") else: print("No") for i in range(b): # [0,b) print(i) for i in range(10, 30): # [10,30) print(i) for i in range(10, 30, 2): # [10,30) 步长为2 print(i) while i <= 5: print(i) i+=1
numbers = list(range(5, 10)) # 转换成列表输出 print(numbers) ------- [5, 6, 7, 8, 9]
numbers = range(1, 20) print(min(numbers)) # 求最小值 print(sum(numbers)) # 求最和 print(min(numbers)) # 求最小值 ----------------------- 1 190 19五、元组
列表适合用于存储在程序运行期间可能引起变化的数据集,列表是可以修改
不可变的列表称为元组.
dimensions = (20, 60, 80) print(dimensions[0]) print(dimensions) -------------------------------- 20 (20, 60, 80)六、字典
字典相当于java中的map集合,使用键值对存储数据
cats = {"name": "john", "age": 20} print(cats) a = cats.get("name", "john") print(cats.values()) for key, value in cats.items(): print(f"{key}") print(f"{value}") ------------------------------- {'name': 'john', 'age': 20} dict_values(['john', 20]) {'name': 'john', 'age': 20} dict_values(['john', 20]) name john age 20 """ items:返回所有键值对列表 keys:返回所有键 valuse:返回所有值 """
字典也可以存储列表
users = {"manage": { "name": "Tom", "age": 30, "location": "A", }, "student": { "name":"mae", "age":20, "location":"S", }, } ----------------------------------- {'manage': {'name': 'Tom', 'age': 30, 'location': 'A'}, 'student': {'name': 'mae', 'age': 20, 'location': 'S'}}七、函数
定义:
def 函数名(形式参数)
def amb(a, b): return (a + b) ** 2 print(amb(1, 3)) # 可以使用默认值 def amb(a, b=3): return (a + b) ** 2 print(amb(1)) ------------------------- 16 16
# 如何传任意个数的实参 args 相当于一个元组 与java相同 def js(*args): print(args) js("a", "b", "c") js("e", "f") ('a', 'b', 'c') ('e', 'f')
将函数存储在模板中
# test07 def amb(a, b=3): return (a + b) ** 2 --------------------- """ improt test07 as t:导入整个模板 as可以起别名 非必选 t.amb(2, 3) """ from test07 import amb #导入特定的函数 print(amb(1, 2))八、类
init():为构造函数
形参self必不可少
每个方法定义都有self。以self为前缀的变量可供类中所有的方法适合于
# test09 class Dog: def __init__(self, name, age): self.name = name self.age = age def bite(self): print("wangwang") --------------------------------- import test09 as t my_dog = t.Dog('Yel', 5) my_dog.bite() --------------------------------- # 结果: wangwang
继承:
在继承类定义在类名后加括号写上继承的类
class Dog: def __init__(self, name, age): self.name = name self.age = age def bite(self): print("wangwang") class BlueDog(Dog): def __init__(self, name, age, log): super().__init__(name, age) self.log = log def describe(self): print(f"{self.name} {self.age} {self.log}") --------------------------------------------- Wa 20 mm九、文件读写
# 写入文件 with open("username", 'w') as file_object: file_object.write("I Love Pythonn") file_object.write("I also love Javan") ----------------------------- I Love Python I also love Java """ 第二个参数 w:表示写,会覆盖原有内容 a: 表示在原有文件后追加内容 """
# 读取文件 with open("username") as file_object2: contents = file_object2.read() print(contents) """ readlines():表示读取一行 """ with open("username") as file_object2: lines = file_object2.readlines() p_string = '' for line in lines: p_string += line.rstrip() print(p_string) -------------------------------------- I Love PythonI also love Java十、异常
1、ZeroDivisionError 异常
try: print(5 / 0) except ZeroDivisionError: print("not divide by zero!" ----------------------------------- not divide by zero!
2、FileNotFoundError 异常
try: with open("username", 'w') as file_object: file_object.write("I Love Pythonn") file_object.write("I also love Javan") except FileNotFoundError: print("File not exist")
3、else 代码块
a = int(input("input a number: ")) try: b = 5 / a except ZeroDivisionError: print("not divide by zero!") else: print(b) ----------------------------- input a number: 0 not divide by zero! input a number: 1 5.0十一、测试代码
# test09 class Dog: def __init__(self, name, age): self.name = name self.age = age def bite(self): print("wangwang") class BlueDog(Dog): def __init__(self, name, age, log): super().__init__(name, age) self.log = log def describe(self): print(f"{self.name} {self.age} {self.log}") ------------------------------------------------ import unittest import test09 as t class DogTestCase(unittest.TestCase): def test_describe(self): my_dog = t.BlueDog("john", 18, "hahaha") my_dog.describe()
# 运行结果: Testing started at 22:10 ... Ran 1 test in 0.003s OK Launching unittests with arguments python -m unittest test12.DogTestCase.test_describe in D:pythonProjectExer Process finished with exit code 0 john 18 hahaha
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)