python面试题

来源:互联网 发布:程序员mac 编辑:程序博客网 时间:2024/06/05 15:07
//函数传递,使用list和dict等传递参数时可以修改对象a = 1def fun(a):    a = 2fun(a)print a  # 1//区分a = []def fun(a):    a.append(1)fun(a)print a  # [1]当你不确定你的函数里将要传递多少参数时你可以用*args>>> def print_everything(*args):        for count, thing in enumerate(args):...         print '{0}. {1}'.format(count, thing)...>>> print_everything('apple', 'banana', 'cabbage')0. apple1. banana2. cabbage相似的,**kwargs允许你使用没有事先定义的参数名:>>> def table_things(**kwargs):...     for name, value in kwargs.items():...         print '{0} = {1}'.format(name, value)...>>> table_things(apple = 'fruit', cabbage = 'vegetable')cabbage = vegetableapple = fruit>>> def print_three_things(a, b, c):...     print 'a = {0}, b = {1}, c = {2}'.format(a,b,c)...>>> mylist = ['aardvark', 'baboon', 'cat']>>> print_three_things(*mylist)a = aardvark, b = baboon, c = cat什么是lambda函数?它有什么好处?答:lambda 表达式,通常是在需要一个函数,但是又不想费神去命名一个函数的场合下使用,也就是指匿名函数Python里面如何实现tuple和list的转换?答:直接使用tuple和list函数就行了,type()可以判断对象的类型Python中pass语句的作用是什么?答:pass语句不会执行任何操作,一般作为占位符或者创建占位程序,whileFalse:passPython里面如何生成随机数?答:random模块随机整数:random.randint(a,b):返回随机整数x,a<=x<=brandom.randrange(start,stop,[,step]):返回一个范围在(start,stop,step)之间的随机整数,不包括结束值。随机实数:random.random( ):返回01之间的浮点数random.uniform(a,b):返回指定范围内的浮点数。如何在一个function里面设置一个全局的变量?答:解决方法是在function的开始插入一个global声明:def f()global x单引号,双引号,三引号的区别答:单引号和双引号是等效的,如果要换行,需要符号(\),三引号则可以直接换行,并且可以包含注释如果要表示Let’s Go 这个字符串单引号:s4 = ‘Let\’s go’双引号:s5 = “Let’s go”s6 = ‘I realy like“python”!’这就是单引号和双引号都可以表示字符串的原因了//列出文件夹下的文件[root@bogon python]# rm h.py rm: remove regular file ‘h.py’? y[root@bogon python]# cat dircontent.py #!/usr/bin/pythondef display_dircontent(sPath):    import os    for sChild in os.listdir(sPath):        sChildPath=os.path.join(sPath,sChild)        if os.path.isdir(sChildPath):            display_dircontent(sChildPath)        else:            print sChildPathdisplay_dircontent('/root/python')运行效果[root@bogon python]# ./dircontent.py /root/python/client.py/root/python/server.py/root/python/a.py/root/python/email.py/root/python/email.pyc/root/python/test.py/root/python/b.py/root/python/c.py/root/python/d.py/root/python/what.py/root/python/dircontent.py[root@bogon python]# 
原创粉丝点击