python基础语法元素笔记_【笔记】《Python语言以及应用》- 基础语法

主要内容:

Python基本元素:数字、字符串和变量

Python容器:列表、元组、字典、集合

程序结构

一、Python基本元素:数字、字符串和变量

Python基本数据类型(不可变): bool, int, float, str

1. 变量

变量名只能包含大小写字母、数字、下划线,开头不能为数字

type()检查对象的类型: type('hello') #

2. 数字

常见运算: +, -, *, /(浮点数除法,结果为小数), //(整除,结果为整数), %(求余), **(幂)

自运算: -=, +=, *=, /=, ...

类型转换: int(), float()

隐式转换: int + float = float, bool + int = int

divmod(9, 5) # (1, 4) 类似于(9 // 5, 9 % 5),获得整数和余数

3. 字符串

三元引号用于创建多行字符串: 每一行的换行符以及行首和行尾的空格都会被保留

single = 'hello world'

multi = '''

hello

world

'''

print(len(single)) # 11

print(len(multi)) # 17

类型转换: str()

转义字符: \n, \t, \', \", \\, \000(空格)

常用操作:

拼接+: 'a' + 'b' # ab

复制*: 'a' * 3 # aaa

提取单个字符[]: 'abc'[1] # b(超过偏移量报错)

切片[start:end:step](不包括end):

[:]复制整个字符

[start:]从start到结尾

[:end]从开头到end-1

[start:end]从start到end-1

[start:end:step]从start到end-1, 每step个字符提取一个

[-n:]最后n个

[::-1]反向, 等同于[-1::-1]

对于超过偏移量的,start当作0, end当作-1

len()获取长度

split()分割(默认使用空白字符-\n,\t,\000): 'a,b,c'.split(',') # ['a', 'b', 'c']

join()合并: ','.join(['a', 'b', 'c']) # 'a,b,c'

字符串常用方法:

str.startswith('a'), 是否以'a'开头

str.endswith('a'), 是否以'a'结尾

str.find('a'), 查询第一次出现'a'的位置

str.rfind('a'), 查询最后一次出现'a'的位置

str.count('a'), 统计'a'出现的次数

str.strip(), 移除头尾指定的字符(默认为空格)

str.capitalize(), 首字母大写

str.title(), 所有单词的开头字母都大写

str.lower(), 小写

str.upper(), 大写

str.swapcase(), 大小写互换

str.replace('a ', 'hello', count), 字符串替换,count默认替换所有实例

二、Python容器:列表、元组、字典、集合

1. 列表(list: 可变、有序、重复)

创建列表: list()或者[]

转换:

字符串:list('abc') # ['a', 'b', 'c']

元组:list(('a', 'b', 'c')) # ['a', 'b', 'c']

split():'a,b,c'.split(',') # ['a', 'b', 'c']

使用[offset]获取和修改元素((超过偏移量会报错))

使用切片[start:end:step]提取部分列表(同字符串切片)

操作数组:

list.append(x)尾部添加元素

list.extend(x)或+=合并列表

list.insert(i, x)指定位置之前插入元素

del list[i]删除指定位置的元素

list.remove(x)删除具有指定值的元素(只删除匹配的第一个元素)

list.pop(i)获取并删除指定位置的元素,pop(0)头部、pop()或pop(-1)尾部

list.index(x)返回列表中第一个值为 x 的元素的索引

in判断值是否存在

list.count(x)记录x出现的次数

', '.join(list)转换为字符串

list.sort()改变list,sorted(list)不改变list,而是生成其副本,参数reverse=True改为降序排序

len(list)获取长度

数组复制:

copy函数:a.copy()

list()转换函数:list(a)

切片:a[:]

2. 元组(tuple: 不可变)

元组占用空间小

不会意外修改元组的值

可以用作字典的键

命名元组可以替代对象

函数的参数是以元组的形式传递的

# 创建元组

empty_tuple = ()

one_char = 'a',

char_tuple = 'a', 'b', 'c'

character = ('a', 'b', 'c')

# 元组解包

a, b, c = character

# 互换

b, a = a, b

# 转换

tuple(list)

3. 字典(dict: 可变)

创建字典: {}

转换:dict()(将包含双值子序列的序列转换为字典)

lol = [['a', 1], ['b', 2], ['c', 3]] # (a list of two-item list)

lot = [('a', 1), ('b', 2), ('c', 3)] # (a list of two-item tuple)

tol = (['a', 1], ['b', 2], ['c', 3]) # (a tuple of two-item list)

los = ['a1', 'b2', 'c3']

tos = ('a1', 'b2', 'c3')

dict(lol) # {'a': 1, 'b': 2, 'c': 3}

dict(lot) # {'a': 1, 'b': 2, 'c': 3}

dict(tol) # {'a': 1, 'b': 2, 'c': 3}

dict(los) # {'a': '1', 'b': '2', 'c': '3'}

dict(tos) # {'a': '1', 'b': '2', 'c': '3'}

常用操作

dict.update(d)合并字典,新规入的字典的值取代原有的值

del dict[key]删除具有指定键的元素

dict.clear()删除所有元素

in判断是否存在

dict.get(key, default)获取元素,不存在时,返回默认值(默认为None),(dict[key]获取不到时会报错)

dict.keys()获取所有的键(list(dict.keys())转换为list)

dict.values()获取所有的键(list(dict.values())转换为list)

dict.items()获取所有的键(list(dict.items())转换为list)

dict.copy()复制

4. 集合(set: 无序、不重复、可变)

集合就像舍弃了值, 仅剩下键的字典

创建集合: set(), {1, 3, 6, 9}

转换:

set('letter') # {'l', 'r', 't', 'e'}

set(['a', 'b', 'c']) # {'c', 'b', 'a'}

set(('a', 'b', 'c')) # {'c', 'b', 'a'}

set({'a': 1, 'b': 2, 'c': 3}) # {'c', 'b', 'a'}

in检查是否存在

运算符:

a = {1, 2}

b = {2, 3}

& 交集(a.intersection(b))

a & b # {2}

| 并集(a.union(b))

a | b # {1, 2, 3}

- 差集(a.difference(b))(出现在第一个集合但不出现在第二个集合)

a - b # {1}

^ 异或集(a.symmetric_difference(b))(两个集合中的不同元素)

a ^ b # {1, 3}

<= 判断子集(a.issubset(b))

a <= b # False

>= 判断真集(a.issuperset(b))

a >= b # False

三、程序结构

1. #注释

Python没有多行注释

2. \连接

把一段长代码分成多行()

# 拼接长字符串

alphabet = ''

alphabet += 'abc'

alphabet += 'def'

# 使用\

alphabet = 'abc' + \

'def'

1 + 2 + 3

使用\

1 + 2 + \

3

3. if elif else条件判断

num = 2

if num == 1:

print('This is one')

elif num === 2:

print('This is two')

else:

print('I don\'t known')

判断假值

类型

假值

bool

False

null类型

None

int

0

float

0.0

str

''

list

[]

tuple

()

dict

{}

set

set()

4. while循环

# 读入整数,如果是奇数则输出其平方数,偶数则跳过,q来结束循环

while True:

value = input('Integer, please [q to quit]: ')

if value == 'q':

break # break 跳出循环

number = int(value)

if number % 2 == 0:

continue # 跳出本次循环,继续下一个循环

print(number, 'squared is', number**2)

循环外使用else: 如果while循环正常结束(没有使用break跳出),程序将执行可选的else片段

5. for...in迭代

list, str, tuple, dict, set都是可迭代的对象

break, continue, else和while一样

range(start, stop, step)生成自然数序列(不包括stop)

zip()并行迭代

alphabet = ['a', 'b', 'c']

number = [1, 2, 3, 4]

for c, n in zip(alphabet, number):

print(c, n)

# 在最短序列用完时停止

# a 1

# b 2

# c 3

# 配对两个元组

list(zip(alphabet, number)) # [('a', 1), ('b', 2), ('c', 3)]

# 字典

dict(zip(alphabet, number)) # {'c': 3, 'a': 1, 'b': 2}

6. 推导式

列表推导式:

# [expression for item in iterable]

number_list = [x for x in range(3)] # [0, 1, 2]

# [expression for item in iterable if condition]

a_list = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]

# 嵌套循环

rows = range(1, 4)

cols = range(1, 3)

# 传统

for row in rows:

for col in cols:

print(row, col)

# 推导式

cells = [(row, col) for row in rows for col in cols]

for row, col in cells:

print(row, col)

字典推导式:

word = 'letters'

letter_counts = {letter: word.count(letter) for letter in word}

# {'e': 2, 'l': 1, 'r': 1, 't': 2, 's': 1}

集合推导式:

a_set = {number for number in range(1, 6) if number % 2 == 1}

# {1, 3, 5}

生成器推导式: (元组没有推导式)

number_thing = (number for number in range(1, 6))

type(number_thing) #

for number in number_thing:

print(number)

# 转换为list(一个生成器只运行一次,只在运行中产生值)

list(number_thing) # [1, 2, 3, 4, 5]

list(number_thing) # []

7. 函数

使用is判断None

def is_none(thing):

if thing is None:

print('It\'s None')

elif thing:

print('It\'s True')

else:

print('It\'s False')

is_none(None) # It's None

is_none([]) # It's False

is_none(1) # It's True

参数

默认参数在函数被定义时就已经计算出来了

# bug

def buggy(arg, result=[]):

result.append(arg)

print(result)

buggy('a') # ['a']

buggy('b') # ['a', 'b']

# fix

def buggy(arg, result=None):

if result is None:

result = []

result.append(arg)

print(result)

buggy('a') # ['a']

buggy('b') # ['b']

def ours(first, middle, last):

return {'first': first, 'middle': middle, 'last': last}

ours(1, 3, 7) # 位置参数

ours(1, 3, last=5) # 关键字参数(关键字参数必须跟随在位置参数的后面)

# 使用*收集位置参数: 将一组可变数量的位置参数集合成参数值的元组

def print_args(required1, required2, *args):

print(required1, required2, args)

print_args(1, 2) # 1 2 ()

print_args(1, 2, 3, 4, 5) # 1 2 (3, 4, 5)

# 使用**收集关键字参数: 将关键字参数收集到一个字典中

def print_kwargs(required1, *args, **kwargs):

print(required1, args, kwargs)

print_kwargs(1, 2, 3, a=4, b=5) # 1 (2, 3) {'b': 5, 'a': 4}

闭包:

def outer(num):

def inner():

return 'This is %d' % num

return inner

a = outer(1)

b = outer(2)

print(a()) # This is 1

print(b()) # This is 2

lambda()函数:

def edit_story(words, func):

for word in words:

print(func(word))

edit_story(['hello', 'bye', 'see'], lambda word: word.capitalize() + '!')

# Hello!

# Bye!

# See!

8. 生成器

调用生成器函数,返回一个generator对象,供迭代器产生数据

def my_range(first=0, last=10, step=1):

number = first

while number < last:

yield number

number += step

for x in my_range(1, 5):

print(x)

9. 装饰器

在不改变源代码的情况下修改已经存在的函数

def document_it(func):

def new_func(*args, **kwargs):

print('Running function:', func.__name__)

print('arguments:', args, kwargs)

result = func(*args, **kwargs)

print('Result:', result)

return result

return new_func

@document_it

def add_ints(a, b):

print('...execute...')

return a + b

# 等价于

# def add_ints(a, b):

# print('...execute...')

# return a + b

# cooler_add_ints = document_it(add_ints)

add_ints(2, 4)

# Running function: add_ints

# arguments: (2, 4) {}

# ...execute...

# Result: 6

多个装饰器时,靠近def的装饰器最先执行

10. 命名空间和作用域

name = 'a' # global

def print_global_name():

print(name, id(name))

def print_local_name():

name = 'b' # local

print(name, id(name))

def change_global_name():

global name # 修改全局变量之前先在变量前面显式声明global

name = 'b'

print(name, id(name))

print_global_name() # a 61125472

print_local_name() # b 61127936

print(name, id(name)) # a 61125472

change_global_name() # b 61127936

print(name, id(name)) # b 61127936

11. try...except处理异常

short_list = [1, 2, 3]

while True:

value = input('Position [q to quit]?')

if value == 'q':

break

try:

position = int(value)

print(short_list[position])

except IndexError as err:

print('Bad index:', position)

except Exception as other:

print('Something else broken:', other)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值