python学习记录

文章目录

  • 字符串
  • 列表
  • if语句
  • 字典(键值对)
  • 输入和while循环
  • 函数
  • 文件和异常
  • 测试代码


字符串



message = " hEllo world"
# 首字母大写其他小写
print(message.title())
# 全大写
print(message.upper())
# 全小写
print(message.lower())

first_name = "adv"
last_name = "lovelace"
# f 是format格式的意思 将{变量}替换
full_name = f"{first_name} {last_name}"
print(full_name)
# 没有f就不会替换
print("hello {full_name}")
print(f"hello {full_name.title()}")
# 删除空格 (前面空格 lstrip 后面空格 rstrip 前后空格 strip)
print(message.lstrip())


# 加减乘除
print(2 * 3)
# 乘方 2^3
print(2 ** 3)
# 两个数相除 结果总是浮点数
print(4 / 2)
# 可以用下划线对数进行分组 方便阅读 并不会打印出来
universe_age = 1_000_000
print(universe_age)
# 多变量赋值
x, y, z = 1, 2, 3
print(x)
print(y)
print(z)

列表

  1. 基础
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
# 打印 包括 [] 括号
print(bicycles)
# 打印第一个 无括号引号
print(bicycles[0])
# 打印最后一个 (特有语法)-1 倒数第一个 -2 倒数第二个
print(bicycles[-1])
print(bicycles[-2])
message = f"My first bicycle is {bicycles[0].title()}."
print(message)
# 列表修改
bicycles[1] = "modify"
# 尾部添加
bicycles.append('add')
# 下标插入
bicycles.insert(0, 'insert')
# 删除下标
del bicycles[0]
x = bicycles.pop(0)
# 删除尾部 并返回尾部
rear = bicycles.pop()
print(rear)
# 删除具体值 remove 只删除第一个 后面的不会删除
bicycles.remove('redline')
# 排序
a = ['bbc', 'abd', 'fcc', 'eda', 'cxa']
# 按字母排序 
a.sort()
print(a)
# 降序
a.sort(reverse=True)
print(a)
# 临时排序,并不对列表永久修改
b = ['bbc', 'abd', 'fcc', 'eda', 'cxa']
print(sorted(a))
print(sorted(a, reverse=True))
# 列表反转 永久性修改 再调用一次复原
b.reverse()
print(b)
# 列表长度
length = len(b)
print(b)

  1. 操作
magicians = ['alice', 'david', 'carolina']
# for循环 循环体里面的语句 看缩进
for magician in magicians:
    print(f"{magician.title()}, that was a great trick")
    print("AA")
    print("BB")
# 列表最后一个元素
print(f"{magician.title()}, end")
# 打印1~5 range()最后一个不打印 range(6):0-5 range(1,6):1-5
for value in range(1, 6):
    print(value)
# 创建数字列表
numbers = list(range(1, 6))
print(numbers)
# 创建数字列表 设置步长(最后一个参数)
even_number = list(range(1, 11, 2))
print(even_number)
# 常见for循环
squares = []
for i in range(1, 11):
    squares.append(i ** 2)
print(squares)
# 最大值 最小值 和
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))
# 列表解析
nums = [value**2 for value in range(1, 11)]
print(nums)
# 打印列表从索引 i -> j-1  下面打印索引为0,1,2的元素,不指定前面参数i默认从0开始 下面两个相同【不指定后面参数默认打印到最后一个元素】
print(nums[0:3])
print(nums[:3])
print(nums[2:])
print(nums[-3:])
print(nums[0:6:2]) # 设置步长
for i in nums[2:]:
    print(i)
# 复制列表 下面是两个不同的对象  直接等于的话是指向同一个变量
nums_copy = nums[:]
# 元组 不可变的列表
dimensions = (200, 50, 40)
print(dimensions[0])
print(dimensions[1])
for value in dimensions:
    print(value)
dimensions = (1, 2, 3) # 元组不能直接修改,但是可以重新赋值
for value in dimensions:
    print(value)



if语句

year = 2023
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print("闰年")
else:
    print("平年")
# 包含类 in 和 not in
str = ['abc', 'efg', 'dcs']
if 'dcs' in str:
    print("包含")
else:
    print("不包含")
if 'dcs' not in str:
    print("XX")
else:
    print("XXX")
# elif
age = 17
if age < 10:
    print("baby")
elif 10 < age < 18:
    print("少年")
else:
    print("adult")
# 确定列表不为空
nums = []
if nums:
    print(nums)
else:
    print("list is empty.")

字典(键值对)

# 键值对赋值
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
# 添加键值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
# 修改键值对
alien_0['color'] = 'yellow'
print(alien_0['color'])
# 删除键值对
del alien_0['color']
# print(alien_0['color']) 报错KeyError: 'color'
# 这个不会报错,返回第二个参数,不指定第二个参数默认返回None
print(alien_0.get('color', 'No point value assigned.'))
# 遍历字典 键值
for key, value in alien_0.items():
    print(f"Key: {key} ,Value: {value}")
# 遍历键key 可以省略keys()方法,默认遍历key
for k in alien_0.keys():
    print(f"Key: {k.upper()}")
if 'color' not in alien_0.keys():
    print("please add color")
for k in sorted(alien_0.keys()):
    print(f"Key: {k.upper()}")
# 遍历所有的值 values()
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python'
    }
for language in favorite_languages.values():
    print(language)
# 去除重复项
print("\n")
for language in set(favorite_languages.values()):
    print(language)
# 字典嵌套
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 20}
alien_2 = {'color': 'green', 'points': 10}

aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
    print(alien)
# 字典中存储列表
pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheeses'],
    }
for topping in pizza['toppings']:
    print(topping)
# 字典中存储字典
users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
         },
    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
         },
    }
for k, v in users.items():
    print(k)
    print(v['first'])
    


输入和while循环

# input 输入字符串
message = input("Tell me something,and I will repeat it back to you: ")
print(message)
# int 将字符串转换为整型
age = input()
age = int(age)
print(age)
# while循环
current_number = 1
while current_number < 5:
    print(current_number)
    current_number += 1

while message != 'quit':
    message = input()
    print(message)

while True:
    message = input()
    if message == 'A':
        print("OK")
        break
    else:
        print("No")

while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue
    print(current_number)

users = ['alice', 'brian', 'candace']
add = []
while users:
    user = users.pop()
    print(f"Hello, {user.title()}")
    add.append(user)
print(add)

pets = ['cat', 'dog', 'goldfish', 'rabbit', 'cat', 'dog']
pets.remove('dog') # 只会删除第一个
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)


函数

  1. 操作
# 定义函数
def greet_user(username):
    print(f"Hello! {username.title()}.")


name = "baby"
greet_user(name)


# 设置默认值
def describe_pet(pet_name, animal_type='dog'):
    print(f"Hello, {pet_name.title()} {animal_type}.")


# 多种调用
describe_pet(pet_name='Alice')
describe_pet('Alice')
describe_pet(animal_type='cat', pet_name='AK')
describe_pet("PK", "goldfish")


# 带返回值 列表修改是永久性的
def all_sum(nums):
    total = 0
    for num in nums:
        total += num
    nums[0] = 9
    return total


a = [1, 2, 3, 4, 5]
print(all_sum(a))
# 函数是可以直接修改 列表实参的,可以传副本不修改,all_sum(a[:])
print(a)


# 传递任意数量的实参 *->创建一个元组
def make_pizza(size, *toppings):
    print(f"SIZE: {size}")
    for value in toppings:
        print(value)


make_pizza(12, 'A')
make_pizza(16, 'B', 'C', 'D')


# 任意数量的关键字实参 **->创建一个空字典
def build_profile(first, last, **user_info):
    user_info['first'] = first
    user_info['last'] = last
    return user_info


user_profile = build_profile('albert', 'einstein',
                             location='princeton',
                             field='physics')
print(user_profile)

  1. 调用其他模块
    python学习记录_第1张图片导入特定函数:from 模块 import *导入所有函数
    python学习记录_第2张图片可以用as起别名:模块和特定函数都可
from pizza import make_pizza as mp


mp(12, 'A')
mp(16, 'B', 'C', 'D')

# 创建类
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.master = "A"

    def sit(self):
        print(f"{self.name.title()} is now sitting.")

    def roll_over(self):
        print(f"{self.name} rolled over!")


