Python3 入门教程 Python 备忘单

2024-02-25 开发教程 Python3 入门教程 匿名 3

Python的备忘单是用于Python 3的编程语言中的单页参考表。

开始

介绍

Hello World

>>> print("Hello, World!")
Hello, World!

Python 中著名的“Hello World”程序

变量

x = 4        # x is of type int
x = "Sally" # x is now of type str
print(x)

Python 没有用于声明变量的命令。

数据类型

str文本
int, float,complex数字
list, tuple,range序列
dict映射
set, frozenset集合
bool布尔值
bytes, bytearray,memoryview二进制

字符串截取(切片)

>>> b = "Hello, World!"
>>> print(b[2:5])
llo

列表

mylist = []
mylist.append(1)
mylist.append(2)
for x in mylist:
print(x) # prints out 1,2

判断语句

a = 200
if a > 0:
print("a is greater than 0")
else:
print("a is not greater than 0")

循环

for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")

函数

>>> def my_function():
... print("Hello from a function")
...
>>> my_function()
Hello from a function

文件处理

with open("myfile.txt", "r", encoding='utf8') as file:
for x in file:
print(x)

算术运算符

result = 10 + 30  # =>  40
result = 40 - 10 # => 30
result = 50 * 5 # => 250
result = 16 / 4 # => 4
result = 25 % 2 # => 1
result = 5 ** 3 # => 125

加等于

counter = 0
counter += 10 # => 10
counter = 0
counter = counter + 10 # => 10

message = "Part 1."
# => Part 1.Part 2.
message += "Part 2."

Python 数据类型

字符串

s = "Hello World"
s = 'Hello World'

a = """Multiline Strings
Lorem ipsum dolor sit amet,
consectetur adipiscing elit """

数字

x = 1    # int
y = 2.8 # float
z = 1j # complex

>>> print(type(x))
<class 'int'>

布尔值

a = True
b = False

bool(0) # => False
bool(1) # => True

列表

list1 = ["apple", "banana", "cherry"]
list2 = [True, False, False]
list3 = [1, 5, 7, 9, 3]
list4 = list((1, 5, 7, 9, 3))

元组

a = (1, 2, 3)
a = tuple((1, 2, 3))

类似于 List 但不可变

集合

set1 = {"a", "b", "c"}   
set2 = set(("a", "b", "c"))

一组独特的项目/对象

字典

>>> empty_dict = {}
>>> a = {"one": 1, "two": 2, "three": 3}
>>> a["one"]
1
>>> a.keys()
dict_keys(['one', 'two', 'three'])
>>> a.values()
dict_values([1, 2, 3])
>>> a.update({"four": 4})
>>> a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>> a['four']
4

键 : 值(key : value)对,类JSON对象

赋值

整型

x = int(1)   # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

浮点型

x = float(1)     # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

字符串

x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

Python 字符串

类似数组

>>> a = "Hello, World"
>>> print(a[1])
e
>>> print(a[len(a)-1])
d

获取索引为 1 处的字符(大多数的编程语言,默认的索引都是从 0 开始。因此,索引为 1 ,代表列表中第 2 位的内容)

循环

>>> for x in "abc":
... print(x)
a
b
c

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

字符串切片

┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
0 1 2 3 4 5 6 7
-7 -6 -5 -4 -3 -2 -1

>>> s = 'mybacon'
>>> s[2:5]
'bac'
>>> s[0:2]
'my'
>>> s = 'mybacon'
>>> s[:2]
'my'
>>> s[2:]
'bacon'
>>> s[:2] + s[2:]
'mybacon'
>>> s[:]
'mybacon'
>>> s = 'mybacon'
>>> s[-5:-1]
'baco'
>>> s[2:6]
'baco'

切片方式

>>> s = '12345' * 5
>>> s
'1234512345123451234512345'
>>> s[::5]
'11111'
>>> s[4::5]
'55555'
>>> s[::-5]
'55555'
>>> s[::-1]
'5432154321543215432154321'

字符串长度

>>> a = "Hello, World!"
>>> print(len(a))
13

len() 函数返回字符串的长度

多次复制

>>> s = '===+'
>>> n = 8
>>> s * n
'===+===+===+===+===+===+===+===+'

检查字符串

>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
>>> s not in 'I saw The Holy Grail!'
True

连接

>>> s = 'spam'
>>> t = 'egg'
>>> s + t
'spamegg'
>>> 'spam' 'egg'
'spamegg'

格式化

name = "John"
print("Hello, %s!" % name)
name = "John"
age = 23
print("%s is %d years old." % (name, age))

format() 方法

txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'm {1}".format("John",36)
txt3 = "My name is {}, I'm {}".format("John",36)

input

>>> name = input("Enter your name: ")
Enter your name: Tom
>>> name
'Tom'

从控制台获取输入数据

join

>>> "#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'

endswith

>>> "Hello, world!".endswith("!")
True

Python 列表

定义

>>> li1 = []
>>> li1
[]
>>> li2 = [4, 5, 6]
>>> li2
[4, 5, 6]
>>> li3 = list((1, 2, 3))
>>> li3
[1, 2, 3]
>>> li4 = list(range(1, 11))
>>> li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

生成

>>> list(filter(lambda x : x % 2 == 1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

>>> [x ** 2 for x in range (1, 11) if x % 2 == 1]
[1, 9, 25, 49, 81]

>>> [x for x in [3, 4, 5, 6, 7] if x > 5]
[6, 7]

>>> list(filter(lambda x: x > 5, [3, 4, 5, 6, 7]))
[6, 7]

append

>>> li = []
>>> li.append(1)
>>> li
[1]
>>> li.append(2)
>>> li
[1, 2]
>>> li.append(4)
>>> li
[1, 2, 4]
>>> li.append(3)
>>> li
[1, 2, 4, 3]

列表切片

列表切片的语法:

a_list[start:end]
a_list[start:end:step]

切片

>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[2:5]
['bacon', 'tomato', 'ham']
>>> a[-5:-2]
['egg', 'bacon', 'tomato']
>>> a[1:4]
['egg', 'bacon', 'tomato']

省略索引

>>> a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>> a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>> a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>> a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

切片方式

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[0:6:2]
['spam', 'bacon', 'ham']
>>> a[1:6:2]
['egg', 'tomato', 'lobster']
>>> a[6:0:-2]
['lobster', 'tomato', 'egg']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

pop

>>> li = ['bread', 'butter', 'milk']
>>> li.pop()
'milk'
>>> li
['bread', 'butter']
>>> del li[0]
>>> li
['butter']

使用权

>>> li = ['a', 'b', 'c', 'd']
>>> li[0]
'a'
>>> li[-1]
'd'
>>> li[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

串联

>>> odd = [1, 3, 5]
>>> odd.extend([9, 11, 13])
>>> odd
[1, 3, 5, 9, 11, 13]
>>> odd = [1, 3, 5]
>>> odd + [9, 11, 13]
[1, 3, 5, 9, 11, 13]

排序和反转

>>> li = [3, 1, 3, 2, 5]
>>> li.sort()
>>> li
[1, 2, 3, 3, 5]
>>> li.reverse()
>>> li
[5, 3, 3, 2, 1]

计数

>>> li = [3, 1, 3, 2, 5]
>>> li.count(3)
2

重复

>>> li = ["re"] * 3
>>> li
['re', 're', 're']

Python 流控制

基本的

a = 5
if a > 10:
print("a is totally bigger than 10.")
elif a < 10:
print("a is smaller than 10.")
else:
print("a is indeed 10.")

一行代码

>>> a = 330
>>> b = 200
>>> r = "a" if a > b else "b"
>>> print(r)
a

if-elif-else

value = True
if not value:
print("Value is False")
elif value is None:
print("Value is None")
else:
print("Value is True")

Python 循环

基本的

primes = [2, 3, 5, 7]
for prime in primes:
print(prime)

带索引

animals = ["dog", "cat", "mouse"]
for i, value in enumerate(animals):
print(i, value)

while

x = 0
while x < 4:
print(x)
x += 1 # Shorthand for x = x + 1

break

x = 0
for index in range(10):
x = index * 10
if index == 5:
break
print(x)

continue

for index in range(3, 8): 
x = index * 10
if index == 5:
continue
print(x)

range 范围

for i in range(4):
print(i) # Prints: 0 1 2 3

for i in range(4, 8):
print(i) # Prints: 4 5 6 7

for i in range(4, 10, 2):
print(i) # Prints: 4 6 8

zip()

name = ['Pete', 'John', 'Elizabeth']
age = [6, 23, 44]
for n, a in zip(name, age):
print('%s is %d years old' %(n, a))

列表理解

result = [x**2 for x in range(10) if x % 2 == 0]

print(result)
# [0, 4, 16, 36, 64]

Python 函数

基本的

def hello_world():
print('Hello, World!')

return

def add(x, y):
print("x is %s, y is %s" %(x, y))
return x + y

add(5, 6) # => 11

位置参数

def varargs(*args):
return args

varargs(1, 2, 3) # => (1, 2, 3)

关键字参数

def keyword_args(**kwargs):
return kwargs

# => {"big": "foot", "loch": "ness"}
keyword_args(big="foot", loch="ness")

返回多个

def swap(x, y):
return y, x

x = 1
y = 2
x, y = swap(x, y) # => x = 2, y = 1

默认值

def add(x, y=10):
return x + y

add(5) # => 15
add(5, 20) # => 25

匿名函数

# => True
(lambda x: x > 2)(3)

# => 5
(lambda x, y: x ** 2 + y ** 2)(2, 1)

Python 模块

导入模块

import math
print(math.sqrt(16)) # => 4.0

从一个模块

from math import ceil, floor
print(ceil(3.7)) # => 4.0
print(floor(3.7)) # => 3.0

全部导入

from math import *

缩短模块

import math as m

# => True
math.sqrt(16) == m.sqrt(16)

功能和属性

import math
dir(math)

Python 文件处理

读取文件

逐行

with open("myfile.txt") as file:
for line in file:
print(line)

带行号

input = open('myfile.txt', 'r')
for i,line in enumerate(input, start=1):
print("Number %s: %s" % (i, line))

String

写一个字符串

contents = {"aa": 12, "bb": 21}
with open("myfile1.txt", "w+") as file:
file.write(str(contents))

读取字符串

with open('myfile1.txt', "r+") as file:
contents = file.read()
print(contents)

目的

写一个对象

contents = {"aa": 12, "bb": 21}
with open("myfile2.txt", "w+") as file:
file.write(json.dumps(contents))

读取对象

with open('myfile2.txt', "r+") as file:
contents = json.load(file)
print(contents)

删除文件

import os
os.remove("myfile.txt")

检查和删除

import os
if os.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file does not exist")

删除文件夹

import os
os.rmdir("myfolder")

Python 类和继承

定义

class MyNewClass:
'''This is a docstring.'''
pass

# Class Instantiation
my = MyNewClass()

构造函数

class Animal:
def __init__(self, voice):
self.voice = voice

cat = Animal('Meow')
print(cat.voice) # => Meow

dog = Animal('Woof')
print(dog.voice) # => Woof

方法

class Dog:

# Method of the class
def bark(self):
print("Ham-Ham")

charlie = Dog()
charlie.bark() # => "Ham-Ham"

类变量

class my_class:
class_variable = "A class variable!"

x = my_class()
y = my_class()

# => A class variable!
print(x.class_variable)

# => A class variable!
print(y.class_variable)

Super() 函数

class ParentClass:
def print_test(self):
print("Parent Method")

class ChildClass(ParentClass):
def print_test(self):
print("Child Method")
# Calls the parent's print_test()
super().print_test()

>>> child_instance = ChildClass()
>>> child_instance.print_test()
Child Method
Parent Method

repr() 方法

class Employee:
def __init__(self, name):
self.name = name

def __repr__(self):
return self.name

john = Employee('John')
print(john) # => John

用户定义的异常

class CustomError(Exception):
pass

多态性

class ParentClass:
def print_self(self):
print('A')

class ChildClass(ParentClass):
def print_self(self):
print('B')

obj_A = ParentClass()
obj_B = ChildClass()

obj_A.print_self() # => A
obj_B.print_self() # => B

覆盖

class ParentClass:
def print_self(self):
print("Parent")

class ChildClass(ParentClass):
def print_self(self):
print("Child")

child_instance = ChildClass()
child_instance.print_self() # => Child

继承

class Animal:
def __init__(self, name, legs):
self.name = name
self.legs = legs

class Dog(Animal):
def sound(self):
print("Woof!")

Yoki = Dog("Yoki", 4)
print(Yoki.name) # => YOKI
print(Yoki.legs) # => 4
Yoki.sound() # => Woof!

其他

注释

# This is a single line comments.
""" Multiline strings can be written
using three "s, and are often used
as documentation.
"""
''' Multiline strings can be written
using three 's, and are often used
as documentation.
'''

生成器

def double_numbers(iterable):
for i in iterable:
yield i + i

生成器可以帮助您编写懒惰的代码。

要列出的生成器

values = (-x for x in [1,2,3,4,5])
gen_to_list = list(values)

# => [-1, -2, -3, -4, -5]
print(gen_to_list)

处理异常

try:
# Use "raise" to raise an error
raise IndexError("This is an index error")
except IndexError as e:
pass # Pass is just a no-op. Usually you would do recovery here.
except (TypeError, NameError):
pass # Multiple exceptions can be handled together, if required.
else: # Optional clause to the try/except block. Must follow all except blocks
print("All good!") # Runs only if the code in try raises no exceptions
finally: # Execute under all circumstances
print("We can clean up resources here")