记录Python入门学习日常,强烈推荐b站up主林粒粒呀的视频
先放一些常用的官方链接
Python官方文档
Python第三方库
前半部分为学习过程中的一些笔记,后半部分为具体代码实现
转义符 \
print("hello")
print("He said \"let's go!\"")
换行符 \n
print("Hello!\nHi!")
三引号换行 '''xxx'''
print('''落霞与孤鹜齐飞
秋水共长天一色''')
greet = "你好,吃了吗,"
greet_chinese = greet
greet_english = "Yo what's up,"
print(greet_english + "A")
print(greet_english + "B")
print(greet_english + "C")
print(greet_chinese + "张三")
乘方运算符 **
带余除法 %
除完后向下取整 //
注释符号 #
or 使用快捷键选中文本 command + /
字符串 str
整数 int
浮点数 float
and 布尔类型
其中 int() 为向下取整
索引 []
python中从0开始计数
逻辑符号 与 或 非 and``````or``````not
append
方法添加列表元素 remove
方法移除列表元素
列表 []
字典 {}
元组tuple ()
删除字典中的键 del
del my_dict["a"]
keys
方法返回所有键
values
方法返回所有值
items
方法返回所有键值对
format
方法替换文字 ( f
方法也可以用来替换文字)
gpa_dict = {"小明": 3.251, "小花": 3.869}
for name, gpa in gpa_dict.items():
print("{0}你好,你的当前绩点为:{1:.2f}".format(name,gpa))
# :.2f 表示浮点数格式化保留位数
str('%.2f'% result)
同样起到保留两位小数的效果
read
读取文件 readline
读取单行 readlines
读取全部行后返回列表
f = open("./data.txt", "r", encoding = "utf-8")
# "r"为只读模式, "w"为写入模式, "a"为添加模式, "r+"为读写模式
print(f.read(10)) # 读取第1-10个字节的文件内容
f.close() # 关闭文件,释放资源
更为简洁写法为
with open("./data.txt") as f:
print(f.read())
# 读取后会自动关闭
代码实现
1. print
print("hello")
print("He said \"let's go!\"")
print("Hello!\nHi!")
print('''落霞与孤鹜齐飞
秋水共长天一色''')
2. variables
greet = "你好,吃了吗,"
greet_chinese = greet
greet_english = "Yo what's up,"
print(greet_english + "A")
print(greet_english + "B")
print(greet_english + "C")
print(greet_chinese + "张三")
3. math
import math
a = -1
b = -2
c = 3
delta = b**2 - 4 * a *c
print((-b + math.sqrt(delta))/(2 * a))
print((-b - math.sqrt(delta))/(2 * a))
4. input
# BMI = 体重 / (身高 ** 2)
user_weight = float(input("请输入您的体重(单位:kg):"))
user_height = float(input("请输入您的身高(单位:m):"))
user_BMI = user_weight / (user_height) ** 2
print("您的BMI值为" + str(user_BMI))
5. condition
mood_index = int(input("对象今天的心情指数是:"))
if mood_index >= 60:
print("恭喜,今晚应该可以打游戏,去吧皮卡丘!")
else:
print("为了自个儿小命,还是别打了")
6. conditions
# BMI = 体重 / (身高 ** 2)
user_weight = float(input("请输入您的体重(单位:kg):"))
user_height = float(input("请输入您的身高(单位:m):"))
user_BMI = user_weight / (user_height) ** 2
print("您的BMI值为" + str(user_BMI))
# 偏瘦:user_BMi <= 18.5
# 正常:18.5 < user_BMI <= 25
# 偏胖:25 < user_BMI <= 30
# 肥胖:user_BMI >30
if user_BMI <= 18.5:
print("此BMI值属于偏瘦范围。")
elif 18.5 < user_BMI <= 25:
print("此BMI值属于正常范围。")
elif 25 <user_BMI <= 30:
print("此BMI值属于偏胖范围。")
else:
print("此BMI值属于肥胖范围。")
7. list
shopping_list = []
shopping_list.append("键盘")
shopping_list.append("键帽")
shopping_list.remove("键帽")
shopping_list.append("音响")
shopping_list.append("电竞椅")
shopping_list[1] = "硬盘"
print(shopping_list)
print(len(shopping_list))
print(shopping_list[0])
price = [799, 1024, 200, 800]
max_price = max(price)
min_price = min(price)
sorter_price = sorted(price)
print(max_price)
print(min_price)
print(sorter_price)
8. dictionnary
slang_dict = {"a": "a的含义是xx",
"b": "b的含义是xx"}
slang_dict["c"] = "c的含义是xx"
slang_dict["d"] = "d的含义是xx"
del slang_dict["a"]
query = input("请输入您想要查询的字母:")
if query in slang_dict:
print("您查询的" + query + "含义如下:")
print(slang_dict[query])
else:
print("您查询的字母暂未收录。")
print("当前本词典收录的字母数为:" + str(len(slang_dict)) + "个。")
9. loop
print("哈喽哈喽!我是一个求平均值的程序")
total = 0
count=0
user_input = input("请输入数字(完成所有数字输入后,请输入q终止程序):")
while user_input != "q":
num = float(user_input)
total += num
count += 1
user_input = input("输入数字(完成所有数字输入后,请输入q终止程序):")
if count == 0:
result = 0
else:
result = total / count
print("您输入的数字平局值为" + str (result))
10. format
gpa_dict = {"小明": 3.251, "小花": 3.869}
for name, gpa in gpa_dict.items():
print("{0}你好,你的当前绩点为:{1: .2f}".format(name,gpa))
11. def
def calculate_sector(central_angle, radius):
sector_area = central_angle / 360 * 3.14 * radius ** 2
print(f"此扇形面积为:{sector_area}")
return sector_area
calculate_sector(30, 16)
12. function
def calculate_BMI(weight, height):
BMI = weight / height ** 2
if BMI <= 18.5:
category = "偏瘦"
elif BMI <= 25:
category = "正常"
elif BMI <= 30:
category = "偏胖"
else:
category = "肥胖"
print(f"您的BMI分类为:{category}")
return BMI
result = calculate_BMI(70,1.8)
print("您的BMI值为:" + str('%.2f'% result))
# '%.2f'% result 为保留两位小数
13. plot
from matplotlib import pyplot as plt
import numpy as np
x = list(np.arange(-2,2,0.1))
y = []
for i in range(len(x)):
y.append(np.log(1 + x[i] ** 2))
plt.figure()
plt.plot(x,y)
plt.show()
14. class
class CuteCat:
# 定义类的属性
def __init__(self, cat_name, cat_age, cat_color):
self.name = cat_name
self.age = cat_age
self.color = cat_color
# 定义类的方法
def speak(self):
print("喵" * self.age)
def think(self, content):
print(f"小猫{self.name}在思考{content}…")
cat1 = CuteCat("Jojo", 2, "橙色")
print(f"小猫{cat1.name}的年龄是{cat1.age}岁,花色是{cat1.color}")
cat1.speak()
cat1.think("现在去抓沙发还是撕纸箱")
15. class_2
class Student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
self.grades = {"语文": 0, "数学": 0,"英语": 0}
def set_grade(self, course, grade):
if course in self.grades:
self.grades[course] = grade
def print_grades(self):
print(f"学生{self.name}(学号:{self.student_id})的成绩为:")
for course in self.grades:
print(f"{course}:{self.grades[course]}分")
chen = Student("小陈", "100618")
chen.set_grade("语文", 92)
chen.set_grade("数学", 95)
chen.print_grades()
li = Student()
li.print_grades()
16. inheritance
class Employee:
def __init__(self, name, id):
self.name = name
self.id = id
def prin_info(self):
print(f"姓名:{self.name},工号:{self.id}")
class FullTimeEmployee(Employee):
def __init__(self, name, id, monthly_salary):
super().__init__(name, id)
self.monthly_salary = monthly_salary
def calculate_monthly_pay(self):
return self.monthly_salary
class PartTimePloyee(Employee):
def __init__(self, name, id, day_salary, work_days):
super().__init__(name, id)
self.day_salary = day_salary
self.work_days = work_days
def calculate_monthly_pay(self):
return self.day_salary * self.work_days
zhang_san = FullTimeEmployee("张三", "1001", 6000)
li_si = PartTimePloyee("李四", "1002", 230,15)
zhang_san.prin_info()
print("工资:" + str(zhang_san.calculate_monthly_pay()))
li_si.prin_info()
print("工资:" + str(li_si.calculate_monthly_pay()))
17. read
with open("./data.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
18. write
with open ("./poem.txt", "w", encoding = "utf-8") as f:
f.write("我欲乘风归去,\n又恐琼楼玉宇,\n高处不胜寒。\n")
with open ("./poem.txt", "a", encoding = "utf-8") as f:
f.write("起舞弄轻影,\n何似在人间。")