Python基础语法

灵活,执行效率低 ,易学易用

开发哲学:用一种方法,最好是只用一种方法来做一件事

具有丰富的数据结构和第三方函数库

运算符 ** 是指数运算

Python3将raw_input和input进行整合成了input....去除了raw_input()函数....

其接受任意输入, 将所有输入默认为字符串处理,并返回字符串类型

注释

三引号:说明文档

函数

变量作用域:再函数中 使用 global 生命变量是全局变量,否则即便是重名也是局部变量

内建函数

dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

标准库函数

math、os、random、datetime

>>> import datetime
>>> dir(datetime)
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_divide_and_round', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']

>>> from datetime import datetime
>>> dt=datetime.now()
>>> dt
datetime.datetime(2020, 5, 27, 17, 5, 1, 764641)
>>> dt.strftime('%a,%b %d %Y %H:%M')
'Wed,May 27 2020 17:05'
>>> print(dt)
2020-05-27 17:05:01.764641
>>> ts = dt.timestamp()
>>> print(ts)
1590570301.764641
>>> print(datetime.fromtimestamp(ts))
2020-05-27 17:05:01.764641
>>> 

字符串

# in 判断 子串 注意大小写敏感
str1 = "chentianming1209"
print("chen" in str1)
print('Chen' in str1)

# 枚举字符 for in
str2 = "1234567890"
for char in str2:
    print(char)

# 切片 子序列 [start:end]
str3 = "1234567890abcde"
print(str3[0:2])
print(str3[-3:])

# 方法 replace 、find(返回的是索引-1是没找到)、split
str4 = "chentianming1209@163.com"
str5 = str4.replace("163","qq")
print(str5)
print(str4.find("chen")) 
print(str4.split('@'))

# 字符串格式化
str = "my name is {},my years'old is {:2d},pi is {:5.4f}"
str = str.format("chen",32,3.1415926)
print(str)

正则表达式

import re

# re库采用raw string类型表示正则表达式,表示为:r'text' 原生字符串是不包含转义字符的
# 邮政编码 r'[1-9]\d{5}'

match = re.search(r'[1-9]\d{5}','BIT 100081')
if match:
	print(match.group(0))

# match方法从开头匹配
match = re.match(r'[1-9]\d{5}','100082 BIT ')
if match:
	print(match.group(0))

# findall 返回list
match = re.findall(r'[1-9]\d{5}','100082 100081 BIT ')
print(match)

# split 函数 按匹配的分割
match = re.split(r'[1-9]\d{5}','A100082B100081C100083',maxsplit=3)
print(match)

#re.finditer

#sub替换
match = re.sub(r'[1-9]\d{5}','zipcode','A100082B100081C100083',count=3)
print(match)

#编译模式
regex = re.compile(r'[1-9]\d{5}')
match = regex.search('A100082B100081C100083')
print(match.group(0))

列表List

列表与字符串相同点

  • 索引[]
  • 切片[:]
  • 拼接+和重复*
  • 成员in
  • 长度len()
  • 循环for

不同点

  • 使用[]生成,元素之间用逗号分隔
  • 可以包含多种类型对象,字符串只能是字符
  • 内容是可变的,字符串是不可变的

列表的方法

# 切片 包左不包右
lst=[5.4,'hello',2]
print(lst[1:3])
lst[0:2]=['b','hello world']
print(lst)

# 长度
print(len(lst))
# append
lst.append(5.4)
print(lst)
# exend 扩展list
lst.extend([1,3])
print(lst)
# insert
lst.insert(0,'haha')
print(lst)
# pop
print(lst.pop())
print(lst)
# remove 删除第一个匹配的元素
lst.append('haha')
print(lst)
lst.remove('haha')
print(lst)
lst.remove('haha')
print(lst)
nums=[]
for i in range(3):
    nums.append(float(input('please input:')))
num=0
avg = sum(nums)/len(nums)
print(avg)


内建函数:sum、max、min

列表的赋值

传递的是指针

查找 list.index() 返回下标

一种由原列表创建新列表的简洁方法

[表达式 for 变量 in 列表 if 条件]

# 一种由原列表创建新列表的简洁方法
lst1 = [1, 2, 3, 4, 5]
lst2 = [i*2 for i in lst1 if i % 2 == 0]
print(lst2)

求平均分

def avg(students):
    return sum(x[1] for x in students)/len(students)

students=[['chen',1],['dong',2]]
print(avg(students))

因数求和

def sum(x):
    return sum(i for i in range(1,x+1) if x%i==0)

print(sum(6))
    

嵌套列表的排序

lst=[['chen',2],['dong',1],['xiao',9]]
def f(a):
    return a[1]

lst.sort(key=f)
print(lst)
lst.sort(key=f,reverse=True)
print(lst)

lambda表达式

lst=[['chen',2],['dong',1],['xiao',9]]

lst.sort(key=lambda x:x[1])
print(lst)
lst.sort(key=lambda x:x[1],reverse=True)
print(lst)

元组

元组就是不可变的list

append、extend、del等不可用

创建元组:使用1,2,3或者(1,2,3)

元组交换值

>>> a=1
>>> b=2
>>> a,b=b,a
>>> print(a)
2
>>> print(b)
1
>>> (a,b)=(b,a)
>>> print(a)
1
>>> print(b)
2
>>> 

切分

>>> name,domain='chentianming@163.com'.split('@')
>>> print(name,domain)
chentianming 163.com
>>> 

函数返回多个值时可以用到元组 return a,b

SDU模式,装饰、排序、反装饰

如根据单词的长度对一个单词列表进行排序

def sort_by_length(words):
    # decorate
    t=[]
    for word in words:
        t.append((len(word),word))
    # sort
    t.sort(reverse=True)
    # undecorate
    res=[]
    for length,word in t:
        res.append(word)
    return res

words=['hello','word','helloword']
print(sort_by_length(words))

也可以使用lambda函数

words=['hello','word','helloword']
words.sort(key=lambda x:len(x),reverse=True)
print(words)

字典

key-value

key in dict

for key in dict 枚举 无序的

dict.items()

dict.keys()

dict.values()

dict.clear()

读取一个字符串,计算每个字母出现的个数

str='aasdfhasjkdfhqiuwnaksdlfkjhasdfuhqwkjnfalskdjhfoqiuwhfakljsdbf'
dict={}
for c in str:
    if c in dict:
        dict[c]+=1
    else:
        dict[c]=1
print(dict)

def count(str):
       dict1={i:str.count(i)for i in str}
       print(dict1)
        
count('abcacba')

集合Set

和字典差不多,但是只有key没有value

创建

X=set()

X={KEY1,KEY2}

add

remove

模块 包

异常

try:
    num1=int(input('enter the first number:'))
    num2=int(input('enter the second number:'))
    print(num1/num2)
except ValueError as e:
    print('please input a digit!',e)
except ZeroDivisionError as e:
    print(e)
else:
    print('everythin is ok')

上下文管理器和with语句

with open('data.txt') as f:
	for line in f:
		print(line,end='')
posted @ 2021-12-31 08:54  bagdje  阅读(16)  评论(0)    收藏  举报