Python学习心得——基础知识(六)

时间:2022-07-08 16:25:20

一、lambda表达式

1、定义

针对简单的函数,用lambda表达式来展现更方便。

2、样例

1 #普通函数
2 def f1(a):
3 return a+1
4 print(f1(7))
5
6 #用lambda表达式来实现
7
8 f2=lambda a: a+1
9 print(f2(7))

 

二、python内置函数

1、常见内置函数表

Python学习心得——基础知识(六)

2、需要熟练掌握的内置函数如下

abs(),all(),any(),bin(),bool(),bytes(),chr(),dict(),dir(),divmod(),enumerate(),eval(),filter(),float(),globals(),help(),hex(),id(),input(),int(),isinstance(),len(),list(),locals(),map(),max(),min(),oct(),open(),ord(),pow(),print(),range(),round(),set(),sorted(),str(),sum(),tuple(),type()

 

三、随机验证码实例

此处引用了老师的随机验证码实例。

 1 #实现六位随机验证码,包括数字与大写字母
2 import random
3 temp = ''
4 for i in range(6):
5 num = random.randrange(0,5) #让出现数字的位置随机
6 if num == 1 or num == 3:
7 rad1 = random.randrange(0,10)
8 temp = temp + str(rad1)
9 else:
10 rad2 = random.randrange(65,91)
11 temp = temp + chr(rad2)
12 print(temp)

 

四、内置函数的排序方法

1、方式一

1 #sort()排序,对象的元素必须是同类型
2
3 li=[10,8,5,28,9,6]
4 li.sort()
5 print(li)

 

 

 

五、文件操作

1、打开文件

文件句柄=open('文件路径','模式')

 

2、打开文件模式

模式 描述
r 只读模式【默认】
r+ 读写【可读,可写】
rb 以二进制格式读取,文件指针放在文件开头
rb+ 以二进制读取和写入方式打开文件
w 只写模式【不可读;不存在则创建;存在则清空内容;】
w+ 写读【可读,可写】
wb 打开文件以二进制方式写入,文件存在则覆盖,不存在则创建新文件
wb+ 以二进制方式写入和读取文件,存在则覆盖现有文件,不存在则创建新文件
x 只写模式【不可读;不存在则创建,存在则报错】
x+ 写读【可读,可写】
a 追加模式【不可读;   不存在则创建;存在则只追加内容;】
a+ 写读【可读,可写】
ab 以二进制格式追加在文件末尾,不存在则创建该文件

 

3、常见操作方法

Python学习心得——基础知识(六)Python学习心得——基础知识(六)
  1 class TextIOWrapper(_TextIOBase):
2 """
3 Character and line based layer over a BufferedIOBase object, buffer.
4
5 encoding gives the name of the encoding that the stream will be
6 decoded or encoded with. It defaults to locale.getpreferredencoding(False).
7
8 errors determines the strictness of encoding and decoding (see
9 help(codecs.Codec) or the documentation for codecs.register) and
10 defaults to "strict".
11
12 newline controls how line endings are handled. It can be None, '',
13 '\n', '\r', and '\r\n'. It works as follows:
14
15 * On input, if newline is None, universal newlines mode is
16 enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
17 these are translated into '\n' before being returned to the
18 caller. If it is '', universal newline mode is enabled, but line
19 endings are returned to the caller untranslated. If it has any of
20 the other legal values, input lines are only terminated by the given
21 string, and the line ending is returned to the caller untranslated.
22
23 * On output, if newline is None, any '\n' characters written are
24 translated to the system default line separator, os.linesep. If
25 newline is '' or '\n', no translation takes place. If newline is any
26 of the other legal values, any '\n' characters written are translated
27 to the given string.
28
29 If line_buffering is True, a call to flush is implied when a call to
30 write contains a newline character.
31 """
32 def close(self, *args, **kwargs): # real signature unknown
33 关闭文件
34 pass
35
36 def fileno(self, *args, **kwargs): # real signature unknown
37 文件描述符
38 pass
39
40 def flush(self, *args, **kwargs): # real signature unknown
41 刷新文件内部缓冲区
42 pass
43
44 def isatty(self, *args, **kwargs): # real signature unknown
45 判断文件是否是同意tty设备
46 pass
47
48 def read(self, *args, **kwargs): # real signature unknown
49 读取指定字节数据
50 pass
51
52 def readable(self, *args, **kwargs): # real signature unknown
53 是否可读
54 pass
55
56 def readline(self, *args, **kwargs): # real signature unknown
57 仅读取一行数据
58 pass
59
60 def seek(self, *args, **kwargs): # real signature unknown
61 指定文件中指针位置
62 pass
63
64 def seekable(self, *args, **kwargs): # real signature unknown
65 指针是否可操作
66 pass
67
68 def tell(self, *args, **kwargs): # real signature unknown
69 获取指针位置
70 pass
71
72 def truncate(self, *args, **kwargs): # real signature unknown
73 截断数据,仅保留指定之前数据
74 pass
75
76 def writable(self, *args, **kwargs): # real signature unknown
77 是否可写
78 pass
79
80 def write(self, *args, **kwargs): # real signature unknown
81 写内容
82 pass
83
84 def __getstate__(self, *args, **kwargs): # real signature unknown
85 pass
86
87 def __init__(self, *args, **kwargs): # real signature unknown
88 pass
89
90 @staticmethod # known case of __new__
91 def __new__(*args, **kwargs): # real signature unknown
92 """ Create and return a new object. See help(type) for accurate signature. """
93 pass
94
95 def __next__(self, *args, **kwargs): # real signature unknown
96 """ Implement next(self). """
97 pass
98
99 def __repr__(self, *args, **kwargs): # real signature unknown
100 """ Return repr(self). """
101 pass
102
103 buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
104
105 closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
106
107 encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
108
109 errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
110
111 line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
112
113 name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
114
115 newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
116
117 _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
118
119 _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
120
121 3.x
3.0

