• python基础篇-day1


                             python基础篇                           

    python是由C语言写的;

    pass 占位符;

    del,python中全局的功能,删除内存中的数据;

    变量赋值的方法:

    user,pass = 'freddy','freddy123'    【变量名全是大写,表示是一个全量,最好不要更改;】

    for循环语法小技巧:

    for i in range(10):
            if i >=3:break   【在程序比较小的时候,可以使用次方法】
         print(i

    查看数据类型:

    【tyep(),】
    >>> r=(1,2,3,4,5) >>> type(r) <class 'tuple'>

    python格式化输出:

    %d  整数

    %f  浮点数

    %s  字符串

    %x  十六进制整数


    name = input("you input name:") age = int(input("you input age:")) job = input("you input job:") msg = """ Infomation is %s ------------ name = %s age = %d job = %s ----END----- """ %(name,name,age,job) print(msg)

    使输入的密码不可见,在pycharm中不好使:

    【getpass.getpass,】
    import getpass username
    = input("username:") password = getpass.getpass("password:") print(username,password)

    python和linux交互:

    >>> import os
    >>> os.system("dir")
    os.mkdir
    
    【python和linux交互变量赋值方法:把输出的结果赋值给变量名cmd_res,先用popen把结果保存到内存中,然后再用read读出来:】
    cmd_res
    = os.popen("df -h").read()
    print (
    "cmd_res")

    【python,寻找python执行脚本文件路径:】
    >>> import sys
    >>> print (sys.path)

    判断用户输入的账号密码是否正确:

    【方法一:】
    user="freddy"
    password="123"
    username = input("you input user:")
    userpass = input("you input password:")
    if username == user:
      print("user ok.")
      if userpass == password:
        print("passwd ok.")
      else:
        print("pass error")
    else:
      print("error error.....")
    
    【方法二:】
    if user == username and password == userpass:
      print("Wecomto Login.")
    else:
      print("User Or Password error.")

    for循环,猜年龄小程序:

    【条件:
    1.用户一共有十次机会;
    2.猜三次以后问用户是否要继续;
    3.如果猜对了,直接退出。】
    
    count = 0
    for i in range(10):
        if count < 3:
            age = 18
            freddyAge=int(input("You Input Age:"))
            count +=1
            if  freddyAge == age:
                print("ok")
                break
            elif    freddyAge  < age:
                print("tai di le.")
            else:
                print("tai gao le")
        else:
            retry=input("Input you (y/n)")
            if retry == 'y':
                count = 0
            else:
                exit()

    【方法二:】
    count = 0
    age = 18
    for i in range(10):
    if count < 3:
    freddy = input("age:")
    count +=1
    if freddy.isdigit():
    freddy = int(freddy)
    if freddy == age:
    print("ok")
    break
    elif freddy > age:
    print('tai gao le.')
    else:
    print("tai di le")
    else:
    print("Ivalid data tyep.")
    else:
    retry=input("(y/n)")
    if retry == 'y':
    count = 0
    else:
    exit('bye bye....')
     

    海枯石烂while循环:

    count=0
    while True:
    count +=1
    if count >50 and count<60:
    continue
        else:
    print("count:%d"%count)
    if count == 100:
    break

    【方法二:】
    count = 0
    while True:
    count +=1
    if count == 100:
    break
    if count > 50 and count <90:
    continue
    print('cout:%s'%(count))
     

    列表操作: 

    【列表赋值:】
    >>> name=["freddy",'tang','21','88']
    
    【取tang字符,取的是下标,下标从0开始:】
    >>> name[1]
    'tang'
    
    【取88数字:】
    >>> name[-1]
    '88'
    
    【顾首不顾尾:】
    >>> name=["freddy",'tang','21','88']
    >>> name[0:2]
    ['freddy', 'tang']
    
    【取后三个值,取几个就输入 - 几:】
    >>> name[-3:]
    ['tang', '21', '88']
    
    【多次取列表里面的数据:】
    >>> name=["freddy",'tang','21','88',234,234,324,32,4]
    >>> name[-6:]
    ['88', 234, 234, 324, 32, 4]
    >>> name[-6:][2:4]
    [234, 324]
    >>> name[-6:][2:4][0]
    234
    
    【给列表中234,改成freddie:】
    >>> name=["freddy",'tang','21','88',234,234,324,32,4]
    >>> name[4]='freddie'
    结果:
    >>> name
    ['freddy', 'tang', '21', '88', 'freddie', 234, 324, 32, 4]
    
    【insert,给列表插入值[在”tang“后面插入"sheng"]】
    >>> name
    ['freddy', 'tang', '21', '88', 'freddie', 234, 324, 32, 4]
    >>> name.insert(2,'sheng')
    >>> name
    ['freddy', 'tang', 'sheng', '21', '88', 'freddie', 234, 324, 32, 4]
    
    【append,在列表末尾追加一个值:】
    ['freddy', 'tang', 'sheng', '21', '88', 'freddie', 234, 324, 32, 4]
    >>> name.append('tail')
    >>> name
    ['freddy', 'tang', 'sheng', '21', '88', 'freddie', 234, 324, 32, 4, 'tail']
    
    【remove,删除列表中指定的值:】
    >>> name
    ['freddy', 'tang', 'sheng', '21', '88', 'freddie', 234, 324, 32, 4, 'tail']
    >>> name.remove("freddy")
    >>> name
    ['tang', 'sheng', '21', '88', 'freddie', 234, 324, 32, 4, 'tail']
    
    【删除下标5~9,也是顾首不顾尾】
    >>> name
    ['GroupLong-tang', 'sheng', 'freddie', 'wei', '23', 234, 54, 234, 123, 523]
    >>> del name[5:9]
    >>> name
    ['GroupLong-tang', 'sheng', 'freddie', 'wei', '23', 523]
    >>>pop,删除列表中的值,是根据下标来删除的:】
    name=['GroupLong-tang', 'sheng', 'freddie', 'wei',23, 523,23,43,23,435]
    name.pop(0)
    print(name)
    
    【以布长为2,打印列表:】
    >>> name
    ['GroupLong-tang', 'sheng', 'freddie', 'wei', '23', 523]
    >>> name[::2]
    ['GroupLong-tang', 'freddie', '23']
    >>>
    
    【count,统计列表中23元素的个数(注意:如果列表中,23被‘单引号’括起来,就不能被count所计算):】
    name=['GroupLong-tang', 'sheng', 'freddie', 'wei', 23, 523,23,43,23,435]
    if 23 in name:
        list_count=name.count(23)
    print("---%s--- 23 is/are in name" %list_count)
    
    【把name列表中的所有23元素,全部替换成99999999:】
    name=['GroupLong-tang', 'sheng', 'freddie', 'wei', 23, 523,23,43,23,435]
    for i in range(name.count(23)):
        list_index=name.index(23)
    name[list_index]=9999999999
    print(name)
    
    【extend,扩展列表:】
    name=['GroupLong-tang', 'sheng', 'freddie', 'wei', 23, 523,23,43,23,435]
    name2=[1,2,3,4,5]
    name.extend(name2)
    print(name)
    
    【reverse,反转显示列表内容:】
    name=['GroupLong-tang', 'sheng', 'freddie', 'wei', 23, 523,23,43,23,435]
    name.reverse()
    print(name)
    
    【sort,列表排序(注意:字符串和数字不能混排):】
    name=['GroupLong-tang', 'sheng', 'freddie', 'wei']
    name.sort()
    print(name)
    
    name=[ 23, 523,23,43,23,435]
    name.sort()
    print(name)
    
    【copy列表:】
    name=['GroupLong-tang', 'sheng', 'freddie', 'wei',23, 523,23,43,23,435]
    name1=name.copy()
    name[0]='TANG'
    print(name)
    print(name1)
    
    【浅copy,二级列表的内容不会被重新copy:】
    name=['tang', 'sheng', 'freddie', 'wei',[23, 523,23],43,23,435]
    name1=name.copy()
    
    name[0]='TANG'
    name[4][1]=11111111
    name1[4][2]=22222222
    
    print(name)
    print(name1)
    
    【deepcopy,深浅copy】
    import copy
    name=['tang', 'sheng', 'freddie', 'wei',[23, 523,23],43,23,435]
    #浅copy,不会copy二级列表里面的元素;
    name1=name.copy()
    # name1=copy.copy(name)
    #深copy,不管有几级,都会copy过去;
    name2=copy.deepcopy(name)
    
    #和原文件不一样;
    name[0]='TANG'
    name[4][1]=11111111
    name1[4][2]=22222222
    name2[4][0]=33333333
    
    print(name)
    print(name1)
    print(name2)
    结果:
    ['TANG', 'sheng', 'freddie', 'wei', [23, 11111111, 22222222], 43, 23, 435]
    ['tang', 'sheng', 'freddie', 'wei', [23, 11111111, 22222222], 43, 23, 435]
    ['tang', 'sheng', 'freddie', 'wei', [33333333, 523, 23], 43, 23, 435]

    【【删除一个列表中所有freddy】】
    >>> name = ['freddy','aaa','ccc','freddy','ddd'] >>> for i in range(name.count('freddy')): ... print(name.remove('freddy')) ... None None >>> name ['aaa', 'ccc', 'ddd'] >>>

    【列表中匹配值的方法】
    >>> name ['1', '2', 'aa', 2, 8] >>> "aa" in name True >>> 2 in name True >>> if "aa" in name: ... print("aaa") ... aaa >>>

    判读列表中有没有haha这个值
    name = ['freddy','aaa','ccc','freddy','ddd'] if 'haha' not in name: print("name list not haha")
    判读“t”是不是一个列表
    >>> type(t) is list True

    元组

    【元组的元素不可修改】

    【元组元素的元素可以修改】

    count,index 【只有两个方法】

    【统计这个元组中有几个88】
    name = (22,88,33,55,33,88)
    result = name.count(88)
    print(result)

    【查找元组中88的第一个索引值】
    name = (22,88,33,55,33,88)
    result = name.index(88)
    print(result)

    【判断元组中是否包含88这个数字】
    name = (22,88,33,55,33,88)
    result = name.__contains__(88)
    print(result)

     字符串操作:

    
    
     name.strip()  【去除两边的空格】
     name.lstrip()  【去除左边的空格】
     name.rstrip()  【去除右边的空格】

    【strip,脱掉空格】 username
    = input("user:") if username.strip() == 'freddy': print("welcome.") 【split,字符串拼接】 name='tang,sheng,wei' name2=name.split(",") print(name2) name='tang,sheng,wei' name2=name.split(",") print("|".join(name2)) 【判断是否有空格:】 name="Freddy Tang" print(' ' in name) 【format,格式化输出】 msg="hello:{name} the is age:{age}" msg2=msg.format(name='freddy',age=23) print(msg2) msg="hello:{0} the is age:{1}" msg2=msg.format('Freddy',23) print(msg2) 【center,给字符串居中增加指定字符:】 name='freddy tang' print(name.center(30,'-')) 【find,查找指定字符所在的下标位置,find找不到时返回“-1”;index找不到时会“报错”】 name='freddy tang' print(name.find('e'))
    print(name.index('3')) 【isdigit (判断是否为数字):】 age
    =input("you num:") if age.isdigit(): age = int(age) print(age) else: print("Iivalid data type.")
    【判读是否只是字母】
    name = 'freddy123'
    result = name.isalpha()
    print(result)
    【 检测是否为空】
    name = 'freddy'
    result = name.isspace()
    print(result)

    【sialnum (判断是否为数字或字母,或数字加字母的类型):】 name
    ="123tang" print(name.isalnum()) 【endswith && startswith (判断是否为1开始3结束)】 name="123" print(name.endswith('3')) print(name.startswith('1'))
    endswith ,在 0,4 这个范围内查找是不是以 y 结尾】
    【查找范围规则:大于等于0 and 小于3】
    name = 'freddy'
    result = name.endswith('y',0,4)
    print(result)
    【upper && lower (字符,大小写转换)】 
    name
    ="tang123"
    name2
    ="FREDDY"
    print(name.upper())
    print(name.lower())
    capitalize,把首字母转换成大写】
    name = 'freddy hahahahah'
    result = name.capitalize()
    print(result)
    
    【casefold,把首字母的大写转换成小写】
    name= 'Freddy'
    result = name.casefold()
    print(result)
    count,查找d出现的次数】
    name = 'freddy'
    result = name.count('d')
    print(result)
    
    【count,在0~4范围内,查找d出现的次数】
    name = 'freddy'
    result = name.count('d',0,4)
    print(result)
    
    【encode,把“唐胜伟”转换成gbk编码】
    name = '唐胜伟'
    result = name.encode('gbk')
    print(result)
    【partition,以“is”为标志位,把字符串分割】
    name = 'freddyissb'
    result = name.partition('is')
    print(result)
    【把s替换成8; "3":指定你想替换几个,并不是替换的范围】
    name = 'freddyissb'
    result = name.replace('s','8')
    #result = name.replace('s','8',3)
    print(result)
    【去掉换行符,以列表形式打印出来】
    name = '''
    aa
    bb
    cc
    '''
    result = name.splitlines()
    print(result)

    【strip:指定去掉的字符,和splitlines功能相同;split:去掉分割符并进行拼接】
    name = '''
    aa
    bb
    cc
    '''
    result = name.split(" ")
    print(result)

     字典操作之-增删改查:

    id_db = {
        123 : {
            'name':'freddy',
            'age':'18',
            'addr':'TangShan'
            },
        789 : {
            'name':'freddie',
            'age':'18',
            'addr':'TangShan'
            },
        456 : {
            'name':'tang',
            'age':'18',
            'addr':'TangShan'
            },
    }
    
    【取字典id_db中,key为123的值:】
    print(id_db[123])
    
    【给字典中key为123,name值改成‘WeiGe’:】
    id_db[123]['name']='WeiGe'
    print(id_db[123])
    
    【给字典id_db中,key为123中,增加一对值:】
    id_db[123]['QQ']=88888888
    print(id_db[123])
    
    【pop,删除字典id_db中,key为123中,addr的值:】
    id_db[123].pop('addr')
    print(id_db[123])
    
    【删除字典中id_db中key为456的key:】
    del id_db[456]
    print(id_db)
    
    【get,取字典id_db中,key为1234的key,使用get取值,娶不到不会报错:】
    v = id_db.get(1234)
    print(v)
    结果:
    None

    【清空字典】
    dic={'k1':'v1','k2':'v2'}
    dic.clear()
    print(dic)

    【浅copy字典】

    food = {'1':'apple','2':'banana'}
    newfood = food.copy()
    print(newfood)
    
    

    字典操作之-字典合并:

    dic_1 = {
        '130282':{
            'name':'freddy',
            'age':23,
            'addr':'TangShan',
        }
    }
    
    dic_2 = {
        'name':'WeiGe',
        '130':{
            'name':'freddie',
            'age':888,
            'addr':'BeiJing'
        },
    }
    print(dic_1)
    print(dic_2)
    dic_1.update(dic_2)
    print(dic_1)

    字典操作之取值:

    【items,把字典转换成列表,数据多的时候千万别这么干:】
    dic_1 = { 130282 :{ 'name':'freddy', 'age':23, 'addr':'TangShan', } } print(dic_1) print(dic_1.items()) print(type(dic_1.items()))

    结果:
    {130282: {'age': 23, 'name': 'freddy', 'addr': 'TangShan'}}
    dict_items([(130282, {'age': 23, 'name': 'freddy', 'addr': 'TangShan'})])
    <class 'dict_items'>

    【keys,取dic_1中的key:】
    print(dic_1.keys())
    结果:
    dict_keys([130282])

    【values,取字典中所有的value:】
    print(dic_1.values())
    结果:
    {'name': 'freddy', 'age': 23, 'addr': 'TangShan'}

    【setdefault,取130282123这个key,要是没有130282123Key,则把130282123设置为字典的Key,value为None:】
    print(dic_1.setdefault(130282123))

    【setdefault,取130282123这个key,要是没有130282123Key,则把130282123设置为字典的Key,value为Tangshengwei:】
    dic_1.setdefault(130282123,"Tangshengwei")
    print(dic_1)

    【fromkeys,给dic_1字典重新做赋值操作:】
    print(dic_1.fromkeys([1,2,3,4,5],'aaa'))
    结果:
    {1: 'aaa', 2: 'aaa', 3: 'aaa', 4: 'aaa', 5: 'aaa'}


    字典:
    dic_1 = {
    130282 :{
    'name':'freddy',
    'age':23,
    'addr':'TangShan',
    },
    12345 :{
    'name':'fr333eddy',
    'age':33,
    'addr':'3333',
    }
    }

    popitem,字典popitem()方法作用是:随机返回并删除字典中的一对键和值(项)。为什么是随机删除呢?因为字典是无序的,没有所谓的“最后一项”或是其它顺序。在工作时如果遇到需要逐一删除项的工作,用popitem()方法效率很高:】
    dic_1.popitem()
    print(dic_1)
    【取字典的key,value:】
    (方法一:效)
    for k,v in dic_1.items():
    print(k,v)
    (方法二,效率高:)
    for key in dic_1:
    print(key,dic_1[key])

     set集合:

    【add,给set集合添加一个元素】
    s = set()
    s.add('freddy')
    print(s)
    
    【difference,打印出S1中有,S2中没有的元素】
    s1 = {11,22,33}
    s2 = {22,33,44}
    s3=s1.difference(s2)
    print(s3)
    
    【symmetric_difference,对称差集,
         把S1中存在,S2中不存在的元素取出来,
    并且把S2中存在,S1中不存在的元素取出来】
    s1 = {11,22,33}
    s2 = {22,33,44}
    s3 = s1.symmetric_difference(s2)
    print(s3)
    
    ==update类型方法,主要应用在其他元素不会再使用的情况下,节省内存空间==
    【difference_update,把S1中存在,S2中不存在的元素取出来,并重新赋值给S1】
    s1 = {11,22,33}
    s2 = {22,33,44}
    s1.difference_update(s2)
    print(s1)
    
    【symmetric_difference_update,把S1中存在,S2中不存在;S2中存在,S1中不存在的值取出来,重新赋值给S1】
    s1 = {11,22,33}
    s2 = {22,33,44}
    s1.symmetric_difference_update(s2)
    print(s1)
    
    【discard,移除指定元素,如果指定的移除元素不存在,不会报错】
    s1 = {11,22,33}
    s2 = {22,33,44}
    s1.discard(22)
    print(s1)
    
    【remove,移除指定元素,如果指定的移除元素不存在,会报错】
    s1 = {11,22,33}
    s2 = {22,33,44}
    s1.remove(22)
    print(s1)
    
    【pop,随机删除S1列表中的一个元素,不能指定移除的元素】
    s1 = {11,22,33}
    res = s1.pop()
    print(res)
    
    【intersection,取交集,把S1和S2相同的值取出来】
    s1 = {11,22,33}
    s2 = {22,33,44}
    s3 = s1.intersection(s2)
    print(s3)
    
    【intersection_update,取交集,把S1和S2相同的值取出来,并重新赋值给S1】
    s1 = {11,22,33}
    s2 = {22,33,44}
    s1.intersection_update(s2)
    print(s1)
    
    【isdisjoint,判断S1和S2有没有交集,没有交集为True,有交集为False】
    s1 = {11,22,33}
    s2 = {44}
    res = s1.isdisjoint(s2)
    print(res)
    
    【issubset,判断S1是否为S2的父序列,是为True,不是为False】
    s1 = {11,22,33}
    s2 = {22,33}
    res = s2.issubset(s1)
    print(res)
    
    【union,取并集,把S1和S2合并,并且把一样的元素去重】
    s1 = {11,22,33}
    s2 = {22,33,44}
    res = s1.union(s2)
    print(res)
    
    【update,给set集合增加元素,被增加的值可以为,列表,元组,字符串;update内部实现就是add】
    s1 = {11,22,33}
    s2 = {11,22,33}
    s3 = {11,22,33}
    
    #列表
    li=[1,2,3,4,5]
    #元组
    tu=(1,2,3,4,5)
    #字符串
    name='freddyfreddy'
    
    s1.update(li)
    s2.update(tu)
    s3.update(name)
    
    print(s1)
    print(s2)
    print(s3)

    【set小练习,例子:服务器增加,减少内存】
    old_dict = {
    "#1":8,
    "#2":4,
    "#4":2,
    }

    new_dict = {
    "#1":4,
    "#2":4,
    "#3":2,
    }
    new_set = set(old_dict.keys())
    old_set = set(new_dict.keys())
    print(new_set)
    print(old_set)
    remove_set = old_set.difference(new_set)
    print(remove_set)
    add_set = new_set.difference(old_set)
    print(add_set)
    update_set = old_set.intersection(new_set)
    print(update_set)
  • 相关阅读:
    为自己的应用程序添加脚本支持
    关于Excel VBA程序的界面编程及其他
    下载JAVA SDK 1.5
    在软件产品中使用VBA的软件和企业
    VBHelper:坚守脚本(转载)
    Google Desktop Search试用手记
    几个不错的开源的.net界面控件
    C++强大背后
    extern用法详解
    条款1:尽量用const和inline而不用#define
  • 原文地址:https://www.cnblogs.com/tangshengwei/p/5598214.html
Copyright © 2020-2023  润新知