Python基础-月考,python基础,1. 8<<2等于?


1. 8<<2等于?

1 # 322 # 解释:将8按位左移2位3 # 8    0 0 0 0  1 0 0 04 # 32  0 0 1 0  0 0 0 0

2. 通过内置函数计算5除以2的余数

1 print(divmod(5, 2))2 3 #(2, 1)  2 = 5 // 2; 1 = 5 % 2

3. s=[1,"h",2,"e",[1,2,3],"l",(4,5),"l",{1:"111"},"o"],将s中的5个字符提取出来并拼接成字符串

1 s = [1, "h", 2, "e", [1, 2, 3], "l", (4, 5), "l", {1: "111"}, "o"]2 s_g = filter(lambda x: type(x) is str, s)   #由于int类型非可迭代对象,先使用filter过滤掉3 s_new = ‘‘  #拼接字符串变量4 for i in s_g:5     s_new += i6 print(s_new)

4. 判断"yuan"是否在[123,(1,"yuan"),{"yuan":"handsome"},"yuanhao"],如何判断以及对应结果?

1 l = [123, (1, "yuan"), {"yuan": "handsome"}, "yuanhao"]2 l_yuan = str(l)     #将列表转换为字符串3 if ‘yuan‘ in l_yuan:4     print(‘True‘)

5.执行结果并解释为什么?

l=[1,2,3]

l2=l.insert(3,"hello")

print(l2)

1 执行结果:None2 解释:‘.insert’方法的返回值为‘None’

6. 计算结果以及为什么?

a=[1,2,[3,"hello"],{"egon":"aigan"}]

b=a[:]

a[0]=5

a[2][0]=666

print(a)

print(b)

 1 a = [1,2,[3,"hello"],{"egon":"aigan"}] 2 b = a[:]    #列表b和列表a相同 3  4 a[0] = 5    #将列表a中的第一个元素‘1’变为‘5’ 5 a[2][0] = 666   #将列表a中的第3个元素‘[3,"hello"]’(同样为列表)的第1个元素变为‘666’ 6  7 print(a)    #打印更改后的列表a 8 print(b)    #打印列表b,就是列表a更改前的元素 9 10 #执行结果:  [5, 2, [666, ‘hello‘], {‘egon‘: ‘aigan‘}]11 #          [1, 2, [666, ‘hello‘], {‘egon‘: ‘aigan‘}]

7. 使用文件读取,找出文件中最长的行的长度(用一行代码解决)?

1 print(max([len(x) for x in open(‘test.py‘, encoding=‘utf-8‘)]))    

8. 分析结果

def add(s, x):

return s + x

def generator():

for i in range(4):

yield i

base = generator()

for n in [1, 11]:

base = (add(i, n) for i in base)

print(list(base))

 1 #结果:[22, 23, 24 ,25] 2 #解释: 3 #这个可以以管道的思路来理解,首先generator()函数是第一个生成器,下一个是第一次循环的base = (add(i, n) for i in base), 4 # 最后一个生成器是第二次循环的base = (add(i, n) for i in base)。 这样就相当于三个管道依次连接,但是水(数据)还没有流过, 5 # 现在到了list(base),就相当于驱动器,打开了水的开关,这时候,按照管道的顺序,由第一个产生一个数据,yield 0, 6 # 然后第一个管道关闭。 之后传递给第二个管道就是第一次循环,此时执行了add(0, 11),然后水继续流, 7 # 到第二次循环,再执行add(11, 11),此时到管道尾巴了,第一个数据22就产生了。此时第一个管道再开放yield 1,  8 # 流程跟上面的一样。依次产生23,24,25; 直到没有数据。 把代码改一下容易理解: 9 10 def generator():11     for i in range(4):12         yield i     #第1个管道13 14 base = (add(i, n) for i in base)    #第2个管道15 base = (add(i, n) for i in base)    #第3个管道16 17 list(base)      #开关驱动器

参考:python迭代器与生成器小结

9.如果用py2,py3下在cmd下运行会报错吗?为什么并提出解决方案? (编码)

test.py (gbk方式保存):

#coding:GBK

print(“老男孩”)

技术分享

扩展,但是在python2.x解释器中,会显式乱码,python3.x下正常显式,是因为解释器自动帮我们解码了文件内容:

技术分享

10. 通过函数化编程实现5的阶乘

 1 def fn(n): 2     x = 1 3     if n == 0:    #0的阶乘为1 4         x 5     else: 6         for i in range(1, n+1): 7             x *= i 8     return x 9 10 print(fn(5))

11. 打印如下图案:

     *

***

*****

*******

*****

***

*

 1 def print_star(n):    #n必须为奇数,此程序没有做判断 2     s = ‘*‘ 3     i = 1   #上部分,包含对称行 4     j = n   #下部分 5     while i < n and i % 2 != 0: 6         print((s * i).center(n)) 7         i += 2 8     while j > 0 and j % 2 != 0: 9         print((s * j).center(n))10         j -= 211 12 print_star(7)

12

def outer():
  count = 10
  def inner():
    count = 20
    print(count)
    return count
  inner()
  print(count)

outer()

(1). 分析运行结果?

1 运行结果:202         103 分析:当调用函数outer时,按顺序读函数定义部分,outer函数内部嵌套定义了inner函数,4 读完inner函数的定义,首先调用了inner(),此时inner函数局部变量count为20,故先打印了20,然后打印了outer函数内部变量10

(2).如何让两个打印都是20

 1 #方法1:将inner函数内部的count变量删除,将outer函数下的count变量赋值为20即可 2 def outer(): 3     count = 20 4     def inner(): 5         print(count) 6         return count 7     inner() 8     print(count) 9 10 outer()

