一、python的集合

集合具有天生去重和无序的特性,也由于无序,所以集合无法通过下标取值

新建一个集合的方法是:

  s = set()   #空集合

  s2 = {'1','2','3'}

添加元素的方法为:

  s.add('1')

删除元素的方法为:

  s.remove('1')

  s.pop()    #随机删除一个值

  

s1 = {1,2,3}

s2 = {3,4,5}

交集:

s2.intersection(s2)

s2 & s1

并集:

s2.union(s1)

s2 | s1

差集(取s2里不同于s1的值):

s2.difference(s1)

s3 - s2

 

二、python的递归

递归,也就是自己调用自己,最多能递归999次

count = 0
def test1():
   num = int(input('please enter a number:'))
   global count
   count+=1
   num = 8
   if num % 2 == 0:  # 判断输入的数字是不是偶数
      pass
   print(count)
   else:
    return test1()  # 如果不是偶数的话继续调用自己,输入值
print(test1())  # 调用test
三、python函数
函数就是吧一堆代码组合到一起,变成一个整体,将需多次重复的步骤整合成一个函数,可简洁代码,也可提高代码的复用性
需要注意,函数不调用就不会被执行
函数中有全局变量和局部变量的区别,若函数内有局部变量,则定义变量需在调用变量前进行
def hello(file_name,content=''): #形参,形式参数
   #函数里面的变量都是局部变量
   f = open(file_name, 'a+',encoding='utf-8')
   if content:
      f.write(content)
      res = ''
   else:
      f.seek(0)
      res = f.read()
   f.close()
   return res
name = hello('aa.txt','kk')  #调用    #这里的aa.txt,hhhh是实参
print(name)
上面file_name属于位置参数,必填,而content由于已经设置了默认值,非必填
函数不是必须有返回值,如果函数无返回值则返回值为None
函数中的return相当于循环里的break,如果在函数中运行到return,则函数直接结束
除了位置参数,也存在可变参数,下面的args中形成的是元组
def test(a,b=1,*args):
   print(a)
   print(b)
   print(args)

test('hh',2,'kk','ss','ll')
test(a=5,b=10)
t = [1,2,3,4,5]
test(*t)

关键字参数是字典形式
def test2(a,**kwargs):
   print(a)
   print(kwargs)
test2(a=1,name='hhh',sex='female')
函数里面的变量都是局部变量,若要修改全局变量,则在函数内变量前面需添加global

此处定义一个检验一个字符串是否为合法的小数的函数
1、小数点的个数为1   2、按照小数点分割
def check_float(s):
   s = str(s)
   print(s)
   if s.count('.')==1:
      s_list = s.split('.')
      #1.2 [1.2]
      left = s_list[0]
      right = s_list[1]
      if left.isdigit() and right.isdigit():
         return True
      elif left.startswith('-') and left.count('-')==1 :
         if left.split('-')[-1].isdigit() and right.isdigit():
            return True
   return False
print(check_float('+5.0'))

四、python模块
python的模块共分为三种,
1、标准模块
  也就是python自带的,不需自己安装
2、第三方模块
  需要安装,是别人提供的
使用pip install xxx可自动安装模块
手动安装步骤:
   # 首先下载安装包
   # 解压
   # 在命令行里面进入到这个解压之后的目录
   # 执行python setup.py install

3、自己写的python文件
  使用时若不在当前py文件的目录下则要添加环境变量
import xx来导入一个文件,导入文件的实质就是把这个文件运行一遍