Python 从基础到入门
目录
- 一、hello,world
- 二、条件判断语句
- 三、循环控制语句
- 四、字符串
- 五、列表
- 六、元组
- 七、字典
- 八、集合
- 九、函数
- 十、文件的操作
- 十一、异常的处理
一、hello,world
控制台命令行,一句一句地输入Python执行语句
>>> print("hello,world")
# hello,world
结束Python终端运行
>>> Ctrl + Z 再回车 # 强制结束
>>> exit() # 退出 Python 终端
# 单行注释
''' 三单(双)引号(英文)多行注释 '''
""" ---ddd--- """
查看 Python 关键字
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield']
格式化输出
>>> print("它是%s"%("小动物")) # 占位符%s 是字符串
# 它是小动物
>>> a = 10
>>> print("它是 %d 岁"%a) # %d 是整型
# 它是 10 岁
>>> print("www","baidu","com",sep = ".") # 用 . 隔开
# www.baidu.com
输入
a = input("请输入: ") # Python 默认输入为字符串
print(type(a))
print("刚刚输入了%s"%a)
# 请输入: ddd
#<class 'str'>
# 刚刚输入了ddd
二、条件判断语句
# 分数初值为 90
score = 90 # Python不用类型来定义变量,根据右值自动转换类型
if score >= 90 and score <= 100:
if score >= 95:
print("grade A+") # 这里嵌套 if 语句
print("grade A")
elif score >= 80:
print("grade B")
elif score >= 70:
print("grade C")
else:
print("grade D")
# grade A
三、循环控制语句
for 默认操作
# for 循环
for i in range(5): # 从 0 到 4 五个整数
print(i)
# 0
# 1
# 2
# 3
# 4
for 有步长打印
# for 循环
for i in range(2,20,3): # 从 2 到 不超过19, 步长为3
print(i)
# 2
# 5
# 8
# 11
# 14
# 17
for 遍历数据结构(如字符串、列表)
str = "dfhak"
for x in str:
print(x, end = ' ') # 用空格隔开
# d f h a k
a = [1, 3, 2, 4]
for i in a:
print(i, end='\t') # 用一个tab隔开
# 1 3 2 4
while 循环
# 求1~100 的和
i = 1
sum = 0
while i <= 100:
sum += i
i += 1
print("1~100 的和为%d" % sum)
# 1~100 的和为5050
注:pass 占位,什么都不干
四、字符串
- 可以用单引号,双引号,三双引号(可直接换行)
Python 采用 Unicode 编码
str = 'there\'s a cat' # 转译字符 \
# there's a cat
str = "there's a cat" # 双引号
print(str)
# there's a cat
字符串截取
str = "ascii码Unicode"
print(str)
print("str[10]:",str[10])
print(str[1:10:2]) # 起始位置,结束位置(不包含),步进值
# ascii码Unicode
# str[10]: o
# si码nc
连接
str = "ascii"
# 连接
print((str + "dd" + '\t') * 3)
# asciidd asciidd asciidd
print(r"ascii\ndd\td") # 加上r不再转译
# ascii\ndd\td
五、列表
list 类型 []
打印
list = [123, "ddd", 11.1]
# 打印
for i in list:
print(i, type(i))
# 123 <class 'int'>
# ddd <class 'str'>
# 11.1 <class 'float'>
使用枚举函数打印
list = ['a', 'b', 'c']
for i, x in enumerate(list): # 相当于把列表枚举开来
print(i, x)
# 0 a
# 1 b
# 2 c
增
a = [1, 3]
s = [2, 4]
b = ['x', 'y']
c = [2, 5, 6]
a.append(b) # 作为整体插入末尾
s.extend(b) # 一个一个插入后面
c.insert(1, 0) # 在位置 1 处插入 0,后面元素依次后移
print(a)
print(s)
print(c)
# [1, 3, ['x', 'y']]
# [2, 4, 'x', 'y']
# [2, 0, 5, 6]
删
a = [1, 2, 3, 4, 3, 5]
del a[1] # 指定位置删除一个
print(a)
# [1, 3, 4, 3, 5]
a.pop() # 删除最后一个
print(a)
# [1, 3, 4, 3]
a.remove(3) # 删除找到的第一个相同内容
print(a)
# [1, 4, 3]
改
# 通过下标修改
a = [1, 2, 3, 4, 3]
a[2] = 10
print(a)
# [1, 2, 10, 4, 3]
查
a = [1, 2, 3, 4, 3]
if 100 in a:
print("100 在列表 a 中")
else:
print("没找到")
# 没找到
a = [1, 2, 3, 4, 3, 5]
print(a.index(4, 1, 5)) # 如果 4 在 [1, 5) 则返回下标,否则报错
# 3
print("3 在a中有%d个" % a.count(3)) # 统计 3 的个数
# 3 在a中有2个
排序
a = [1, 2, 3, 4, 3, 5]
print("原 a:", a)
a.reverse()
print("反转后 a:", a)
a.sort() # 升序
print("升序后 a:", a)
a.sort(reverse=True) # 降序
print("降序后 a:", a)
# 原 a: [1, 2, 3, 4, 3, 5]
# 反转后 a: [5, 3, 4, 3, 2, 1]
# 升序后 a: [1, 2, 3, 3, 4, 5]
# 降序后 a: [5, 4, 3, 3, 2, 1]
二维列表
import random
a = [[1, 2], [3], [4, 5]]
a[1].append(random.randint(2, 5)) # 随机数为 [2, 5] 的整数
print(a[1][0]) # 通过下标索引
# 遍历所有元素
print("矩阵为:")
for i in a:
for j in i:
print(j, end=' ')
print('\r') # 退回到行首
# 3
# 矩阵为:
# 1 2
# 3 4
# 4 5
六、元组
tuple 类型 ()
tuple 的元素不可改变
tup = (1, 2)
tup[0] = 3 # 报错
# 元组定义
tup1 = ()
tup2 = (1,) # 只有一个数据的时候需加,表示是元组类型
tup3 = (1, 2, 3)
tup = (1, "ddd", 2, 1.0)
print(tup[1])
print(tup[-1])
print(tup[1:3]) # 切片区间左闭右开
# ddd
# 1.0
# ('ddd', 2)
增
tup1 = (1, 3, 5)
tup2 = (2, 4)
tup3 = tup1 + tup2
print(tup3)
# (1, 3, 5, 2, 4)
删
tup = (1, 3, 5)
del tup # 删除了这个变量
七、字典
dict 类型 {}
注:key 不可变
a = {1: "a", 2: "b", 3: "c"}
# 访问
print(a[2])
print(a.get(4, "null")) # 这里设置未找到默认值 null
# b
# null
增
a = {1: "a", 2: "b", 3: "c"}
a[4] = "d"
print(a)
# {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
删
a = {1: "a", 2: "b", 3: "c"}
del a[2]
print(a)
# {1: 'a', 3: 'c'}
a.clear() # 清空
print(a)
# {}
del a # 执行后 a 就不存在了
改
a = {1: "a", 2: "b", 3: "c"}
a[2] = 8
print(a)
# {1: 'a', 2: 8, 3: 'c'}
查
a = {1: "a", 2: "b", 3: "c"}
print(a.keys()) # 得到所有键(列表)
print(a.values()) # 得到所有值(列表)
print(a.items()) # 得到所有项(列表),每个键值是一个元组
# dict_keys([1, 2, 3])
# dict_values(['a', 'b', 'c'])
# dict_items([(1, 'a'), (2, 'b'), (3, 'c')])
# 格式化打印内容
a = {1: "a", 2: "b", 3: "c"}
# 打印
for key in a.keys():
print(key, end=' ')
for value in a.values():
print(value, end=' ')
print('\r')
for key, value in a.items():
print("key = %d,value = %s" % (key, value))
# 1 2 3 a b c
# key = 1,value = a
# key = 2,value = b
# key = 3,value = c
八、集合
去重
list = [1, 2, 2, 3, 4, 4]
a = set(list)
print(a)
# {1, 2, 3, 4}
九、函数
无参
def display():
print("print")
display()
# print
带参
def add(a, b):
return a + b
print(add(1, 2))
# 3
返回多个值
def divide(a, b):
s = a // b
y = a % b
return s, y
sh, yu = divide(7, 3) # 使用多个变量接收多个返回值
print("商为%d" % sh, " 余数为%d" % yu)
# 商为2 余数为1
较全局变量局部变量优先使用,要改变全局变量,在函数里用 global
a = 10 # 全局变量
def display():
global a # 这样就可以在函数里修改全局变量了
a = 2
display()
print(a)
# 2
def main():
print("dd")
if __name__ == "__main__": # Python 的主函数,一般在这里组织函数调用关系
# 函数调用
main()
十、文件的操作
写入
f = open("ts.txt", "w") # 当前目录下,有则写入,无则创建写入
f.write("""hello
world
I am
here""")
f.close() # 关闭文件
读取
f = open("ts.txt", "r") # 只读打开
print(f.read()) # 读全部
f.close()
# hello
# world
# I am
# here
f = open("ts.txt", "r")
contents1 = f.readline() # 一行一行地读
print(contents1, end='\r')
contents2 = f.readline()
print(contents2)
f.close()
# hello
# world
f = open("ts.txt", "r")
contents = f.readlines() # 读出全部存到列表里
print(contents)
f.close()
# ['hello\n', 'world\n', 'I am\n', 'here']
十一、异常的处理
a = 3
b = 0
try:
c = a / b # 除 0
print(c)
except Exception as res: # 捕获异常
print(res)
finally:
print("finally")
# division by zero
# finally