# 001 单行注释
# 002 多行注释
"""
这个是多行注释
"""
'''
这个也是多行注释
'''
# 003 变量的定义
weather = '晴天'
print('今天的天气是' + weather)
# 004 数据类型
"""
int
long #版本3删掉了
float
boolean
string
list
tuple元组
dict字典
"""
money = 100
money = 100.1
sex = True
s = "这就是字符串,单引号也是可以"
name_list = ['1', '2'] # 列表 输出['1', '2']
age_tuple = (18, 19, 20, 21) # 元组 输出(18, 19, 20, 21)
person = {'name': '丽华', 'age': '18'} # 字典 输出{'name': '丽华', 'age': '18'}
# 005 判断数据类型
print(type(money))
# 006 变量命名规范
# 007 类型转换
print(int("123"))
print(int(123.123))
print(int(True))
print(float("123.123"))
print(float(123))
str1 = str(45)
print(bool(''))
print(bool(""))
print(bool(0))
print(bool({}))
print(bool([]))
print(bool(())) # 有内容则为True,否者为false
# 008 运算符
'''
算术运算符+-*/ //整除 %取余 **指数 ()优先级
'''
'''
赋值运算符
a = b = 20
a,b,c,d = 1,2,3,4
'''
'''
复合赋值运算符+= -= *= /= //= %= **=
'''
'''
比较运算符
== != >= <= > <
'''
'''
逻辑运算符and or not
'''
# 009 输入输出
print('你好')
age = 18
name = "红浪漫晶哥"
print("我的姓名是%s, 年龄是%d" % (name, age))
内容 = input('请输入内容')
# 010 流程控制
age = 19
if age >= 18:
print("我已经成年了")
age = 18
if age >= 18:
print("我可以去红浪漫了")
else:
print("未成年,不允许去")
score = 77
if score >= 90:
print('本次考试,等级为A')
elif score >= 80:
print('本次考试,等级为B')
elif score >= 70:
print('本次考试,等级为C')
elif score >= 60:
print('本次考试,等级为D')
elif score < 60:
print('本次考试,等级为E')
for s in "hello":
print(s)
for i in range(5):
print(i)
# range 可以生成数字供 for 循环遍历,它可以传递三个参数,分别表示 起始、结束和步长
for x in range(2, 10, 3):
print(x)
# 011 字符串高级
s = "china"
print(len(s)) # len
print(s.find('c')) # find
print(s.startswith('c')) # 是否以‘’为开头
print(s.count('a')) # 出现次数
print(s.replace('c', 'd')) # 替换
s1 = '1#2#3'
print(s1.split('#')) # 切割
'''
.upper() .lower()
.strip()去空格
join (怪异)不是直接拼接,是插入很多次
'''
# 012列表高级
food_list = ['米饭', '馒头']
print(food_list)
food_list.append('面条')
char_list = ['a', 'b', 'c']
print(char_list)
char_list.insert(0, 'a')
print(char_list)
num_list = [1, 2, 3]
num1_list = [4, 5, 6]
num_list.extend(num1_list)
print(num_list)
'''修改'''
city_list = ['北京', '上海', '广州']
city_list[2] = '深圳'
if '深圳' in city_list:
print('在')
else:
print('不在')
'''删除del pop remove
del:根据下标进行删除del movieName[2]
pop:删除最后一个元素movieName.pop()
remove:根据元素的值进行删除movieName.remove('xxx')
'''
# 013元组:不可以修改内容,唯一元素的元组,要在其后面加逗号
a_tuple = (1, 2, 3, 4)
a_tuple = (0,)
print(a_tuple[0]) # 访问
# 014切片
'''切片是指对操作的对象截取其中一部分的操作。字符串、列表、元组都支持切片操作
切片的语法:[起始:结束:步长],也可以简化使用 [起始:结束]'''
s = 'hello world'
print(s[0:4]) # hell 左闭右开
print(s[0:])
print(s[:4])
print(s[0:6:2]) # 步长0,2,4
# 015字典高级
person = {'name': '李华', 'age': 28}
print(person['name'])
print(person['age'])
print(person.get('name'))
person['name'] = '王二'
person['id'] = '1005' # 添加
del person['name'] # 删除指定元素
del person # 删除整个字典
person = {'name': '李华', 'age': 28}
person.clear() # 清空整个字典
# 遍历字典key value key-value
person = {'name': '李华', 'age': 28}
for key in person.keys():
print(key)
for value in person.values():
print(value)
for item in person.items():
print(item)
# 016函数
def f1():
print('hello world') # 定义函数
f1() # 调用函数
def f2(a, b): # 带参函数
c = a + b
print(c)
def f3(a, b): # 带返回值函数
return a + b
# 017文件
# (文件路径(绝对/相对),访问模式)
'''
r:只读,指针在文件开头;不存在会报错 r+:读写 rb:bit二进制格式打开 rb+
w:只写,直接覆盖;不存在会新建 w+:读写 wb:bit二进制格式打开 wb+
a:指针在文件末尾,追加写入;不存在会新建 a+:读写 ab:bit二进制格式打开 ab+
'''
f = open('test.txt', 'w')
f.write('hello world,i am here!\n' * 5)
f.close()
f = open('test.txt', 'r')
content = f.read(5) # 读5个数据
print(content)
content = f.read() # 继续读取上次没读完的数据
print(content)
f.close()
f = open('test.txt', 'r') # readline
content = f.readline()
print(content)
f.close()
print('-' * 20)
f = open('test.txt', 'r') # redlines 读入全部数据,存储为list
content = f.readlines()
print(type(content))
for temp in content:
print(temp)
f.close()
# 序列化
'''
通过文件操作,我们可以将字符串写入到一个本地文件。但是,如果是一个对象(例如列表、字典、元组等),就无
法直接写入到一个文件里,需要对这个对象进行序列化,然后才能写入到文件里。
设计一套协议,按照某种规则,把内存中的数据转换为字节序列,保存到文件,这就是序列化,反之,从文件的字
节序列恢复到内存中,就是反序列化。
'''
import json
file = open('name.txt', 'w')
names = ['hangman', 'lisi', 'wang', 'jerry']
result = json.dumps(names) # 此时name变为字符串
file.write(result)
json.dump(names, file) # 简洁的方法
file.close()
# 反序列化
result = json.loads('["hangman", "lisi"]')
print(type(result))
# 018异常
try:
f = open('test1.txt', 'r')
print(f.read())
except FileNotFoundError:
print('文件没有找到,请检查文件名称是否正确')