Python

Python编程基础

1 标识符

  • 标识符是编程时使用的名字,用于给变量、函数、语句块等命名,Python 中标识符由字母、数字、下划线组成,不能以数字开头,区分大小写。
  • 以下划线开头的标识符有特殊含义,单下划线开头的标识符,如:_xxx ,表示不能直接访问的类属性,需通过类提供的接口进行访问,不能用 from xxx import * 导入;双下划线开头的标识符,如:__xx,表示私有成员;双下划线开头和结尾的标识符,如:xx,表示 Python 中内置标识,如:init() 表示类的构造函数

2 关键字

and exec not assert finally or
break for pass class from print
continue global raise def if return
del import try elif in while
else is with except lambda yield

上面表中是 Python 中的关键字(保留字),我们在自定义标识符时不能使用关键字。

3 缩进

Python 不使用 {} 来控制类、函数、逻辑判断等,而是使用缩进,缩进的空格可变。如下所示:

if True:
    print(True)
else:
    print(False)

4 注释

Python 中单行注释使用 #,多行注释使用三个单引号(‘’')或三个双引号(“”")。如下所示:

# 我是单行注释

'''
我是多行注释
我是多行注释
'''

"""
我是多行注释
我是多行注释
"""

5 数据类型

  • 整数:可以为任意大小、包含负数
  • 浮点数:就是小数
  • 字符串:以单引号 ‘、双引号"、三引号 ‘’’ 或 “”"括起来的文本
  • 布尔:只有 True、False 两种值
  • 空值:用 None 表示
  • 变量:是可变的
  • 常量:不可变

6 运算符

6.1 常用运算符

运算符 描述 示例
+ 相加 a+b
- 相减 a-b
* 相乘 a*b
/ 相除 a/b
% 取模 a%b
** a**b表示a的b次幂
// 取整除 9//4结果为2
== 是否相等 a==b
!= 是否不等于 a!=b
> 是否大于 a>b
>= 是否大于等于 a>=b
<= 是否小于等于 a<=b
= 简单的赋值运算符 a=b+c
+= 加法赋值运算符 a+=b等效于a=a+b
-= 减法赋值运算符 a-=b等效于a=a-b
*= 乘法赋值运算符 a*=b等效于a=a*b
/= 除法赋值运算符 a/=b等效于a=a/b
%= 取模赋值运算符 a%=b等效于a=a%b
**= 幂赋值运算符 a**=b等效于a=a**b
//= 取整除赋值运算符 a//=b等效于a=a//b
& a&b
| a&b (此处示例可能有误,应为a|b )
^ 异或 a^b
~ 取反 ~a
<< 左移动 a<<3
>> 右移动 a>>3
and 布尔类型与 a and b
or 布尔类型或 a or b
not 布尔类型非 not a
is 判断两个标识符是否引用同一个对象 a is b
is not 判断两个标识符是否引用不同对象 a is not b

6.2 运算符优先级

运算符 描述(由上至下对应优先级由高到低)
** 幂运算
~ + - 取反、正号、负号
* / % // 乘、除、取模、取整除
+ - 加法、减法
>> << 右移、左移
&
^ | 异或、或
<= < > >= 比较运算符
== != 是否等于、是否不等于
= %= /= //= -= += *= **= 赋值运算符
is is not 身份运算符
in not in 成员运算符
not and or 逻辑运算符

7.math库

常用函数 数学表达式 功能
math.pi π 圆周率,值为3.1415926……
math.e e 自然对数,值为2.718281……
math.inf 正无穷大
-math.inf -∞ 负无穷大
math.nan 非浮点数标记,返回浮点nan
math.fabs (x) 返回x的绝对值,同abs (x)
math.fmod (x, y) x%y 返回x与y的模,即x%y
math.fsum ([X1,X2,…Xn ]) X1+X2…+Xn 浮点数精确求和(传入参数为可迭代类型,如列表等等)
math.ceil (x) 向上取整,返回不小于x的最小整数
math.floor (x) 向下取整,返回不大于x的最大整数
math.factorial (x) x! 返回x的阶乘,如果x是小数或者负数,返回ValueError(一种异常)
math.gcd (x, y) 返回a,b的最大公约数
math.frexp (x) x = m * 以二元组的形式,返回组成x的尾数和指数 (m, e)
math.ldexp (x, i) x * 返回x * 的值
math.modf (x) 例如x=3.14 返回(0.1400…, 3.00) 以元组的形式(浮点数部分,整数部分)的形式返回x的小数和整数部分
math.trunc (x) 返回x的整数部分
math.isinf (x) 当x为正负无穷大,返回True,否则返回False
math.isfinite (x) 当x不是无穷大或NaN,返回True否则返回False
math.pow(x,y) 返回x的y次幂,即x**y
math.exp (x) 返回e的x次幂,e是自然对数
math.sqrt(x) 返回x的平方根
math.log(x,base) 返回以base为底,x为对数,base为可选参数,若不输入,则默认为自然对数e,即lnx
math.log2 (x) 返回以二为底,x的对数
math.log10 (x) 返回以10为底,x的对数
math.expm1 (x) 返回e的x次幂 减一
math.log1p (x) 返回x + 1的自然对数值
math.degrees(x) 角度x的弧度值转角度值
math.radians (x) 角度x的角度值转弧度制
math.hypot (x, y) 返回坐标(x,y)到原点的距离
math.sin (x) 返回x的正弦值,x为弧度值
math.cos(x) 返回x的余弦值,x为弧度值
math.tan(x) 返回x的正切值,x为弧度值
math.asin(x) 返回x的反正弦值,x为弧度值
math.acos(x) 返回x的反余弦值,x为弧度值
math.atan(x) 返回x的反正切值,x为弧度值
math.atan2(y,x) 返回y/x的反正切值,x为弧度值
math.sinh(x) 返回x的双曲正弦函数值
math.cosh(x) 返回x的双曲余弦函数值
math.tanh(x) 返回x的双曲正切函数值
math.asinh(x) 返回x的反双曲正弦函数值
math.acosh(x) 返回x的反双曲余弦函数值
math.atanh(x) 返回x的反双曲正切函数值

