Python常见语法一

变量

  • 变量类型
1
2
3
4
5
6
7
8
a = 100
b = 123.45
c = 'hello, world'
d = True
print(type(a))  # <class 'int'>
print(type(b))  # <class 'float'>
print(type(c))  # <class 'str'>
print(type(d))  # <class 'bool'>

通过type来看变量的类型。

  • 变量转换
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
a = 100
b = 123.45
c = '123'
d = '100'
e = '123.45'
f = 'hello, world'
g = True
print(float(a))         # int类型的100转成float,输出100.0
print(int(b))           # float类型的123.45转成int,输出123
print(int(c))           # str类型的'123'转成int,输出123
print(int(c, base=16))  # str类型的'123'按十六进制转成int,输出291
print(int(d, base=2))   # str类型的'100'按二进制转成int,输出4
print(float(e))         # str类型的'123.45'转成float,输出123.45
print(bool(f))          # str类型的'hello, world'转成bool,输出True
print(int(g))           # bool类型的True转成int,输出1
print(chr(a))           # int类型的100转成str,输出'd'
print(ord('d'))         # str类型的'd'转成int,输出100
  • 算术运算
1
2
3
4
5
6
print(321 / 12)     # 除法运算,输出26.75,跟java中整除不像
print(321 // 12)    # 整除运算,输出26
print(321 % 12)     # 求模运算,输出9
print(2 ** 3)       # 幂次运算,2的3次方
# 海象运算符
print((a := 10))  # 10
  • 小数表示法
1
2
3
f = float(input('请输入华氏温度: '))
c = (f - 32) / 1.8
print('%.1f华氏度 = %.1f摄氏度' % (f, c))

解释:此处使用%.1f来格式化一个浮点类型的数,并且保留小数点1位。还有中格式化表示法:

1
2
3
f = float(input('请输入华氏温度: '))
c = (f - 32) / 1.8
print(f'{f:.1f}华氏度 = {c:.1f}摄氏度')

前面用f开头,表示里面有格式化的操作,用{f:.1f}来代替f的值,并且保留小数点1位,同理c变量也是一样。

分支

  • 分支判断
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
height = float(input('身高(cm):'))
weight = float(input('体重(kg):'))
bmi = weight / (height / 100) ** 2
print(f'{bmi = :.1f}')
if bmi < 18.5:
    print('你的体重过轻!')
elif bmi < 24:
    print('你的身材很棒!')
elif bmi < 27:
    print('你的体重过重!')
elif bmi < 30:
    print('你已轻度肥胖!')
elif bmi < 35:
    print('你已中度肥胖!')
else:
    print('你已重度肥胖!')
  • match case表示法:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
status_code = int(input('响应状态码: '))
match status_code:
    case 400: description = 'Bad Request'
    case 401: description = 'Unauthorized'
    case 403: description = 'Forbidden'
    case 404: description = 'Not Found'
    case 405: description = 'Method Not Allowed'
    case 418: description = 'I am a teapot'
    case 429: description = 'Too many requests'
    case _: description = 'Unknown Status Code'
print('状态码描述:', description)

循环

  • 循环
1
2
3
4
5
6
7
8
"""
每隔1秒输出一次“hello, world”,持续1小时
"""
import time

for i in range(3600):
    print('hello, world')
    time.sleep(1)

i的值是从0到3599。 不要i变量的时候,可以用如下写法:

1
2
3
for _ in range(3600):
    print('hello, world')
    time.sleep(1)
1
2
3
4
total = 0
for i in range(2, 101, 2):
    total += i
print(total)

range方法第一个参数是起始值,第二个参数是终止值,第三个参数是步长。其余的while循环,break和continue和java一样的用法。

列表

  • 列表的定义
1
2
3
4
5
6
items1 = [35, 12, 99, 68, 55, 35, 87]
items2 = ['Python', 'Java', 'Go', 'Kotlin']
items3 = [100, 12.3, 'Python', True]
print(items1)  # [35, 12, 99, 68, 55, 35, 87]
print(items2)  # ['Python', 'Java', 'Go', 'Kotlin']
print(items3)  # [100, 12.3, 'Python', True]

列表使用[]来初始化,可以有重复值。

  • 使用list定义列表
1
2
3
4
items4 = list(range(1, 10))
items5 = list('hello')
print(items4)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(items5)  # ['h', 'e', 'l', 'l', 'o']

使用list()来初始化一个列表。

  • 列表相加
1
2
3
4
5
6
7
items5 = [35, 12, 99, 45, 66]
items6 = [45, 58, 29]
items7 = ['Python', 'Java', 'JavaScript']
print(items5 + items6)  # [35, 12, 99, 45, 66, 45, 58, 29]
print(items6 + items7)  # [45, 58, 29, 'Python', 'Java', 'JavaScript']
items5 += items6
print(items5)  # [35, 12, 99, 45, 66, 45, 58, 29]

两个列表相加,得到一个新的列表。

  • 列表元素的获取
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
items8 = ['apple', 'waxberry', 'pitaya', 'peach', 'watermelon']
print(items8[0])   # apple
print(items8[2])   # pitaya
print(items8[4])   # watermelon
items8[2] = 'durian'
print(items8)      # ['apple', 'waxberry', 'durian', 'peach', 'watermelon']
print(items8[-5])  # 'apple'
print(items8[-4])  # 'waxberry'
print(items8[-1])  # watermelon
items8[-4] = 'strawberry'
print(items8)      # ['apple', 'strawberry', 'durian', 'peach', 'watermelon']

取列表中的元素,负数表示倒数第几个。

  • 列表区间取元素
1
2
3
4
5
print(items8[1:3:1])     # ['strawberry', 'durian']
print(items8[0:3:1])     # ['apple', 'strawberry', 'durian']
print(items8[0:5:2])     # ['apple', 'durian', 'watermelon']
print(items8[-4:-2:1])   # ['strawberry', 'durian']
print(items8[-2:-6:-1])  # ['peach', 'durian', 'strawberry', 'apple']

区间取元素,第三个参数是取值的跳跃几个。

1
2
3
4
5
print(items8[1:3])     # ['strawberry', 'durian']
print(items8[:3:1])    # ['apple', 'strawberry', 'durian']
print(items8[::2])     # ['apple', 'durian', 'watermelon']
print(items8[-4:-2])   # ['strawberry', 'durian']
print(items8[-2::-1])  # ['peach', 'durian', 'strawberry', 'apple']

三个参数可以省略,第一个参数省略是0,第二个参数省略是到最后一个元素,第三个参数省略是1。

  • 列表遍历
1
2
3
languages = ['Python', 'Java', 'C++', 'Kotlin']
for index in range(len(languages)):
    print(languages[index])

使用range的时候传入列表的长度,然后进行遍历取元素。

  • 列表的元素添加
1
2
3
4
5
languages = ['Python', 'Java', 'C++']
languages.append('JavaScript')
print(languages)  # ['Python', 'Java', 'C++', 'JavaScript']
languages.insert(1, 'SQL')
print(languages)  # ['Python', 'SQL', 'Java', 'C++', 'JavaScript']

使用append添加到列表末尾,使用insert给指定位置添加元素。

  • 列表的元素移除
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
languages = ['Python', 'SQL', 'Java', 'C++', 'JavaScript']
if 'Java' in languages:
    languages.remove('Java')
if 'Swift' in languages:
    languages.remove('Swift')
print(languages)  # ['Python', 'SQL', C++', 'JavaScript']
languages.pop()
temp = languages.pop(1)
print(temp)       # SQL
languages.append(temp)
print(languages)  # ['Python', C++', 'SQL']
languages.clear()
print(languages)  # []

在列表中用remove方法移除元素的时候,需要判断元素在不在里面,如果不在里面直接remove会报错:ValueError错误导致程序崩溃。上面使用pop方法会移除最后一个元素,pop也可以按位置指定移除,clear方法是清除所有的元素。

1
2
3
items = ['Python', 'Java', 'C++']
del items[1]
print(items)  # ['Python', 'C++']

通过del删除元素,它是不返回元素,性能上比上面的pop要好。

  • 列表的索引和频次
1
2
3
4
5
6
7
8
9
items = ['Python', 'Java', 'Java', 'C++', 'Kotlin', 'Python']
print(items.index('Python'))     # 0
# 从索引位置1开始查找'Python'
print(items.index('Python', 1))  # 5
print(items.count('Python'))     # 2
print(items.count('Kotlin'))     # 1
print(items.count('Swfit'))      # 0
# 从索引位置3开始查找'Java'
print(items.index('Java', 3))    # ValueError: 'Java' is not in list

index能找到指定元素的索引,第一个参数是元素,第二个元素是第几个。count获取元素出现的次数。

  • 列表的排序和翻转
1
2
3
4
5
items = ['Python', 'Java', 'C++', 'Kotlin', 'Swift']
items.sort()
print(items)  # ['C++', 'Java', 'Kotlin', 'Python', 'Swift']
items.reverse()
print(items)  # ['Swift', 'Python', 'Kotlin', 'Java', 'C++']

sort按照首字母进行排序,reverse进行前后翻转。

  • 列表的生成式
1
2
items = [i for i in range(1, 100) if i % 3 == 0 or i % 5 == 0]
print(items)

首先用for-in来循环1到99,后面是if过滤,如果是3或者5的倍数才会是循环要用的元素,for前面是生成式的运算,这里直接返回i,最后生成一个items的新列表。

1
2
3
nums1 = [35, 12, 97, 64, 55]
nums2 = [num ** 2 for num in nums1]
print(nums2)

对列表中的元素求平方操作,生成一个新的列表。

  • 列表嵌套
1
2
3
scores = [[95, 83, 92], [80, 75, 82], [92, 97, 90], [80, 78, 69], [65, 66, 89]]
print(scores[0]) # [95, 83, 92]
print(scores[0][1]) # 83

跟java中二维数组没什么区别。

  • 嵌套列表添加
1
2
3
4
5
6
7
8
scores = []
for _ in range(5):
    temp = []
    for _ in range(3):
        score = int(input('请输入: '))
        temp.append(score)
    scores.append(temp)
print(scores)

外层是一个大的列表,大的列表里面有5个小列表,每个小列表的大小是3。

  • 嵌套列表生成式
1
2
3
import random
scores = [[random.randrange(60, 101) for _ in range(3)] for _ in range(5)]
print(scores)

第一个for-in指定每个小列表的长度,第二个for-in指定了外层列表的长度。

元组

  • 元组的定义
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 定义一个三元组
t1 = (35, 12, 98)
# 定义一个四元组
t2 = ('张三', 45, True, '四川成都')

# 查看变量的类型
print(type(t1))  # <class 'tuple'>
print(type(t2))  # <class 'tuple'>

# 查看元组中元素的数量
print(len(t1))  # 3
print(len(t2))  # 4

# 索引运算
print(t1[0])    # 35
print(t1[2])    # 98
print(t2[-1])   # 四川成都

# 切片运算
print(t2[:2])   # ('张三', 43)
print(t2[::3])  # ('张三', '四川成都')

# 循环遍历元组中的元素
for elem in t1:
    print(elem)

# 成员运算
print(12 in t1)         # True
print(99 in t1)         # False
print('Hao' not in t2)  # True

# 拼接运算
t3 = t1 + t2
print(t3)  # (35, 12, 98, '张三', 43, True, '四川成都')

# 比较运算
print(t1 == t3)            # False
print(t1 >= t3)            # False
print(t1 <= (35, 11, 99))  # False

元组定义好后,就不能再添加元素和删除了,也不能修改。

  • 空元组和元组定义
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
a = ()
print(type(a))  # <class 'tuple'>
b = ('hello')
print(type(b))  # <class 'str'>
c = (100)
print(type(c))  # <class 'int'>
d = ('hello', )
print(type(d))  # <class 'tuple'>
e = (100, )
print(type(e))  # <class 'tuple'>

上面a是空元组,而b是一个字符串类型,c是一个int类型,d才是元祖类型,e也是,也就是说如果元祖中只有一个元素的时候,后面需要加上逗号,如果是空的就不需要加逗号,如果是两个或以上也不需要逗号。

  • 元组的打包和解包
1
2
3
4
5
6
7
# 打包操作
a = 1, 10, 100
print(type(a))  # <class 'tuple'>
print(a)        # (1, 10, 100)
# 解包操作
i, j, k = a
print(i, j, k)  # 1 10 100

打包操作只需要用逗号分隔,而解包只需要把对应的变量用逗号分隔会自定赋值。

  • 交换变量的值
1
2
3
4
a = 10
b = 20
a, b = b, a
print(a, b) # 20 10

其实这个是运用了元祖的打包和解包,首先将b,a组成一个元组,然后付给另外一个元组,然后元组进行解包,给到a和b,所以达到了互换值。

字符串

  • 转义字符串 字符串中使用\来表示转义,转义的意思是\后面字符不再是原来的意思,例如\n不是代表字符\和字符n,而是表示换行;\t也不是代表字符\和字符t,而是表示制表符。而如果想表示原始字符的话前面需要再加一个\字符:
1
2
3
4
5
s1 = '\'hello, world!\'' # 'hello, world!'
s2 = '\\hello, world!\\' # \hello, world!\
s3 = 'hello\nworld!' # hello换行world!
s5 = 'hello\\nworld!' # hello\nworld!
s4 = 'hello\tworld!' # hello	world!
  • 原始字符串 在上面默认都是\n表示换行,如果不想换行需要使用\\n来表示不转义。而如果在字符串前面加上r的话,就表示原始字符串,也就是说\n不再表示换行,而是表示\字符和n字符:
1
s3 = r'hello\nworld!' # hello\nworld!
  • 字符的特殊表示 在\字符后面可以跟一个八进制的数或者是十六进制数来表示字符,比如字符a的ASCII 码值十进制对应的是97。那么可以用\141来表示a,141表示97的八进制数。而\x61也可以表示a,61表示97的十六进制数。
1
s1 = '\141\142\143\x61\x62\x63' # abcabc

另外一种是在u后面跟 Unicode 字符编码,例如\u5f20\u4e09代表中文"张三":

1
s2 = '\u5f20\u4e09' # 张三

关于字符的遍历,索引,长度,切片等和列表类似。

集合

python中的集合和java中的集合不太一样,python中集合对应了java中set容器。也是无序,不重复

  • 集合的定义
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
set1 = {1, 2, 3, 3, 3, 2}
print(set1)

set2 = {'banana', 'pitaya', 'apple', 'apple', 'banana', 'grape'}
print(set2)

set3 = set('hello')
print(set3)

set4 = set([1, 2, 2, 3, 3, 3, 2, 1]) # {1, 2, 3}
print(set4)

set5 = {num for num in range(1, 20) if num % 3 == 0 or num % 7 == 0}
print(set5)

上面通过{}初始化一个集合,也可以通过set()来初始化一个集合。set4集合传入的是一个列表,由于是不能重复,所以只有1,2,3这三个数字。set5是通过生成式来初始化一个集合。然后集合的添加,查询等功能和列表类似。

字典

  • 字典的初始化
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
person = {"name":"张三", "age":18}
print(type(person)) # <class 'dict'>
print("name" in person) # True
print(person["name1"]) # KeyError
person["score"] = 100
for item in person:
    print(item)
student = dict()
student['name'] = "小明"
for e in student:
    print(f"key = {e}; value = {student[e]}")    
student1 ={}
student1['name'] = "小王"
for e in student1:
    print(f"key1 = {e}; value1 = {student1[e]}")    

字典是通过key和value组成,跟java的hashMap类似。通过in判断key在不在字典中,如果key不在字典中,直接去拿值的时候,会报KeyError的异常。给新的key添加元素。for in遍历的时候,取的是字典的key,如果要在for-in里面取valye的话需要通过key来取value值。上面可以通过dict()来初始化一个字典,也可以通过{}来初始化一个字典。

  • 字典的方法
1
2
print(person.get("name1")) # None
print(person.get("name1","王二")) # 王二

get方法如果获取不到对应的值不会报错,会返回None,并且第二个参数可以指定没有值的时候,返回默认值。

1
2
3
4
5
6
7
print(person.keys()) # dict_keys(['name', 'age', 'score'])
print(person.values()) # dict_values(['张三', 18, 100])
print(person.items()) # dict_items([('name', '张三'), ('age', 18), ('score', 100)])
for item in person.items():
    print(item) # ('name', '张三') ('age', 18) ('score', 100)
for k,v in person.items():
    print(item) # ('name', '张三') ('age', 18) ('score', 100)    

keys()方法获取所有的key,values()获取所有的value,items()方法能拿到所有的元素,返回的元素是一个元组,需要自己解包到对应的值上。

函数

  • 不定参数
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def add(*args):
    print(type(args)) # <class 'tuple'>
    total = 0
    # 对保存可变参数的元组进行循环遍历
    for val in args:
        # 对参数进行了类型检查(数值型的才能求和)
        if type(val) in (int, float):
            total += val
    return total
print(add(1, 2, 3,"hello",4)) # 10    

上面通过*args定义不定参数,可以传入任何类型,如果是int或者是float才累加。args参数是一个元组类型。

1
2
3
4
5
def foo(*args, **kwargs):
    print(args) # (3, 2.1, True)
    print(kwargs) # {'name': '张三', 'age': 43, 'gpa': 4.95}
    print(type(kwargs)) # <class 'dict'>
foo(3, 2.1, True, name='张三', age=43, gpa=4.95)

上面**kwargs是一个字典类型,也是一种不定参数的类型写法。

  • 函数高级用法
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def calc(init_value, op_func, *args, **kwargs):
    items = list(args) + list(kwargs.values())
    result = init_value
    for item in items:
        if type(item) in (int, float):
            result = op_func(result, item)
    return result
def add(x, y):
    return x + y

def mul(x, y):
    return x * y    

print(calc(0, add, 1, 2, 3, 4, 5))  # 15
print(calc(1, mul, 1, 2, 3, 4, 5))  # 120 

上面的calc方法在上面的不定参数中增加了init_value和op_func参数,其中init_value是初始值,op_func是传入的函数,通过外界传入函数来进行运算,有点像kotlin的高阶函数。比如下面传入add方法的时候,是对参数求和,传入mul函数的时候是对参数求乘积。 也可以传入operator模块中定义的函数:

1
2
3
import operator
print(calc(0, operator.add, 1, 2, 3, 4, 5))  # 15
print(calc(1, operator.mul, 1, 2, 3, 4, 5))  # 120
  • 内置的高阶函数
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def is_even(num):
    """判断num是不是偶数"""
    return num % 2 == 0

def square(num):
    """求平方"""
    return num ** 2

old_nums = [35, 12, 8, 99, 60, 52]
new_nums = list(map(square, filter(is_even, old_nums)))
print(new_nums)  # [144, 64, 3600, 2704]

上面的filter和map都是高阶函数,它们的第一个参数是要传入的方法,第二个参数是数据源。filter先过滤出列表的偶数,然后map进行平方操作。最后返回一个列表。

1
2
3
old_strings = ['in', 'apple', 'zoo', 'waxberry', 'pear']
new_strings = sorted(old_strings, key=len)
print(new_strings)  # ['in', 'zoo', 'pear', 'apple', 'waxberry']

前面讲过list的sort()方法, 此处的sorted方法也是类似,此处可以传入key,它也是一个方法,此处通过字符串的长度进行排序。

  • Lambda函数
1
2
3
old_nums = [35, 12, 8, 99, 60, 52]
new_nums = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, old_nums)))
print(new_nums)  # [144, 64, 3600, 2704]

filter中传入lambda x: x % 2 == 0,它就是一个Lambda函数,x表示输入,冒号后面是运算操作,最后一条语句是lambda的返回值,用来判断是不是偶数,map中传入lambda x: x ** 2,它也是一个Lambda函数,用来求平方。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import functools
import operator

# 用一行代码实现计算阶乘的函数
fac = lambda n: functools.reduce(operator.mul, range(2, n + 1), 1)

# 用一行代码实现判断素数的函数
is_prime = lambda x: all(map(lambda f: x % f, range(2, int(x ** 0.5) + 1)))

# 调用Lambda函数
print(fac(6))        # 720
print(is_prime(37))  # True

首先reduce函数是python标准库functools模块中的函数,可以实现对一组数据的规约操作,类似上面讲的calc函数,第一个参数是运算的函数,第二个参数是运算的数据,第三个参数是初始值。第二个判断素数是首先通过map传入lambda计算x%f是否不能整除,f的是lambda的输入,输入

Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy