python基础语法三

Posted on 2018-11-04 19:40  郑幸福  阅读(195)  评论(0编辑  收藏  举报

集合:

1.不同元素组成
 2.无序
 3.集合中的元素必须是不可变类型
 s = {1, 2, 3 }
 #定义集合

s = set('hello') 
print(s)
    
s.pop()
#指定删除
s.remove("")
s.remove("sss") #删除元素不存在会报错
s.discard('sbb') #删除元素不存在,,不会报错

print(s)
View Code

集合的运算关系:

python_1 = ['lcg', "szw", "zjw"]
linux_1 = ["lcg", "szw"]

  #取公共部分

    python_and_linux_1 = []
	for p_name in python_1:
		if p_name in linux_1:
			python_and_linux_1.append(p_name)
			
	print(python_and_linux_1)
	

	p_s = set(python_1)
	l_s = set(linux_1)
	
	
	#取交集的部分
	print(p_s.intersection(l_s))
	print(p_s&l_s)
	
	
	# 去并集的部分
	print(p_s.union(l_s))
	print(p_s|l_s)
	
	
	#差集
	print(p_s-l_s)
	print(p_s.difference(l_s))
	
	
	#字符串格式化
	
	msg = "i am hobby is alex", %"lhf"
	msg = "i am hobby is %s ", %("lhf", "alex") \

  函数:

 

python中函数的定义方法

def test(x):
    "The function definitiens"
    x+=1
    return x
def : 定义函数的内容
test : 函数名
() : 内可定义形参
"":文档描述
x+=1: 泛指代码块或程序逻辑
return : 定义返回值
调用运行: 可以带参数,也可以不带参数
函数名()
 
 
 
函数参数:
#改成用函数写
def calc(x, y): # x, y, 形参
    res = x**y
    return res

c = calc(a, b)# a, b 实参
print(c)

默认参数:

def handle(x, type = "mysql"):
    print(x)
    print(type)
handle('hello' , type='sqlite')
#参数组 : **字典 , *列表
def test(x, *args)
 print(x)
 print(args)
 print(args[2])
test(1,2,3,4,5,6)
test(1, {"name":"alex})




def test(x, **kwargs):
 print(x)
 print(kwargs)
 
test(1, y=2, y=3)


def test(x, *args, **kw   args):
 print(x)
 print(args)
 print(kwargs)

局部变量,和全局变量

name  = lhf # 全局变量

def chang():
    name = lhf #局部变量
    print(name)


def chang():
    global name = lhf #全局变量
    print(name)
    
    
函数就是变量!!!

函数递归

def calc(n):
        print(n)
        calc(n)
    
    calc(10)
    
    #自己调用自己!
    
    
    def calc(n):
        print(n)
        if int(n/2)==0
            return n
        return calc(int(n/2))
        
    calc(10)
    
    
person_list = ['alex', 'wupeiqi', 'yuanhao', 'linhaifeng', 'zsc']
def ask_way(person_list):
    if len(person_list) == 0:
        return '根本没人知道'
    person = person_list.pop(0)#取出一个值。
    if person == 'linhaifeng':
        return '%说: 我知道,老男孩就在沙河汇德商厦下地铁就是' %person
    ask_way(person_list)
    
    
ask_way(person_list)
View Code

递归特性:
 1.必须有一个明确的结束条件
 2.每次进入更深一层的递归时,问题规模相比上一次递归都应有减少
 3.递归效率不高, 递归层次会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入
 一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧,由于栈的大小不是无限的,所以,递归调用次
 数过多会导致栈溢出)