8.数据类型转换

函数 功能描述
int() 将其他数据类型转换为整数
float() 将其他数据类型转换为浮点数
complex() 将其他数据类型转换为复数
str() 将其他数据类型转换为字符串
list() 将可迭代对象(如字符串、元组、字典等)转换为列表
tuple() 将可迭代对象转换为元组
set() 将可迭代对象转换为集合。注意:集合是无序且元素唯一的
dict() 将可迭代对象(如元组、列表等)转换为字典。要求输入对象是一个包含二元组(键值对)的可迭代对象
bool() 将其他数据类型转换为布尔值。通常,空值、0 、None 被转换为 False ,其他的都转换为 True
bin() 将整数转换为二进制字符串(以 “0b” 开头)
oct() 将整数转换为八进制字符串(以 “0o” 开头)
hex() 将整数转换为十六进制字符串(以 “0x” 开头)
iter() 将对象转换为迭代器(只有可迭代的对象可以转换为迭代器)
ord() 将单个字符转换为其对应的 Unicode 编码
chr() 将 Unicode 编码转换为字符

顺序结构程序设计

num = int(input("请输入一个三位数"))
a = num // 100
b = (num % 100) // 10
c = num % 10
print("百位=%d,十位=%d,个位=%d" % (a, b, c))
ch = input()
# ord()计算ASCII码
pre = ord('z') - (ord('z') - ord(ch) + 1) % 26
nex = ord('a') + (ord(ch) - ord('a') + 1) % 26
print("%c,%c,%c" % (ch, pre, nex))

选择结构程序设计

x, y, z = eval(input('请输入x,y,z:'))
if x > y:
    x, y = y, x
if x > z:
    x, z = z, x
if y > z:
    y, z = z, y
print(x, y, z)
year = int(input('请输入年份:'))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(year, "年是闰年")
else:
    print(year, "不是闰年")
score = int(input("请输入学生成绩:"))
if score < 60:
    print("不及格")
elif score < 70:
    print("及格")
elif score < 90:
    print("良好")
else:
    print("优秀")
n, m = eval(input('请输入乘坐的人数,乘坐站数:'))
if m <= 4:
    pay = 3 * n
else:
    if m < 9:
        pay = 4 * n
    else:
        pay = 5 * n
print('''应付款''', pay)
a = float(input('input:'))
if a >= 0:
    b = a
else:
    b = -a
c = a ** 2
print("abs=%f,square=%f" % (b, c))
from math import *

a, b, c = eval(input('a,b,c='))
if a + b > c and a + c > b and b + c > a:
    p = (a + b + c) / 2
    s = sqrt(p * (p - a) * (p - b) * (p - c))
    print('area=', s)
else:
    print('Input data error')
x = int(input('请输入三位整数x:'))
a = x // 100
b = (x - a * 100) // 10
c = x - 100 * a - 10 * b
if x == a ** 3 + b ** 3 + c ** 3:
    print(x, '是水仙花数')
else:
    print(x, '''不是水仙花数''')

循环结构程序设计

count=int(input())
while count<5:
    print(count,"is less than 5")
    count=count+1
else:
    print(count,"is not less than 5")
sum, n = 0, 0
while n <= 100:
    sum = sum + n
    n = n + 1
print("1+2+3···+100=", sum)
sum = 0
x = int(input("请输入一个正整数"))
while x >= 0:
    sum = sum + x
    x = int(input("请输入一个正整数"))
print("sum=", sum)
x = int(input())
if 0 <= x < 99999:
    i = x
    n = 0
    while i > 0:
        i = i // 10
        n = n + 1
    a = x % 10
    print("%d是%d位数,个位是%d" % (x, n, a))
else:
    print("输入错误!!!")
for i in range(5):
    print(i)
print("------------------------------------")
for i in range(2, 4):
    print(i)
print("------------------------------------")
for i in range(2, 20, 3):
    print(i)
sum = 0
for i in range(101):
    sum = sum + i
print("1+2+3+···+100 =", sum)
m = int(input("请输入要判断的正整数m:"))
flag = 1
for i in range(2, m):
    if m % i == 0:
        flag = 0
        i = m
if flag == 1:
    print("%d是素数" % m)
else:
    print("%d不是素数" % m)
str = input("请输入一串字符:")
flag = 0
count = 0

for c in str:
    if c == " ":
        flag = 0
    else:
        if flag == 0:
            flag = 1
            count = count + 1
print("共有%d个单词" % count)
print("满足条件的四位数分别是:")
for i in range(1000, 10000):
    a = i // 100
    b = i % 100
    if (a + b) ** 2 == i:
        print(i)
print()
count = 0
for i in range(1, 100):
    if i % 7 == 0 and i % 11 != 0 or i % 11 == 0 and i % 7 != 0:
        print(i, end=" ")
        count = count + 1
        if count % 10 == 0:
            print("")
for i in range(1, 10, 1):
    for j in range(1, i + 1, 1):
        print("%d*%d=%2d " % (j, i, j * i), end=" ")
    print("")
print("100~200中的素数有:")
for m in range(100, 200):
    flag = 1
    for i in range(2, m):
        if m % i == 0:
            flag = 0
            break
    if flag == 1:
        print(m, end=" ")
m, n = eval(input("请输入两个整数"))
if m < n:
    min = m
else:
    min = n
for i in range(min, 1, -1):
    if n % i == 0 and m % i == 0:
        print("最大公约数为:", i)
        break
x = y = 0
while True:
    x += 1
    if not (x % 2):
        continue
    elif x > 100:
        break
    else:
        y += x
print("y=", y)
for letter in "Python":
    if letter == "o":
        pass
        print("This is pass block")
    print("Current Letter:", letter)
print("End!")
import math

s = 1
n = 1.0
t = 1.0
pi = 0
while math.fabs(t) >= 1e-6:
    pi = pi + t
    n = n + 2
    s = -s
    t = s / n
