Python语法基础

前言

推荐文档:https://www.w3school.com.cn/python/index.asp

打印

1
print("Hello, World!")

格式化打印

1
print(f"lineRect {lineRect} wordRect {wordRect}")

注释

1
# print("Hello, World!")

if else

1
2
3
4
5
6
7
8
a = 200
b = 66
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

循环

while循环

在 i 等于 3 时退出循环:

1
2
3
4
5
6
i = 1
while i < 7:
print(i)
if i == 3:
break
i += 1

for循环

for 循环用于迭代序列(即列表,元组,字典,集合或字符串)。

循环字符串

循环遍历单词 “banana” 中的字母:

1
2
for x in "banana":
print(x)

循环列表

1
2
3
4
5
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break

循环字典

方式1

1
2
3
d = {'name1' : 'pythontab', 'name2' : '.', 'name3' : 'com'}
for key in d:
print (key, ' value : ', d[key])

方式2

1
2
for key, value in d.items():
print (key, ' value : ', value)

遍历元素及索引

1
2
3
4
fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")

range函数

range() 函数返回一个数字序列,默认情况下从 0 开始,并递增 1(默认地),并以指定的数字结束。

包含开始不包含结束

使用 range() 函数:

1
2
for x in range(10):
print(x)

设置开始

1
2
for i in range(3, 8):
print(i)

迭代器

从元组返回一个迭代器,并打印每个值:

1
2
3
4
5
6
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

创建迭代器

要把对象/类创建为迭代器,必须为对象实现 iter() 和 next() 方法。

正如您在 Python 类/对象 一章中学到的,所有类都有名为 init() 的函数,它允许您在创建对象时进行一些初始化。

  • __iter__() 方法的作用相似,您可以执行操作(初始化等),但必须始终返回迭代器对象本身。

  • __next__() 方法也允许您执行操作,并且必须返回序列中的下一个项目。

创建一个返回数字的迭代器,从 1 开始,每个序列将增加 1(返回 1、2、3、4、5 等):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
x = self.a
self.a += 1
return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

StopIteration

如果你有足够的 next() 语句,或者在 for 循环中使用,则上面的例子将永远进行下去。

为了防止迭代永远进行,我们可以使用 StopIteration 语句。

next() 方法中,如果迭代完成指定的次数,我们可以添加一个终止条件来引发错误:

在 20 个迭代之后停止:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class MyNumbers:
def __iter__(self):
self.a = 1
return self

def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
print(x)

函数

基本

1
2
3
4
def my_function():
print("Hello from a function")

my_function()

Lambda

1
2
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

调用时传入

1
2
3
4
def do_something(callback):
result = 42
callback(result)
do_something(lambda x: print("The result from lambda is:", x))

日期

1
2
3
4
5
6
7
8
import datetime

x = datetime.datetime(2020, 5, 17)

print(x)

y = datetime.datetime.now()
print(y)

模块

在名为 mymodule.py 的文件中保存代码:

1
2
def greeting(name):
print("Hello, " + name)

导入名为 mymodule 的模块,并调用 greeting 函数:

1
2
3
import mymodule

mymodule.greeting("Bill")

也可以

1
2
from mymodule import greeting
greeting("Bill")

如果路径是这样的utils/mylog.py

1
2
3
import utils.mylog

utils.mylog.greeting("Bill")

或者

1
2
from utils.mylog import greeting
greeting("Bill")