4、写文件样例

1 f1=open('jishiben.txt','w+')
2 f1.write('hello\n')
3 f1.close()

#还有个writelines()方法,写入的是一个LIST类型参数

5、读文件样例

f2=open('jishiben.txt','r')
print(f2.read())

#还有个readlines()方法,读得是一个list内容

 

六、用户登录验证样例

 
 
#!usr/bin/env python
# -*- coding: utf-8 -*-

'''
作业要求

结合文件实现
#实现用户登录
#实现用户注册
#判断用户存在性
#实现删除用户
#实现修改密码

'''

#用户选择操作类型
def f1(args):
"""
用于实现调用各种操作类型的函数
:param args: 操作类型序号
:return: 若调用成功,返回True,否则返回False
"""
if args==1:
name=input('请您输入用户名:')
pwd=input('请您输入密码:')
result=f2(name,pwd)
if result:
print('登录成功!')
else:
print('登录失败,用户名或密码错误!')
if args==2:
name=input('请您输入注册的用户名:')
pwd=input('请您输入注册密码:')
is2_f4=f4(name)
if is2_f4:
print('用户名已存在,无法注册!')
else:
result2=f3(name,pwd)
if result2:
print('用户注册成功!')
else:
print('用户注册失败!')
if args==3:
name=input('请您输入要修改密码的用户名:')
is3_f4=f4(name)
if is3_f4:
pwd=input('请您输入新密码:')
is3_f5=f5(name,pwd)
if is3_f5:
print('密码修改成功!')
else:
print('密码修改失败!')
else:
print('您输入的用户名不存在!')
if args==4:
name=input('请您输入要删除的用户名:')
is4_f4=f4(name)
if is4_f4:
is4_f6=f6(name)
if is4_f6:
print('成功删除用户!')
else:
print('删除用户失败!')
else:
print('您输入的用户名不存在!')


#用户登录
def f2(name,pwd):
"""
用于验证用户登录
:param name: 登录的用户名
:param pwd: 登录的用户名密码
:return: 如果用户名与密码正确,返回True,否则返回False
"""
with open('login.txt','r',encoding='utf-8') as f:
for line in f:
line=line.strip()
line_list=line.split('@')
if name==line_list[0] and pwd==line_list[1]:
return True
return False

#用户注册
def f3(name,pwd):
with open('login.txt','a',encoding='utf-8') as f:
temp='\n'+name+'@'+pwd
f.write(temp)
return True

#用户存在性
def f4(name):
'''
验证用户名是否在文件中已存在
:param name: 输入的用户名
:return: 若输入的用户名在文件中已存在,返回True,否则返回False
'''
with open('login.txt','r',encoding='utf-8') as f:
for line in f:
line=line.strip()
line_list=line.split('@')
if name==line_list[0]:
return True
return False

#修改密码
def f5(name,pwd):
'''
实现修改密码功能,读取原文件login的内容,替换成新密码,然后重新写入到文件login
:param name: 需要修改密码的用户名
:param pwd: 新密码
:return: 修改成功,返回True ,修改失败,返回False
'''
s=[]
with open('login.txt','r+',encoding='utf-8') as f:
for line in f:
line=line.strip()
line_list=line.split('@')
if name==line_list[0]:
temp=name+'@'+pwd
s.append(temp)
else:
s.append(line)
f.seek(0)
for i in s:
f.write(i+'\n')
return True



#删除用户
def f6(name):
'''
实现删除用户功能,读取原文件login的内容,过滤掉删除用户,然后重新写入到文件login
:param name: 要删除的用户名
:return: 删除成功,返回True;删除失败,返回False
'''
m=[]
with open('login.txt','r+',encoding='utf-8') as f:
for line in f:
line=line.strip()
line_list=line.split('@')
if name==line_list[0]:
continue
else:
m.append(line)
f.seek(0)
for i in m:
f.write(i+'\n')
return True

print('用户登录请输入 1\n用户注册请输入 2\n修改用户密码请输入 3\n删除用户请输入 4')
a=int(input('请您输入操作内容: '))
result=f1(a)