python 基础习题
1、8<<2等于?
8 ---> 1000 32 ---> 100000 -----------结果--- 32
2、通过内置函数计算5除以2的余数
print(dir()) #不带参数时,返回当前范围内的变量、方法和定义的类型列表,#找到__builtins__ print(dir(__builtins__)) #找内置函数 print(divmod(5,2)[1]) ----------------------结果----------- 1
3、s=[1,"h",2,"e",[1,2,3],"l",(4,5),"l",{1:"111"},"o"],将s中的5个字符提取出来并拼接成字符串。
方法一: s1 = [] for n in s: if type(n) == str: s1.append(n) print("".join(s1)) 方法二: print("".join([i for i in s if type(i) == str]))
4、判断"yuan"是否在[123,(1,"yuan"),{"yuan":"handsome"},"yuanhao"],如何判断以及对应结果?
s1 = [123,(1,"yuan"),{"yuan":"handsome"},"yuanhao"] def foo(name): if "yuan" in name: print(name) for i in name: if type(i) == list or type(i) == tuple: foo(i) if type(i) == dict: foo(i.keys()) foo(i.values()) foo(s1) -----------结果为--------- (1, 'yuan') dict_keys(['yuan'])
6、 a=[1,2,[3,"hello"],{"egon":"aigan"}]
b=a[:]
a[0]=5
a[2][0]=666
print(a)
print(b)
#计算结果以及为什么?
[5, 2, [666, 'hello'], {'egon': 'aigan'}] [1, 2, [666, 'hello'], {'egon': 'aigan'}] b相当于a的浅拷贝,当拷贝a中[3,"hello"]相当于只拷贝了一个内存地址,当劣列表里的元素改变时,b指向的内存地址并未发生改变,所以列表元素跟着一起改变
7 使用文件读取,找出文件中最长的行的长度(用一行代码解决)?
print(max([len(line) for line in open('file')]))
10 .通过函数化编程实现5的阶乘
方式一: def func(n): if n == 1: return 1 else: return n * func(n-1) obj = func(3) print(obj) 方式二: from functools import reduce def func(number): obj = reduce(lambda x,y:x*y,range(1,number + 1)) return obj print(func(4))
11 打印如下图案:
* *** ***** ******* ***** *** * def func(number): for i in range(1,number,2): print(("*" * i).center(number)) for i in range(number,0,-2): print(("*" * i).center(number)) func(7)
12.
def outer(): count = 10 def inner(): nonlocal count #nonlocal 作用于外部作用域 count = 20 print(count) inner() print(count) outer() 1.分析运行结果? 20 10 2.如何让两个打印都是20 def outer(): count = 10 def inner(): nonlocal count #nonlocal 作用于外部作用域 count = 20 print(count) inner() print(count) outer()
13 输入一个年份,判断是否是闰年?
def func(year): if (year%4 == 0 and year%100 != 0) or year%400 == 0: return True else: return False print(func(2005)) judge = lambda year: True if (year%4 == 0 and year%100 != 0) or (year%400 == 0) else False print(judge(2004))
14 任意输入三个数,判断大小?
def func(a,b,c): if a >b: if a >c: print("%s最大"% a) else: print("%s最大" % c) else: if b >c: print("%s最大" % b) else: print("%s最大" % c) func(1,2,3)
15 求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222,几个数相加以及a的值由键盘控制。
def func(number,count): ret = 0 if int(count) > 1: for i in range(1,int(count) + 1 ): ret += int((str(number) * i)) return ret else: return number obj = func(2,3) print(obj)
16.
f=open("a") while 1: choice=input("是否显示:[Y/N]:") if choice.upper()=="Y": for i in f: print(i) else: break 请问程序有无bug,怎么解决? --------------------------------结果--------------- f=open("a") while 1: choice=input("是否显示:[Y/N]:") if choice.upper()=="Y": for i in f: print(i) f.seek(0) else: break f.close("a")
17
def foo():
print('hello foo')
return()
def bar():
print('hello bar')
(1)为这些基础函数加一个装饰器,执行对应函数内容后,将当前时间写入一个文件做一个日志记录。
(2)改成参数装饰器,即可以根据调用时传的参数决定是否记录时间,比如@logger(True)
import time def init(func): def wrapper(*args,**kwargs): a= str(time.time()) + "执行%s\n" % func with open("record.txt","a+") as f: f.write(a) func(*args,**kwargs) return wrapper @init def foo(): print('hello foo') return() @init def bar(): print('hello bar') foo() bar() import time def auth(flag): def init(func): def wrapper(*args,**kwargs): if flag == True: a= str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "执行%s\n" % func with open("record.txt","a+") as f: f.write(a) func(*args,**kwargs) return wrapper return init @auth(True) def foo(): print('hello foo') return() @auth(True) def bar(): print('hello bar') foo() bar()
18.
list3 = [ {"name": "alex", "hobby": "抽烟"}, {"name": "alex", "hobby": "喝酒"}, {"name": "alex", "hobby": "烫头"}, {"name": "alex", "hobby": "Massage"}, {"name": "wusir", "hobby": "喊麦"}, {"name": "wusir", "hobby": "街舞"},] a = [ {"name":"alex","hobby":[1,2,3,4]}, {"name":"wusir","hobby":[1,2,3,4]} ]
19 三次登陆锁定:要求一个用户名密码输入密码错误次数超过三次锁定?
accounts = {} def lock_user(name): with open("lock_user", mode="r+", encoding="utf8") as f_lock: for line in f_lock: if line.strip().split()[0] == name: print("Lock user") exit() def lockd_user(**kwargs): with open("lock_user",mode="a+",encoding="utf8") as f_lockd_user: for key in kwargs: if kwargs[key] >2: f_lockd_user.write(key + "\n") def check_user(name,passwd): with open("user",mode="r",encoding="utf8") as f_check: for line in f_check: if name == line.strip().split()[0]: if passwd == line.strip().split()[1]: print("Success") exit() else: add_error(name) return name return name def add_error(name): if accounts: if name in accounts: accounts[name] += 1 else: accounts[name] = 1 else: accounts[name] = 1 def main(): count = 0 while True: name = input("input name: ") passwd = input("input passwd: ") lock_user(name) #判断用户是否锁定 name = check_user(name,passwd) #判断用户 count += 1 if count > 2: lockd_user(**accounts) print("exit than three") break if __name__ == '__main__': main()