my_dog = Dog("Alice", 11)
print(my_dog.master)
my_dog.sit()
my_dog.name = "ABCDE"
my_dog.roll_over()


# 继承

class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def get_describe(self):
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

    def speed(self):
        print(f"{self.model} 未知")


class ElectricCar(Car):
    def __init__(self, make, model, year, size):
        super().__init__(make, model, year)
        self.battery_size = size

    def describe_battery(self):
        print(f"battery is {self.battery_size}.")

    """重写"""
    def speed(self):
        print("fast")


my_tesla = ElectricCar('tesla', 'model s', 2019, 100)
print(my_tesla.get_describe())
my_tesla.describe_battery()
my_tesla.speed()

导入类 :from 模块 import 类名1,类名2


文件和异常

  1. 读写文件
# 读文件(全部内容) with不需要关闭文件(但对象只能在with代码块中有用) 单斜杠可行 但是遇到\t会有歧义 换成\\解决
with open('D:\\Documents\\txt\\pi_digits.txt') as file_object:
    contents = file_object.read()
print(contents)

# 逐行读取
with open('D:\\Documents\\txt\\pi_digits.txt') as file_object:
    for line in file_object:
        print(line.rstrip())

# 创建一个包含文件各行内容的列表
pi_str = ""
filename = "D:\\Documents\\txt\\pi_digits.txt"
with open(filename) as file_object:
    lines = file_object.readlines()
for line in lines:
    pi_str += line.strip()
    print(line)

print(pi_str)
"""输出8个字符"""
print(pi_str[:8])


# 写文件
# 读取模式 ('r')、写入模式 ('w' )、附加模式 ('a' )或读写模式 ('r+')
# 默认只读模式打开
# 写入的文件不存在,函数open() 将自动创建它
# 写入模式('w' )打开文件时,文件对象会清空该文件的内容,然后再写入
# Python只能将字符串写入文本文件。要将数值数据存储
# 到文本文件中,必须先使用函数str() 将其转换为字符串格式
filename = "D:\\Documents\\txt\\programming.txt"
with open(filename, 'w') as file_object:
    file_object.write("I love you.")

# 写入多行
with open(filename, 'w') as file_object:
    file_object.write("I love programming.\n")
    file_object.write("I love creating new games.\n")

# 附加到文件(不覆盖之前的)
with open(filename, 'a') as file_object:
    file_object.write("AAAA.\n")
    file_object.write("BBB.\n")

  1. 异常
# try-except 捕获异常
try:
    print(5 / 0)
except ZeroDivisionError:
    print("You can't divide by zero.")

# try-except-else : 将可能引发异常的放try,正常操作放else
try:
    answer = 5 / 1
except ZeroDivisionError:
    print("You can't divide by zero.")
else:
    print(answer)

filename = "D:\\Documents\\txt\\programming.txt"
try:
    with open(filename, encoding='utf-8') as f:
        content = f.read()
except FileNotFoundError:
    print(f"Not find {filename}")
else:
    """分割字符串空格-》列表"""
    words = content.split()
    num_words = len(words)
    print(num_words)
    """计算某个字符串出现的次数"""
    num = content.lower().count("i")
    print(num)

# pass 什么都不需要做
try:
    print(5 / 0)
except ZeroDivisionError:
    pass

  1. 存储数据JSON
import json

# 存储json数据
numbers = [1, 2, 3, 4, 5]

filename = "numbers.json"
with open(filename, 'w') as f:
    json.dump(numbers, f)

# 读json数据
nums = []
with open(filename) as f:
    nums = json.load(f)
print(nums)

测试代码

python学习记录_第3张图片测试用例可多个,测试不同功能。

测试结果:

通过python学习记录_第4张图片未通过
python学习记录_第5张图片
断言:

方法 用途
assertEqual(a, b) 核实a == b
assertNotEqual(a, b) 核实a != b
assertTrue(x) 核实x 为True
assertFalse(x) 核实x 为False
assertIn(item , list ) 核实 item 在 list 中
assertNotIn(item , list ) 核实 item 不在 list 中

类的测试:
python学习记录_第6张图片


你可能感兴趣的:(python,学习,开发语言)