python面试题

//函数传递,使用list和dict等传递参数时可以修改对象
a = 1
def fun(a):
    a = 2
fun(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. apple
1. banana
2. 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 = vegetable
apple = 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:pass

Python里面如何生成随机数?
答:random模块
随机整数:random.randint(a,b):返回随机整数x,a<=x<=b
random.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/python
def 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 sChildPath
display_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]# 


posted on 2017-10-25 18:06  标配的小号  阅读(114)  评论(0编辑  收藏  举报

导航