pi = pi * 4
print("PI=%f" % pi)
for i in range(ord('x'), ord('z') + 1):
    for j in range(ord('x'), ord('z') + 1):
        if i != j:
            for k in range(ord('x'), ord('z') + 1):
                if (i != k) and (j != k):
                    if i != ord('x') and (k != ord('x')) and (k != ord('z')):
                        print('order is:\na-->%s\nb-->%s\nc-->%s' % (chr(i), chr(j), chr(k)))
s = 1
i = 1
a = int(input("请输入角度值(单位:角度):"))
x = 3.1415926 / 180 * a
sinx = x
fitem = e = x
d = 1
while fitem > 10 ** -7:
    e = e * x * x
    d = d * (i + 1) * (i + 2)
    i = i + 2
    fitem = e / d
    s = -s
    sinx += s * fitem
print("sin(%3.1f)=%.3f" % (a, sinx))
for i in range(1, 21):
    for j in range(1, 34):
        for k in range(1, 101):
            if i + j + k == 100 and i * 5 + j * 3 + k / 3 == 100:
                print("公鸡:%d只,母鸡:%d只,小鸡:%d只" % (i, j, k))
for i in range(1, 19):
    for j in range(1, 32):
        k = 100 - i - j
        if i + j + k == 100 and i * 5 + j * 3 + k / 3 == 100:
            print("公鸡:%d只,母鸡:%d只,小鸡:%d只" % (i, j, k))
for i in range(1, 14):
    for j in range(1, 24):
        k = 100 - i - j
        if i + j + k == 100 and i * 5 + j * 3 + k / 3 == 100:
            print("公鸡:%d只,母鸡:%d只,小鸡:%d只" % (i, j, k))
for i in range(1, 14):
    j = (100 - 7 * i) / 4
    k = 100 - i - j
    if i % 4 == 0:
        print("公鸡:%d只,母鸡:%d只,小鸡:%d只" % (i, j, k))

组合数据类型

1.列表

b_list = input("请输入数据:")
a_list = []
for i in b_list.split(','):
    a_list.append(i)