1 #方法2:将inner函数内部变量count = 20返回给外部函数outer的变量count2 def outer():3     def inner():4         count = 205         print(count)6         return count7     count = inner()8     print(count)9 outer()

13. 输入一个年份,判断是否是闰年?

 1 #闰年:四年一润,百年不润,四百年再润 2 def leap_year(y): 3     if y % 100 == 0: 4         if y % 400 == 0: 5             print(‘leap year‘) 6         else: 7             print(‘not leap year‘) 8     elif y % 4 == 0: 9         print(‘leap year‘)10     else:11         print(‘not leap year‘)12 13 leap_year(2000)

14. 任意输入三个数,判断大小?

1 def max_three(x, y, z):2     return max(max(x, y),z)3 4 print(max_three(1,2,3))

15. 求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222,几个数相加以及a的值由键盘控制。

1 def sum_new(a, n):      #a代表求和的数字,n代表相加的次数2     sum = 03     a = str(a)4     for i in range(1, n+1):5         x = int(a * i)6         sum += x7     return sum8 9 print(sum_new(2,3))

16. 请问程序有无bug,怎么解决?

1 f=open("a")2 while 1:3     choice=input("是否显示:[Y/N]:")4     if choice.upper()=="Y":5         for i in f:6             print(i)7     else:8         break
 1 #有bug, 2 # 1,只要用户输入非‘y/Y’字符,程序都会结束,这与提示信息不符合 3 # 2. ‘y/Y’只一次有效,如果用户想再次查看文件内容,必须得重启程序 4 #解决方法: 5 f = open("a") 6 while 1: 7     choice=input("是否显示:[Y/N]:") 8     if choice.upper() == "Y": 9         for i in f:10             print(i)11         f.seek(0)  #重置文件位置于文首12     elif choice.upper() == "N":  #严格要求用户必须输入‘n/N’方可退出程序13         break

17.

1 def foo():2     print(‘hello foo‘)3     return()4 def bar():5     print(‘hello bar‘)

(1). 为这些基础函数加一个装饰器,执行对应函数内容后,将当前时间写入一个文件做一个日志记录。

 1 def timer(func): 2     def wrapper(): 3         import time 4         res = func() 5         f = open(‘log‘, ‘a+‘)   #以追加的方式打开文件,没有则会创建 6         s = time.asctime()      #获取当前时间:Tue Apr 18 21:46:18 2017 7         f.write(s + ‘\n‘)       #将当前时间写入log文件,并换行 8         f.close()               #关闭log文件 9         return res10     return wrapper11 12 @timer13 def foo():14     print(‘hello foo‘)15     return ()16 @timer17 def bar():18     print(‘hello bar‘)19 20 foo()21 22 bar()

(2). 改成参数装饰器,即可以根据调用时传的参数决定是否记录时间,比如@logger(True)

 1 def logger(choice): 2     def timmer(func): 3         def wrapper(): 4             import time 5             if choice == True: 6                 res = func() 7                 f = open(‘log‘, ‘a+‘)   #以追加的方式打开文件,没有则会创建 8                 s = time.asctime()      #获取当前时间:Tue Apr 18 21:46:18 2017 9                 f.write(s + ‘\n‘)       #将当前时间写入log文件,并换行10                 f.close()               #关闭log文件11                 return res12             else:13                 pass14         return wrapper15     return timmer16 17 @logger(True)18 def foo():19     print(‘hello foo‘)20     return ()21 @logger(True)22 def bar():23     print(‘hello bar‘)24 25 foo()26 27 bar()

18. 三次登陆锁定:要求一个用户名密码输入密码错误次数超过三次锁定?

 1 with open(‘account‘,encoding=‘utf8‘) as f_account, open(‘lockedlist‘, ‘a+‘) as f_locked: 2     l = []                  #定义用户名验证列表,存放黑名单数据 3     f_locked.seek(0)        #"a+"模式打开后,文件位置位于末尾,要遍历文件内容,需要将指针移至文件起始位置 4     for locked_info in f_locked.readlines():    #遍历黑名单 5         l.append(locked_info.strip())                   #将黑名单数据添加进列表,注意:需要将文件中的换行符脱掉 6  7     c = []                  #定义用户登录名列表,存储用户尝试的登录名 8     count = 1               #登陆次数计数器 9     flag = True             #登陆循环控制开关10     while flag and count < 4:11         user = input(‘Please input username:‘)      #输入用户名12         pwd = input(‘Please input password:‘)       #输入用户密码13         if user in l:                 #用户名在黑名单中14             print("This user is in blacklist,can‘t log in!")    #打印提示信息15             continue16         c.append(user)17         for info in f_account:                  #用户名不在黑名单中,遍历用户登陆文件18             user_name, user_pwd = info.strip().split(‘,‘)       #将文件中的用户名和登陆密码赋值给判定变量19             if user == user_name:               #用户名符合20                 if pwd == user_pwd:             #对应密码符合21                     print(‘Welcome %s‘ % user)  #打印登陆成功信息22                     flag = False               #登陆成功,跳出登陆程序23                     break24                 count += 1                      #对应密码不符合,while循环计数器加125                 break26             count += 1                          #用户名不符合,while循环计数器加127             break28     if count == 4:                              #如果不同用户名密码输错3次,关闭程序29         print(‘More than 3 times wrong!‘)       #打印提示信息30     if len(c) == 3 and c[0] == c[1] == c[2]:    #如果相同用户名密码输错3次,将该用户名加入黑名单,限制登陆31         print(‘This user has been locked!‘)32         f_locked.write(user+‘\n‘)               #将错误3次的用户名写入黑名单,注意,加换行符

Python基础-月考

评论关闭