基础语法
大约 7 分钟
Python之禅
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
注意
后续所有的Python开发和运行环境,都基于在Anaconda中创建的Python3.9
。
> conda create -n dev-3.9 python==3.9
> conda activate dev-3.9
数据类型
# 这是python的单行注释
# Number数字类型
'''
这是python的多行注释
int :整数(无short、long)
float :浮点数(无double)
'''
"""
这也是python的多行注释
"""
print(type(1))
print(type(3.1415926))
print(type(1 + 3.1415926))
# /:会自动转型成float
print(type(1 / 1))
# //:整型相除会得到整型而不是float
# //:浮点数相除得到的也是浮点数
print(type(1 // 1))
# 得到的是int
print(type(1 // 2))
# 得到的是float
print(type(3.14 // 1))
print(type(1 // 3.14))
# 前缀0b表示二进制
print(0b10)
# 前缀0o表示八进制
print(0o10)
# 前缀0x表示十六进制
print(0x10)
# 将其他进制转换为二进制
print(bin(10))
print(bin(0o10))
print(bin(0x10))
# 将其他进制转换为十进制
print(int(0b10))
print(int(0o10))
print(int(0x10))
# 将其他进制转换为八进制
print(oct(0b10))
print(oct(10))
print(oct(0x10))
# 将其他进制转换为十六进制
print(hex(0b10))
print(hex(10))
print(hex(0o10))
# bool布尔
# bool是一种Number数字类型
print(type(True))
print(type(False))
print(int(True))
print(int(False))
# 非0数字都是True,只有0表示False
print(bool(1))
print(bool(-1))
print(bool(2))
print(bool(3.1415926))
print(bool(0b01))
# True
print(bool('abc'))
print(bool([0]))
print(bool((0, 1)))
print(bool({0}))
# False
print(bool(0))
print(bool(0x0))
print(bool(''))
print(bool([]))
# [0]表示True,但(0)表示False
print(bool((0)))
print(bool(()))
print(bool({}))
print(bool(None))
# complex复数
print(type(1j))
# 字符串
print(type('1'))
print(type("1"))
print(type('''1'''))
print(type("""1"""))
# 原始字符串
print(r"c:\system\windows")
print(R"c:\system\windows")
# 字符串运算
print("a" + "b")
print("a" * 3)
print("a" in "abc")
print("a" not in "abc")
print("a" > "b")
print("a" < "b")
print("a" >= "b")
print("a" <= "b")
print("a" == "b")
print("a" != "b")
print("a" == "a")
print("hello world"[1])
print("hello world"[-1])
# 几种不同的字符串格式化输出
name = "lixingyun"
age = 19
print("%s, %d"%(name, age))
print("{}, {}".format(name, age))
print("{0}, {1}".format(name, age))
print("{name}, {age}".format(name=name, age=age))
print(f"{name}, {age}")
# 浮点数格式化输出
print("%.2f"%3.1415926)
print("{:.2f}".format(3.1415926))
print("{0:.2f}".format(3.1415926))
print("{name:.2f}".format(name=3.1415926))
print(f"{3.1415926:.2f}")
# 第二个参数表示第二个字符串的索引位置,截取内容为左闭右开的区间:[x, y)
print("hello world"[1:3])
print("hello world"[1:-1])
# 超出索引范围会取最大的有效索引值
print("hello world"[1:20])
print("hello world"[1:])
print("hello world"[-5:])
print("hello world"[:3])
# 值、身份(id)、类型(type和isinstance)
a = "hello"
print(a)
print(id(a))
print(type(a) == str)
print(isinstance(a, str))
print(isinstance(a, (int, str, float)))
# None全局只有一个
b = None
c = None
print(b == c)
print(b is c)
变量与运算符
# 变量只能以数字、字母、下划线的组合来命名
# 变量名不能以数字开头,不能用保留关键字
a = [1, 2, 3]
print(a)
a = "test"
b = a
a = "hello"
# b == test,因为它是值传递而非引用传递
print(b)
a = [1, 2, 3]
b = a
a[0] = "1"
print(a)
# b == ['1', 2, 3],因为它是引用传递而非值传递
print(b)
# int、str、tuple都是值类型,属于不可变类型
# list、set、dict都是引用类型,属于可变类型
# 运算符
# 算术运算符:+、-、*、/、//、%、**
# 赋值运算符:=、+=、*=、/=、%=、**=、//=
# 关系运算符:<、>、<=、>=、==、!=
# 逻辑运算符:and、or、not
# 成员运算符:is、is not
# 身份运算符:in、not in
# 位运算符:>>、<<、&、|、^、~
print([1, 2, 3] + [4, 5, 6])
print([1, 2, 3] * 2)
print(2 ** 2)
a = 1
a += a >= 1
print("a + True ==> ", a + True)
print("a > true ==> ", "a" > "true")
print("a > True ==> ", "a" > "True")
print("[1, 2, 3] < [1, 2, 3, 4] ==> ", [1, 2, 3] < [1, 2, 3, 4])
print("(1, 2, 3) > (1, 2, 3, 4) ==> ", (1, 2, 3) > (1, 2, 3, 4))
a = 1
print(a is True)
print(a in [1, 2, 3])
print(a not in [2, 3])
print(a in (1, 2, 3))
print(a in {1, 2, 3})
print(a in {1, 2, 3})
b = 'a'
# in操作符默认检查字典的键,而不是值,它等价于 'a' in {'a': 1}.keys()
print(b in {'a' : 1})
# 若想检查值是否存在于字典中,需要显式使用.values()
c = 1
print(c in {'a' : 1}.values())
b = 2
c = 1
print(a is b)
print(a is c)
d = 'hello'
e = 'hello'
print(d is e)
print(d == e)
f = 1
g = 1.0
# == 比较数值是否相等
print("f == g ==> ", f == g)
# is 比较身份或内存地址是否相等
print("f is g ==> ", f is g)
print(id(f))
print(id(g))
a = {1, 2, 3}
b = {2, 1, 3}
print(a == b)
print(a is b)
# Python会缓存小整数(-5到256)和短字符串(驻留机制),因此它们的is可能返回True
a = 256
b = 256
print(a is b)
c = 257
d = 257
print(c is d)
# 连续赋值
a = b = c = d = 1
print(a, b, c, d)
条件判断
a = 1
if a > 1:
print("a大于1")
elif a == 1:
print("a等于1")
print("这是同一个if中的语句")
else:
print("a小于1")
username = "admin"
password = "123456"
print("请输入用户名:")
input_username = input()
print("请输入密码:")
input_password = input()
if input_username == username and input_password == password:
print("登录成功")
else:
print("登录失败")
# 三元表达式:条件为True时返回 if 条件判断 else 条件为False时返回
print(1 if 2 > 1 else 0)
循环语句
username = "admin"
password = "123456"
# 无限循环
while True:
print("请输入用户名:")
input_username = input()
print("请输入密码:")
input_password = input()
if input_username == username and input_password == password:
print("登录成功")
break
else:
print("登录失败")
# 有限循环 while...else
counter = 0
while counter < 5:
counter += 1
print(counter)
else:
print("循环结束")
# for主要用来遍历序列、集合、字典中的数据
# for...else是一个特殊的语法结构,用于在循环正常结束(未被break中断)时执行特定的代码块
# else 块执行条件:
# 当for循环遍历完所有元素且未被break终止时,else块会执行
# 如果循环中途被break中断,else块不会执行
# 常见用途
# 搜索场景:遍历一个集合寻找符合条件的元素,若未找到,则在else中处理未找到的情况
# 验证场景:检查数据是否全部满足条件,若遍历完都满足,则在else中处理
list1 = [[1, "2", 3.14, True], (1, 2, 3)]
for i in list1:
for j in i:
if j == "2":
break
print(j, end="\t")
print(i)
else:
print("这里会被打印")
a = [1, 2, 3, 4]
for i in a:
if i == 3:
# 当加入break后,并不会打印else中的内容
break
print(i)
else:
print("这里不会被打印")
print()
# while循环也支持else,规则与for...else一致
# range函数:起始位置,偏移量,步长
for i in range(0, 6, 2):
print(i, end="\t")
print()
for i in range(10, 0, -2):
print(i, end="\t")
海象运算符
# 海象运算符不能像Go语言中那样做简单的赋值
# c := len(a)
# 海象运算符只能放在表达式中
a = 'python'
if (b := len(a)) > 1:
print(b)
num = 3
while (num := num - 1) + 1:
print(f"{num}")
# 用于推导
a = [n for x in range(0, 10) if (n := x + 1) % 2]
print(a)
# 三元表达式
a, b = 20, 15
# 使用f关键字来拼接字符串
print(f"还剩{a}个苹果") if (a := a - b) > b else print(f"还剩{b}个苹果")
# 上面的三元表达式等同于下面的代码
if (a := a - b) > b:
print(f"还剩{a}个苹果")
else:
print(f"还剩{b}个苹果")
None
# None不等同于空字符串"",空序列[],空字典{},空集合set(),以及0和False
a = ''
b = False
c = {}
d = []
e = set()
f = None
print("'' == None ==>", a == None)
print("not '' ==>", not a)
print("'' is None ==>", a is None)
print()
print("False == None ==>", b == None)
print("not False ==>", not b)
print("False is None ==>", b is None)
print()
print("{} == None ==>", c == None)
print("not {} ==>", not c)
print("{} is None ==>", c is None)
print()
print("[] == None ==>", d == None)
print("not [] ==>", not d)
print("[] is None ==>", d is None)
print()
print("set() == None ==>", e == None)
print("not set() ==>", not e)
print("set() is None ==>", e is None)
print()
print("None == None ==>", f == None)
print("not None ==>", not f)
print("None is None ==>", f is None)
print()
print("type(None) ==>", type(None))
感谢支持
更多内容,请移步《超级个体》。