print("逆置前的数据为:", a_list)
n = len(a_list)
for i in range(n // 2):
    a_list[i], a_list[n - i - 1] = a_list[n - i - 1], a_list[i]
print("逆置后数据为:", a_list)
m = 1000
for a in range(2, m + 1):
    s = 0
    L1 = []
    for i in range(1, a):
        if a % i == 0:
            s += i
            L1.append(i)
            if s == a:
                print("%d its factors are:" % a, L1)

2.元组

# 包含整数、浮点数、字符串的元组
tuple_one = (10, 3.14, "hello")
# 包含布尔值、列表、另一个元组的元组
tuple_two = (True, [1, 2], (4, 5))
# 二维平面坐标元组
point_one = (2, 5)
# 三维空间坐标元组
point_two = (1, 3, 7)
# 学生姓名、年龄、成绩元组
student_one = ("Alice", 20, 85)
# 另一个学生信息元组
student_two = ("Bob", 21, 90)

3.字符串

字符串的常用操作

字符串创建

str1="Hello"
str1
'Hello'
str2='Program\n\'Python\''
str2
"Program\n'Python'"

字符串元素读取

str1[0]
'H'
str[-1]
'g'

字符串分片

str="Python Program"
str[0:5:2]
'Pto'
str[:]
'Python Program'
str[-1:-20]
''
str[-1:-20:-1]
'margorP nohtyP'

连接

"Hello"+"World"
'HelloWorld'
"p"+"y"+"t"+"h"+"o"+"n"+"Program"
'pythonProgram'
"python"+str(3)
'python3'

重复

"Hello"*3
'HelloHelloHello'
3*"Hello World"
'Hello WorldHello WorldHello World'

关系运算

"a"=="a"
True
"a"=="A"
False
"0">"1"
False
"abc"<"abd"
True
"abc">"abcd"
False
"abc"<"cde"
True
""<"0"
True

成员运算

"ab" in "anbcd"
False
"ab" in"abcd"
True
"abc" not in "abcd"
False

字符串的常用方法

子串查找

s1="beijingisbeijingbeijing"
s1.find("beijing")
0
s1.find("beijing",3)
9
s1.find("beijing",3,20)
9

字符串替换

s2="this is haha, this is haha"
s2.replace("is","was")
'thwas was haha, thwas was haha'
s2.replace("is","was",2)
'thwas was haha, this is haha'

字符串分离

s3="beijing,shanghai,xian,tianjing,chongqing"
s3.split(',')
['beijing', 'shanghai', 'xian', 'tianjing', 'chongqing']
s3.split('a')
['beijing,sh', 'ngh', 'i,xi', 'n,ti', 'njing,chongqing']
s3.split()
['beijing,shanghai,xian,tianjing,chongqing']

字符串连接

s4=["beijing","xian","tianjin","chongqing"]
sep="-->"
str=sep.join(s4)
str
'beijing-->xian-->tianjin-->chongqing'
s5=("hello","world")
sep=""
sep.join(s5)
'helloworld'
方法 功能
str() 将其他数据类型转换为字符串
find(sub) 查找子字符串 sub 在字符串中的位置,找不到返回 -1
index(sub) 类似 find ,但找不到时会抛出 ValueError
rfind(sub) 从右向左查找子字符串 sub 的位置
replace(old, new, count) 替换字符串中的子字符串,count 为替换次数
startswith(prefix) 检查字符串是否以 prefix 开头
endswith(suffix) 检查字符串是否以 suffix 结尾
isalpha() 判断字符串是否只包含字母
isdigit() 判断字符串是否只包含数字
isalnum() 判断字符串是否只包含字母和数字
isspace() 判断字符串是否只包含空白字符
lower() 将字符串中的所有字符转为小写
upper() 将字符串中的所有字符转为大写
title() 将字符串的每个单词首字母大写
capitalize() 将字符串的第一个字符大写,其他字符小写
strip() 去掉字符串两端的空白字符(默认),或者去掉指定字符
lstrip() 去掉字符串左边的空白字符(默认)
rstrip() 去掉字符串右边的空白字符(默认)
zfill(width) 将字符串填充为指定的宽度,使用 0 填充
split(sep, maxsplit) 将字符串分割成一个列表,sep 为分隔符,maxsplit 为最大分割次数
rsplit(sep, maxsplit) 从右向左分割字符串
join(iterable) 将一个可迭代对象中的元素连接成一个字符串,iterable 是字符串列表
format(*args, **kwargs) 用 {} 占位符在字符串中插入数据
f"…" f - string 格式化字符串(Python 3.6+)
encode(encoding) 将字符串编码为字节对象,encoding 是编码方式
decode(encoding) 将字节对象解码为字符串
count(sub) 计算子字符串 sub 在字符串中出现的次数
partition(separator) 将字符串分为三部分,返回一个三元组(head, separator, tail)
removeprefix(prefix) 如果字符串以 prefix 开头,则去除它
removesuffix(suffix) 如果字符串以 suffix 结尾,则去除它
len(s) 返回字符串的长度

字符串的应用

从键盘输入5个单词,输出其中以元音字母开头的单词

str = "AEIOUaeiou"
a_list = []
for i in range(0, 5):
    word = input("请输入一个英文单词:")
    a_list.append(word)
print("输入的5个英文单词是:",a_list)
print("首字母是元音的英文单词有:")
for i in range(0, 5):
    for ch in str:
        if a_list[i][0] == ch:
            print(a_list[i])
            break

输入一段字符,统计其中单词的个数,单词之间用空格分隔

str = input("请输入一串字符:")
flag = 0
count = 0

for c in str:
    if c == " ":
        flag = 0
    else:
        if flag == 0:
            flag = 1
            count = count + 1
print("共有%d个单词" % count)

输入一行字符,分别统计出其中英文字母、空格、数字和其他字符的个数

a_list = list(input("请输入一行字符:"))
letter = []
space = []
number = []
other = []

for i in range(len(a_list)):
    if ord(a_list[i]) in range(65, 91) or ord(a_list[i]) in range(97, 123):
        letter.append(a_list[i])
    elif a_list[i] == ' ':
        space.append(' ')
    elif ord(a_list[i]) in range(48, 58):
        number.append(a_list[i])
    else:
        other.append(a_list[i])

print('英文字母个数:%s' % len(letter))
print('空格个数:%s' % len(space))
print('数字个数:%s' % len(number))
print('其他字符个数:%s' % len(other))

4.字典

字典的基本操作

字典的创建

a_dict={'Alice':95,'Beth':79,'Emily':95,'Tom':65.5}   
a_dict    
{'Alice': 95, 'Beth': 79, 'Emily': 95, 'Tom': 65.5}

b_dict={}      
b_dict       
{}

c_dict=dict(zip(['one','two','three'],[1,2,3]))
c_dict   
{'one': 1, 'two': 2, 'three': 3}

d_dict=dict(one=1,two=2,three=3)    
d_dict
{'one': 1, 'two': 2, 'three': 3}

e_dict=dict([('one',1),('two',2),('three',3)])  
e_dict    
{'one': 1, 'two': 2, 'three': 3}

f_dict=dict((('one',1),('two',2),('three',3)))
f_dict
{'one': 1, 'two': 2, 'three': 3}

g_dict=dict()
g_dict
{}

h_dict={}.fromkeys((1,2,3),'student')
h_dict
{1: 'student', 2: 'student', 3: 'student'}

i_dict={}.fromkeys((1,2,3))
i_dict
{1: None, 2: None, 3: None}

j_dict={}.fromkeys(())
j_dict
{}

字典元素的读取

a_dict={'Alice':95,'Beth':82,'Tom':65.5,'Emliy':95}        
a_dict['Tom']       
65.5

a_dict.get('Alice')       
95

a_dict.get('a','address')       
'address'

print(a_dict.get('a'))      
None

字典元素的添加与修改

a_dict['Beth']=79    
a_dict      
{'Alice': 95, 'Beth': 79, 'Tom': 65.5, 'Emliy': 95}

a_dict['Eric']=98      
a_dict      
{'Alice': 95, 'Beth': 79, 'Tom': 65.5, 'Emliy': 95, 'Eric': 98}

a_dict       
{'Alice': 95, 'Beth': 79, 'Tom': 65.5, 'Emliy': 95, 'Eric': 98}
b_dict={'Eric':98,'Tom':82}      
a_dict.update(b_dict)     
a_dict      
{'Alice': 95, 'Beth': 79, 'Tom': 82, 'Emliy': 95, 'Eric': 98}

删除字典的元素

del a_dict['Beth']      
a_dict       
{'Alice': 95, 'Tom': 82, 'Emliy': 95, 'Eric': 98}

a_dict.pop('Alice')     
95
a_dict      
{'Tom': 82, 'Emliy': 95, 'Eric': 98}

a_dict.popitem()       
('Eric', 98)
a_dict     
{'Tom': 82, 'Emliy': 95}

a_dict.clear()     
a_dict       
{}

删除字典

del a_dict

字典的遍历

a_dict={'Alice':95,'Beth':79,'Emily':95,'Tom':65.5}
    
a_dict.keys()     
dict_keys(['Alice', 'Beth', 'Emily', 'Tom'])

a_dict.values()
dict_values([95, 79, 95, 65.5])

a_dict.items()     
dict_items([('Alice', 95), ('Beth', 79), ('Emily', 95), ('Tom', 65.5)])
方法 功能
dict(seq) 用(键,值)对(或者映射和关键字参数)创建字典
get(key[,returnvalue]) 返回key的值,若无key而指定了returnvalue,则返回returnvalue值;若无此值则返回None
has_key(key) 如果key存在于字典中,返回1(真);否则返回0(假)
items() 返回一个由元组构成的列表,每个元组包含一个键值对
keys() 返回一个由字典所有的键构成的列表
popitem() 删除任意的键值对,并作为两个元素的元组返回。若字典为空,则返回KeyError异常
update(newDictionary) 将来自newDictionary的所有键值添加到当前字典中,并覆盖同名键的值
values() 以列表的方式返回字典的所有“值”
clear() 从字典中删除所有项

字典的应用

将一个字典的键和值对调

a_dict = {'a': 1, 'b': 2, 'c': 3}
b_dict = {}
for key in a_dict:
    b_dict[a_dict[key]] = key
print(b_dict)

输入一串字符,统计其中每个单词出现的次数,单词之间用空格分隔开

string = input("input string:")
string_list = string.split()
word_dict = {}
for word in string_list:
    if word in word_dict:
        word_dict[word] += 1
    else:
        word_dict[word] = 1
print(word_dict)

5.集合

方法 功能
s.update(t) 用t中的元素修改,即修改之后s中包含s和t的成员
s.add(obj) 在s集合中添加对象obj
s.remove(obj) 从集合s中删除对象obj,如果obj不是s中的元素,将触发KeyError错误
s.discard(obj) 如果obj是集合s中的元素,从集合s中删除对象obj
s.pop() 删除集合s中的任意一个对象,并返回该对象
s.clear() 删除集合s中的所有元素

正则表达式

1.正则表达式的语法

字符 功能
. 匹配任意1个字符(除了\n)
[] 匹配[]中列举的字符
\d 匹配数字,即0-9
\D 匹配非数字,即不是数字
\s 匹配空白,即 空格,tab键
\S 匹配非空白
\w 匹配单词字符,即a-z、A-Z、0-9、_
\W 匹配非单词字符
* 匹配前一个字符出现0次或者无限次,即可有可无
+ 匹配前一个字符出现1次或者无限次,即至少有1次
? 匹配前一个字符出现1次或者0次,即要么有1次,要么没有
{m} 匹配前一个字符出现m次
{m,} 匹配前一个字符至少出现m次
{m,n} 匹配前一个字符出现从m到n次
^ 匹配字符串开头
$ 匹配字符串结尾
\b 匹配一个单词的边界
\B 匹配非单词边界
| 匹配左右任意一个表达式
(ab) 将括号中字符作为一个分组
\num 引用分组num匹配到的字符串
(?P) 分组起别名
(?P=name) 引用别名为name分组匹配到的字符串

2.re模块

compile()

import re

str = "I love china"
pattern = 'china'
a = re.compile(pattern)  # 匹配str中的字符串‘china'
print(a.findall(str))  # 返回一个列表

search()

import re

str = "Good Bye!Good Bye"
print(re.search("Bye",str))
<re.Match object; span=(5, 8), match='Bye'>

match()

import re

str = "12345helloworld12345helloworld"
pattern = r'(\d*)([a-zA-z]*)'
m = re.match(pattern, str)
print(m)
print(m.string)
print(m.re) 
print(m.pos)
print(m.endpos)
print(m.lastindex)
print(m.lastgroup)
print(m.group(0))
print(m.groups())
print(m.groupdict())
print(m.start(1))
print(m.end(1))
print(m.start(2))
print(m.end(2))
print(m.span(2))

findall()

import re

str = input()
p = re.compile('^[a-zA-z0-9]+$')
a = p.findall(str)
print(a)

finditer()

import re

str="Python 2.10;Python 3.10"
p=r'[0-9]'
for i in re.finditer(p,str):
    if i:
        print(i.group(0))

sub()

import re

str = input()
p = r'(元|人民币|RMB)'
a = re.sub(p, '¥', str)
print(a)

split()

import re

str = "Python 2.10;Python 3.10"
print(re.split(r';', str))
print(re.split(r'[.;]', str))

3.应用

import re

p = re.compile("^[a-zA-z0-9]{1,10}@[a-zA-z0-9]{1,10}\.(com|org)$")
str = input()
m = p.match(str)
if m:
    print("%s符合规则" % str)
else:
    print("%s不符合规则" % str)
import random
import re
import string

a_list = []
x = string.ascii_letters + string.digits + "_#$*@"
for i in range(10):
    y = [random.choice(x) for i in range(random.randint(1, 25))]
    m = ''.join(y)
    a_list.append(m)
print(a_list)
p = r'^[a-zA-z]{1}[a-zA-z0-9*@]{4,19}$'
for i in a_list:
    if re.findall(p, i):
        print(i)
import re

name = input("输入用户名:")
password = input("输入密码:")
rname = re.compile(r"^[A-Za-z_]{1}[A-za-z\\d_]{5,19}$")
rpassword = re.compile(r"^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?![_]+$)[0-9a-zA-Z_]{7,19}$")
if rname.match(name) and rpassword.match(password):
    print("匹配成功")
else:
    print("匹配不成功")

函数

1.函数的定义与调用

def getMax(a, b, c):
    if a > b:
        max = a
    else:
        max = b
    if c > max:
        max = c
    return max


a, b, c = eval(input("input a,b,c:"))
n = getMax(a, b, c)
print("max=", n)

2.函数的参数及返回

def swap(a_list):
    a_list[0], a_list[1] = a_list[1], a_list[0]
    print("a_list[0]=", a_list[0], "a_list[1]=", a_list[1])


x_list = [3, 5]
swap(x_list)
print("x_list[0]=", x_list, "x_list[1]=", x_list[1])
def func(x, n=2):
    f = 1
    for i in range(n):
        f *= x
    return f


print(func(5))
print(func(5, 3))
def func(x, a_list=[]):
    a_list.append(x)
    return a_list


print(func(1))
print(func(2))
print(func(3))
def func(x, a_list=None):
    if a_list == None:
        a_list = []
    a_list.append(x)
    return a_list


print(func(1))
print(func(2))
print(func(3))
def func(*para_t):
    print("可变长参数数量为:")
    print(len(para_t))
    print("参数依次为:")
    for x in range(len(para_t)):
        print(para_t[x])


func('a')
func(1, 2, 3,4)
def func(para, *para_a, **para_b):
    print("para:", para)
    for value in para_a:
        print("other_para:", value)
    for key in para_b:
        print("dictpara:{0}:{1}".format(key, para_b[key]))


func(1, 'a', True, name='Tom', age=12)
def isprime(n):
    for i in range(2, n):
        if n % i == 0:
            return 0
    return 1


m = int(input("请输入一个整数:"))
flag = isprime(m)
if flag == 1:
    print("%d是素数" % m)
else:
    print("%d不是素数" % m)
def getMaxMin(x):
    max=x[0]
    min=x[0]
    for i in range(0, len(x)):
        if max < x[i]:
            max = x[i]
        if min > x[i]:
            min = x[i]
    return (max, min)


a_list = [-1, 28, -15, 5, 100]
x, y = getMaxMin(a_list)
print("a_list=", a_list)
print("最大值=", x, "最小值=", y)

string = "Hello"
x, y = getMaxMin(string)
print("string=", string)
print("最大值=", x, "最小值=", y)

3.函数的嵌套调用和递归调用

def fac(n):
    if n == 0:
        f = 1
    else:
        f = fac(n - 1) * n
    return f


n = int(input())
f = fac(n)
print(f)

4.匿名函数

# 无参数
lambda_a = lambda: "Computer"
print(lambda_a())

# 一个参数
lambda_b = lambda n: n * 1001
print(lambda_b(5))

# 多个参数
lambda_c = lambda a, b, c, d: a + b + c + d
print(lambda_c(1, 2, 3, 4))

# 嵌套条件分支
lambda_d = lambda x, y: x if x > y else y
print(lambda_d(3, 5))


# 作为函数参数
def func1(a, b, func):
    print('a=', a)
    print('b=', b)
    print('a * b=', func(a, b))


func1(3, 5, lambda a, b: a * b)


# 作为函数的返回值
def func2(a, b):
    return lambda c: a * b * c


retrun_func = func2(2, 4)
print(retrun_func(6))

5.变量的作用域

局部变量

def fun(x):
    print("x=", x)
    x = 20
    print("changed local x=", x)


x = 30
fun(30)
print("main x=", x)

全局变量

x = 30


def func():
    global x
    print("x=", x)
    x = 20
    print("x=", x)


func()
print("x=", x)

6.模块

  • 导入模块

import 模块

  • 导入模块中的函数

from 模块名 import 函数名

  • 导入模块中的所有函数

from 模块名 import *

7.应用

def insert_sort(array):
    for i in range(1, len(array)):
        if array[i - 1] > array[i]:
            temp = array[i]
            index = i
            while index > 0 and array[index - 1] > temp:
                array[index] = array[index - 1]
                index -= 1
            array[index] = temp


b = input("请输入一组数据:")
array = []
for i in b.split(','):
    array.append(int(i))
print("排序前的数据:")
print(array)
insert_sort(array)
print("排序后的数据:")
print(array)
def xn(x, n):
    if n == 0:
        f = 1
    else:
        f = x * xn(x, n - 1)
    return f


x, n = eval(input("情输入x和n:"))
if n < 0:
    n = -n
    y = xn(x, n)
    y = 1 / y
else:
    y = xn(x, n)
print(y)

文件

1.文件的打开与关闭

  • r(read):读
  • w(write):写
  • a(append):追加
  • t(text):文本文件,可省略不写
  • b(binary):二进制文件
  • +:读与写
x = open("D:\\pythoncode\\test.txt", 'r', buffering=1024)
fp = open("D:\\pythoncode\\test.txt", 'r')
# 返回文件的名称
print(fp.name)
# 返回文件的打开方式
print(fp.mode)
# 如果文件被关闭返回True,否则返回False
print(fp.closed)

2.文件的读写

read()

fp = open("D:\\pythoncode\\test.txt", 'r', encoding="utf-8")
string1 = fp.read()
print("%s" % string1)
fp = open("D:\\pythoncode\\test.txt", 'r', encoding="utf-8")
string2 = fp.read(10)
print("%s" % string2)

readline()

fp = open("D:\\pythoncode\\test.txt", 'r', encoding="utf-8")
string3 = fp.readline()
print(string3)

readlines()

fp = open("D:\\pythoncode\\test.txt", 'r', encoding="utf-8")
string4 = fp.readlines()
print(string4)
string5 = fp.readlines()  # 再次读取文件,返回空列表
print(string5)

write()

fp = open("D:\\pythoncode\\test.txt", 'w', encoding="utf-8")
a = fp.write("Python")
print(a)
b = fp.write("Python programing")
print(b)
fp.close()

writelines()

fp = open("D:\\pythoncode\\test.txt", 'w', encoding="utf-8")
fp.writelines(["Python","Python programming"])
def split_file(filename):
    col1 = []
    col2 = []
    fd = open(filename, encoding="utf-8")
    text = fd.read()
    lines = text.splitlines()
    for line in lines:
        part = line.split(None, 1)
        col1.append(part[0])
        col2.append(part[1])
    return col1, col2


def write_list(filename, alist):
    fd = open(filename, 'w', encoding="utf-8")
    for line in alist:
        fd.write(line + '\n')


filename = 'D:\\pythoncode\\text\\input.text'
col1, col2 = split_file(filename)
write_list('D:\\pythoncode\\text\\col1.text', col1)
write_list('D:\\pythoncode\\text\\col2.text', col2)

二进制的读写
pack()

import struct

x = 100
y = struct.pack('i', x)
print(y)
print(len(y))
fp = open("D:\\pythoncode\\test.txt", "wb")
print(fp.write(y))
fp.close()
import struct

i = 12345
f = 2017.2017
b = False
string = struct.pack('if? ', i, f, b)
fp = open("D:\\pythoncode\\test.txt", "wb")
fp.write(string)
fp.close()

dump()

import pickle

x = 100
fp = open("D:\\pythoncode\\test.txt", "wb")
pickle.dump(x, fp)
fp.close()
import pickle

i = 12345
f = 2017.2017
b = False
fp = open("D:\\pythoncode\\test.txt", "wb")
pickle.dump(i, fp)
pickle.dump(f, fp)
pickle.dump(b, fp)
fp.close()

unpack()

import struct

fp = open("D:\\pythoncode\\test.txt", "rb")
y = fp.read()
x = struct.unpack('i', y)
print(x)

load()

import pickle

fp = open("D:\\pythoncode\\test.txt", "rb")
x = pickle.load(fp)
fp.close()
print(x)
import pickle

fp = open("D:\\pythoncode\\test.txt", "rb")
while True:
    n = pickle.load(fp)
    if fp:
        print(n)
    else:
        break
fp.close()

3.文件的定位

tell

fp = open("D:\\pythoncode\\test.txt", "rb")
print(fp.tell())
fp.read(10)
print(fp.tell())

seek

  • 0:文件开始
  • 1:当前位置
  • 2:文件末尾
fp = open("D:\\pythoncode\\test.txt", "rb")
print(fp.read())
print(fp.read())
print(fp.seek(0, 0))
print(fp.read())
print(fp.seek(6, 0))
print(fp.read())
print(fp.seek(6, 2))
print(fp.read())

4.与文件相关的模块

import os

print(os.getcwd())  # 显示当前的工作目录
os.chdir("e:\\")  # 改变当前的工作目录
print(os.getcwd())
print(os.listdir("c:\\"))  # 列出指定目录下的所有的文件和目录
import os

os.mkdir("python")  # 创建单级目录
import os

os.makedirs(r"e:\\aa\\bb\\cc")  # 递归创建多级目录
import os

os.rmdir("python")  # 删除指定目录
os.removedirs(r"aa\\bb\\cc") # 递归删除指定目录
os.rename("a.txt","b.txt") # 重命名
os.remove("b.txt") # 删除文件
os.stat("b.txt") # 获取文件的所有属性
os.path.spilt("e:\\program\\soft\\python\\") # 分离文件名和路径
os.path.spiltext("e:\\program\\soft\\python\\prime.py") # 分离文件名与扩展名
os.path.abspath('prime.py') #获取绝对路径
os.chdir(r"e:\\") 
os.path.getsize('e:\\string1.txt') # 获取指定文件的大小
os.path.getatime('e:\\string1.txt') # 返回指定文件的最近的访问时间
os.path.exists("prime.py") # 判断文件或者目录是否存在,返回值是True和False

异常处理

  • 语法错误
  • 编译错误
  • 系统错误
try: 
     语句块
except:
     异常处理语句块

异常处理结构

import random

num = random.randint(1, 10)
while True:
    try:
        guess = int(input("Enter 1~10:"))
    except:
        print("请输入1~10的数字")
        continue
    if guess > num:
        print("大")
    elif guess < num:
        print("小")
    else:
        print("成功")
        break
try:
    x = input("请输入被除数:")
    y = input("请输入除数:")
    z = int(x) / float(y) * 1.0
except ZeroDivisionError:
    print("除数不能为0")
except NameError:
    print("变量不存在")
else:
    print(x, "/", y, "=", z)
try:
    fp = open("test04.py", "r")
    ss = fp.read()
    print(ss)
except IOError:
    print("IOError")
finally:
    print("close file!")
    fp.close()

自定义异常

class Networkerror(RuntimeError):
    def __init__(self, arg):
        self.args = arg

try:
    raise Networkerror("myexception")
except Networkerror as e:
    print(e.args)

断言与上下文

断言

from math import sqrt


def isPrime(n):
    try:
        assert n >= 2  # 断言
    except AssertionError:
        print("AssertionError")
    for i in range(2, int(sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True


while True:
    n = int(input("请输入一个整数:"))
    flag = isPrime(n)
    if flag == True:
        print("%d是素数" % n)
    else:
        print("%d不是素数" % n)

上下文管理

with open('text.txt') as f:
    for line in f:
        print(line, end=' ')

面向对象程序设计

类与对象

class Dog:
    def describe(self):
        print('This is Dog')


dog = Dog()
dog.describe()
# 判断dog是否是Dog的实例
print(isinstance(dog, Dog))
class Dog:
    def __init__(this, d):
        this.value = d

    def show(this):
        print(this.value)


dog = Dog(23)
dog.show()

属性与方法

class Cat:
    size = 'small'

    def __init__(self, s):
        self.name = s


cat1 = Cat('mi')
cat2 = Cat('mao')
print(cat1.name, cat2.name)
Cat.size = 'big'
Cat.price = 1000
Cat.name = 'maomi'
print(cat1.size)
print(cat2.price)
class Animal:
    def __init__(self):
        self.name = 'cat'
        self.__color = 'white'

    def setValue(self, n2, c2):
        self.name = n2
        self.__color = c2

    def get_color(self):
        return self.__color

a = Animal()
print(a.name)
# 通过定义一个获取私有属性的公有方法来访问私有属性
print(a.get_color())

# 如果想要修改私有属性的值,可以通过公有方法来间接修改
a.setValue('dog', 'black')
print(a.name)
print(a.get_color())
class Animal:
    specie = 'cat'

    def __init__(self):
        self.__name = 'mao'  # 定义和设置私有方法
        self.__color = 'black'

    def __outPutName(self):  # 定制私有函数
        print(self.__name)

    def __outPutColor(self):
        print(self.__color)

    def outPut(self):  # 定义共有函数
        self.__outPutName()  # 调用私有函数
        self.__outPutColor()

    @staticmethod
    def getSpecie():
        return Animal.specie  # 调用类属性

    @staticmethod
    def setSpecie(s):
        Animal.specie = s


cat = Animal()
cat.outPut()
print(Animal.getSpecie())
Animal.setSpecie('dog')
print(Animal.getSpecie())

继承和多态

class Animal(object):  # 定义基类
    size = 'small'

    def __init__(self):  # 基类构造函数
        self.color = 'white'
        print('superClass:init of animal')

    def outPut(self):  # 基类公有函数
        print(self.size)


class Dog(Animal):  # 子类Dog,继承自Animal类
    def __init__(self):  # 子类构造函数
        self.name = 'dog'
        print('SubClass:init of dog')

    def run(self):
        print(Dog.size, self.color, self.name)
        Animal.outPut(self)  # 通过父类名调用父类构造函数(方法一)


class Cat(Animal):  # 子类Cat,继承自Animal类
    def __init__(self):  # 子类构造函数
        self.name = 'cat'
        print('subClass: init of cat')

    def run(self):  # 子类方法
        super(Cat, self).__init__()  # 调用父类构造函数(方法二)
        print(Cat.size, self.color, self.name)
        super().outPut()  # 调用父类构造函数(方法三)


a = Animal()
a.outPut()
dog = Dog()
dog.size = 'mid'
dog.color = 'black'
dog.run()
cat = Cat()
cat.name = 'maomi'
cat.run()
class A(object):  # 父类 A
    def __init__(self):
        print('start A')
        print('end A')

    def fun1(self):  # 父类函数
        print('a_fun1')


class B(A):
    def __init__(self):  # 类B继承于父类A
        print('start B')
        super(B, self).__init__()
        print('end B')

    def fun2(self):
        print('b_fun2')


class C(A):  # 类C继承于父类A
    def __init__(self):
        print('start C')
        super(C, self).__init__()
        print('end C')

    def fun1(self):  # 重新父类函数
        print('c_fun1')


class D(B, C):
    def __init__(self):  # 类D同时继承自类B和类C
        print('start D')
        super(D, self).__init__()
        print('end D')


d = D()
d.fun1()
class A(object):
    def run(self):
        print('this is A') 


class B(A):
    def run(self):
        print('this is B')


class C(A):
    def run(self):
        print('this is C')


b = B()
b.run()
c = C()
c.run()

举例

class ListArr:
    def __init__(self):
        self.sum = 0
        self.pro = 1

    def add(self, l):
        for item in l:
            self.sum += item

    def product(self, l):
        for item in l:
            self.pro *= item


a = [1, 2, 3, 4]
l = ListArr()
l.add(a)
l.product(a)
print(l.sum)
print(l.pro)
import random


class OrderList:
    def __init__(self):
        self.arr = []
        self.num = 0

    def getList(self):
        for i in range(10):
            self.arr.append(random.randint(1, 100))
            self.num += 1

    def selectSort(self):
        for i in range(0, self.num - 1):
            for j in range(i + 1, self.num):
                if self.arr[i] > self.arr[j]:
                    self.arr[i], self.arr[j] = self.arr[j], self.arr[i]


lst = OrderList()
lst.getList()
print("before:", lst.arr)
lst.selectSort()
print('alter:', lst.arr)

Python标准库

random库

seed(a)

import random

num = 0
while num < 5:
    # 初始化伪随机数生成器
    random.seed(5)
    # 返回一个介于[0.0,1.0)间的浮点数
    print(random.random())
    num += 1
import random

num = 0
# 初始化伪随机数生成器
random.seed(5)
while num < 5:
    # 返回一个介于[0.0,1.0)间的浮点数
    print(random.random())
    num += 1

randint(a,b)

import random

# 返回一个大于等于a且小于等于b的随机整数
print(random.randint(3, 10))
print(random.randint(3, 10))

randrange([start,]end[,step])

import random

# 从指定范围start~end内,按指定步长step递增的集合中,获取一个随机整数
print(random.randrange(1, 10, 2))
print(random.randrange(1, 10, 2))

choice(seq)

import random

# 从中随机取出一个元素
print(random.choice([1, 2, 3, 5, 9]))
print(random.choice('A string'))

shuffle(x[,random])

import random

list = [20, 16, 10, 5]
# 打乱序列
random.shuffle(list)
print("随机排序列表:", list)
random.shuffle(list)
print("随机排序列表:", list)

sample(population,k)

import random

# 从population样本或集合中随机抽取k个不重复的元素形成新的序列
print(random.sample([10, 20, 30, 40, 50], k=4))
print(random.sample([10, 20, 30, 40, 50], k=4))
print(random.sample([10, 20, 30, 40, 50], k=4))

uniform(a,b)

import random

# 返回a~b的浮点数
print(random.uniform(10, 20))

举例

import random

a_list = []
for i in range(97, 123):
    a_list.append(chr(i))
for i in range(65, 91):
    a_list.append(chr(i))
for i in range(48, 58):
    a_list.append(chr(i))

length = len(a_list)

x = int(input("请输入随机数种子x:"))
n = int(input("请输入生成密码的个数n:"))
m = int(input("请输入每个密码的字符串m:"))
random.seed(x)
for i in range(n):
    for j in range(m):
        print(a_list[random.randint(0, length)], end='')
    print()
from random import *

n = int(input("请输入n的值(1~10):"))
m = int(input("请输入m的值:"))
count = 1
seed(m)
b = int(randint(1, 10))
while True:
    if b == n:
        break
    count = count + 1
    b = int(randint(1, 10))
print("{} times to go it".format(count))

turtle库

import turtle

t=turtle.Pen()
t.pencolor("blue")
for i in range(6):
    t.forward(100)
    t.left(60)
import turtle

turtle.pensize(5)
turtle.pencolor("yellow")
turtle.fillcolor("red")

turtle.begin_fill()

for i in range(5):
    turtle.forward(200)
    turtle.right(144)
turtle.end_fill()

turtle.penup()
turtle.goto(-150, -120)
turtle.color("violet")
turtle.write("五角星", font=('Arial', 40, 'normal'))

time库

import time

t = time.time()
print("now time is:{}".format(t))
m = time.localtime(t)
print("now time is:{}".format(m))
time.sleep(2)
t = time.time()
n = time.localtime(t)
print("now time is:{}".format(n))

你可能感兴趣的:(语言,python,开发语言)