• python学习一(基础语句)


    开发环境“pycharm”

    python版本"3.7.3"

    1.程序开始运行的地方

            跟C语言不同,python代码是从上而下依次执行的,就跟bat脚本一样的。这里有一点需要注意,python的缩进符是会被判定为代码语句的。可以这么说,代码从没有缩进的代码开始执行

    例如:

    print("hello world")

            执行结果如下:

            如果在语句前边加入缩进符

        print("hello world")

            结果为:

            这里就会报错。pthon中的缩进符就跟C语言中的"{}"一样,如果在python中定义一个函数,那函数的内容代码前边都需要有缩进符

    if __name__ == '__main__':

            上边这行代码的意思是,如果这个文件被别的文件当作模块调用了,那么此时name 就会变为文件的名字,否则默认是main,那么整个工程就会从这句话下面的没有缩进的代码开始执行。

            所以,如果加了上边这行代码,程序就会从这里开始执行。

            例如:

    1. def test():
    2. print("start here")
    3. if __name__ == '__main__':
    4. print("hello world")
    5. a = "this is"
    6. b = "test"
    7. print(a,b)
    8. test()

            结果为:

            可以看出程序先执行了下边的,最后才执行test。

            但如果我这么写的话,

    1. print("inter start")
    2. def test():
    3. print("start here")
    4. if __name__ == '__main__':
    5. print("hello world")
    6. a = "this is"
    7. b = "test"
    8. print(a,b)
    9. test()
    10. print("end")

            结果为:

             这里可以看到,程序还是从没有缩进的代码开始执行遇到函数则跳过先执行if __name__ == '__main__':,结束后,再执行没有缩进的代码

    2.Pycharm调试与运行

            学会程序的调试非常有助于我们平时的代码分析与改错。

            Pycharm有3种方式进入到DEBUG状态。

            第一种:

            第二种:

            第三种:

             进入调试之前可以先代码前用鼠标左键点击一下,打一个初始断点。

             进入到调试界面后,界面如下:

            调试的话,差不多就用到以上这些功能。可以使用F7进行单步调试(遇到函数则进入),或F8(遇到函数不进入)。

    3.print()函数使用

            print在平时编程和调试中使用的非常多。这里做一个总结。

    1. print("hello world")
    2. 结果:hello world
    3. dic = {'aaa': '111', 'bbb': 222, 'ccc': '333'} #打印数组完整内容
    4. print(dic.items())
    5. 结果:dict_items([('aaa', '111'), ('bbb', 222), ('ccc', '333')])
    6. print("a""b")
    7. 结果:ab
    8. print('*' * 50) #打印50个相同的字符
    9. 结果:**************************************************
    10. print("a","b") #,表示空格符
    11. 结果:a b
    12. a="aaa"
    13. b="bbb"
    14. print(a,b)
    15. 结果aaa bbb
    16. print("www", "xxxx", "com", sep=".") # 设置间隔符,sep即为间隔符
    17. 结果:www.xxxx.com
    18. print("this", end=".") # 设置输出文本末尾的字符,默认的\n
    19. print("is", end=".")
    20. print("test")
    21. 结果:this.is.test
    22. a = 10
    23. b = 20
    24. print("a = %d,b = %d" %(a,b)) #输出整数参数
    25. 结果:a = 10,b = 20
    26. a = 'hello'
    27. b = 'world'
    28. print("a = %s,b = %s" %(a,b)) #输出字符串参数
    29. 结果:a = hello,b = world
    30. arr='this' #字符串长度
    31. print("len = ",len(a))
    32. 结果:len = 4
    33. arr = ['this','is','test'] #数组长度
    34. print('len=',len(arr),sep='')
    35. 结果:len=3
    36. PI = 3.141592653
    37. print('%10.3f'%PI) #字段宽10,精度3
    38. 结果: 3.142
    39. #精度为3,所以只显示142,指定宽度为10,所以在左边需要补充5个空格,以达到10位的宽度
    40. PI=3.1415926
    41. print('%-10.3f' %PI) #左对齐,还是10个字符,但空格显示在右边。
    42. 结果:3.142
    43. PI=3.1415926
    44. print('%+f' % PI) #显示正负号,类型f的默认精度为6位小数。
    45. 结果:+3.141593
    46. PI=3.1415926
    47. print('%010.3f'%PI) #字段宽度为10,精度为3,不足处用0填充空白,0表示转换值若位数不够则用0填充
    48. 结果:000003.142
    49. print('{0},{0},{1},num{2:.2f}'.format('hello','world',1.2345)) #format以{}和: 代替%,format参数可以被多次调用
    50. 结果:hello,hello,world,num1.23
    51. a = 'this'
    52. b = 'is'
    53. c = 'test'
    54. d = 3.14 * 3.14
    55. print('{a} {b} {c},{d:.2f}')
    56. 结果:{a} {b} {c},{d:.2f}
    57. print(f'{a} {b} {c}') #f 表示输出参数
    58. 结果:this is test,9.86

            列表:list

            这里需要补充一下知识点,python中内置了一种数据类型“列表”:list。List是一种有序的集合,可以随时添加和删除其中的元素。

    1. a = ["this","is","a","test","array"]
    2. print(a)
    3. print(f"{a[0]},{a[1]},%s" %a[2],a[-2],a[-1])
    4. 结果是:['this', 'is', 'a', 'test', 'array']
    5. this,is,a test array

             可以添加、删除

    1. a = ["this","is","a","test","array",123]
    2. print(f"arr len:{len(a)},data:{a}")
    3. a.append("add") #在list中追加元素到末尾
    4. print(f"arr len:{len(a)},data:{a}")
    5. a.insert(2,"and") #将元素插入指定的位置
    6. print(f"arr len:{len(a)},data:{a}")
    7. a.pop() #删除List末尾的元素
    8. print(f"arr len:{len(a)},data:{a}")
    9. a.pop(2) #删除指定位置的元素
    10. print(f"arr len:{len(a)},data:{a}")
    11. a[0] = "that" #将某个元素内容直接替换成别的内容
    12. print(f"arr len:{len(a)},data:{a}")
    13. 结果:
    14. arr len:6,data:['this', 'is', 'a', 'test', 'array', 123]
    15. arr len:7,data:['this', 'is', 'a', 'test', 'array', 123, 'add']
    16. arr len:8,data:['this', 'is', 'and', 'a', 'test', 'array', 123, 'add']
    17. arr len:7,data:['this', 'is', 'and', 'a', 'test', 'array', 123]
    18. arr len:6,data:['this', 'is', 'a', 'test', 'array', 123]
    19. arr len:6,data:['that', 'is', 'a', 'test', 'array', 123]

            元组:tuple

             另一种有序列表叫元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改

    1. a = ("this","is","a","test","array",123)
    2. print(f"arr len:{len(a)},data:{a}")
    3. 结果:arr len:6,data:('this', 'is', 'a', 'test', 'array', 123)

             注:如果只有一个元素的时候,定义必须加一个逗号‘,’,用来消除歧义

    a = (1,)

            字典:dict

            无序列表字典dict

            list是有序的,而dict是无序的。也就是说,dict在创建后,内部的元素是无序排列的,如果用print打印的话,打印出来的值跟创建的顺序有可能是不同的

    1. a = {"this","is","a","test","array",123}
    2. print(f"arr len:{len(a)},data:{a}")
    3. 结果:
    4. arr len:6,data:{'is', 'this', 'array', 'a', 'test', 123}
    5. 再次运行:
    6. arr len:6,data:{'this', 'is', 'test', 'array', 123, 'a'}
    7. 再次运行:
    8. arr len:6,data:{'test', 'array', 123, 'this', 'a', 'is'}

             可以看到每次运行的结果都是不一样的。这也就是dict的无序属性

            那dict有什么用呢?顾名思义,dict就是字典的意思,也就是用来查询时使用。dict使用键-值(key-value)存储,具有极快的查找速度

            例如当需要根据名字查看年龄时

    1. # list
    2. name = ["tom","jack","pony","lisa"]
    3. age = [20,21,22,23]
    4. j = 0
    5. for i in name:
    6. if i == "pony":
    7. print(age[j])
    8. break
    9. j += 1
    10. else:
    11. print("no find")
    12. 结果:22
    13. #dict
    14. name = {'tom':20,'jack':21,'pony':22,'lisa':23}
    15. print(name['pony'])
    16. 结果:22

            可以看到,使用dict进行查找的话,速度是相当快的

            如果查询的东西不在列表里,则会直接报错

    1. name = {'tom':20,'jack':21,'pony':22,'lisa':23}
    2. print(name['ponys'])
    3. 结果:
    4. Traceback (most recent call last):
    5. File "d:/python/test_project/test.py", line 28, in
    6. print(name['ponys'])
    7. KeyError: 'ponys'

             针对这种情况,可以通过inget进行判断。

    1. #in
    2. if "pony" in name:
    3. print('age is %d' %name['pony'])
    4. else:
    5. print('no find pony')
    6. if "han" in name:
    7. print('age is %d' %name['han'])
    8. else:
    9. print('no find han')
    10. 结果:
    11. age is 22
    12. no find han
    13. #get
    14. print('pony rst:%s' %name.get('pony',-1))
    15. print('han rst:%s' %name.get('han',-1))
    16. 结果:
    17. pony rst:22
    18. han rst:-1

             如果要替换内容,可以直接往key处写value值。如果要删除,可以调用pop(key)来实现。

    1. name = {'tom':20,'jack':21,'pony':22,'lisa':23}
    2. print('pony rst:%s' %name.get('pony',-1))
    3. #替换
    4. name['pony'] = 55
    5. print('pony rst:%s' %name.get('pony',-1))
    6. #删除
    7. name.pop("pony")
    8. print('pony rst:%s' %name.get('pony',-1))
    9. 结果:
    10. pony rst:22
    11. pony rst:55
    12. pony rst:-1

             和list比较,dict有以下几个特点:

    1.查找和插入的速度极快,不会随着key的增加而变慢

    2.需要占用大量的内存,内存浪费多

            而list相反:

    1.查找和插入的时间随着元素的增加而增加

    2.占用空间小,浪费内存很少

            所有,dict是用空间来换取时间的一种方法

            注:dict的key必须是不可变对象。在python中,字符串、整数等都是不可变的,因此可以作为key,而list是可变的,不能作为Key.

            set

            set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。

            要创建一个set,需要提供一个List作为输入集合

    1. #set
    2. s = set([1,2,3])
    3. print(s)
    4. 结果:
    5. {1, 2, 3}

            注:传入的参数[1,2,3]是一个List,而显示的{1,2,3}也只是表示这个set内部有1,2,3这三个元素,显示的顺序也不表示set是有序的

            重复的元素在set中会被自动过滤,可以通过add(key)方法添加元素到set中。通过remove(key)方法删除元素

    1. #set
    2. s = set([1,2,3,3,2,3])
    3. print(s)
    4. s.add(4)
    5. print(f"s rst:{s}")
    6. s.add(4)
    7. print(f"s rst:{s}")
    8. s.remove(2)
    9. print("s rst:%s" %s)
    10. 结果:
    11. {1, 2, 3}
    12. s rst:{1, 2, 3, 4}
    13. s rst:{1, 2, 3, 4}
    14. s rst:{1, 3, 4}

    4.input

            有时候需要通过读取用户输入信息,此时可以调用input函数进行输入信息获取。

    1. a = input("num:")
    2. print("user input:%s" %a)
    3. 输入:
    4. num:hello
    5. 结果:
    6. user input:hello

             注:input返回的数据类型是str,如果需要将输入的值做判断,则需要将str转换成Int型

    1. a = input("num:")
    2. print("user input:%s" %a)
    3. a = int(a)
    4. if(a > 100):
    5. print(a)
    6. else:
    7. print("not correct")
    8. 输入:123
    9. 结果:123
    10. 输入:0
    11. 结果:not correct

    5.if else

            要注意语句后跟‘:’,跟随执行的代码要加缩进

     6.for

            for 循环

    1. for i in range(5): #从0-4
    2. print(i)
    3. 结果:
    4. 0
    5. 1
    6. 2
    7. 3
    8. 4
    9. for i in range(1,5) #range(star,stop)
    10. print(i)
    11. 结果:
    12. 1
    13. 2
    14. 3
    15. 4
    16. for i in range(1,5,2) #range(start,stop,step)
    17. print(i)
    18. 结果:
    19. 1
    20. 3
    21. arr = 'this' #字符串单个输出
    22. for i in arr:
    23. print(i)
    24. 结果:
    25. t
    26. h
    27. i
    28. s
    29. arr = ['this','is'] #字符串数组单个输出
    30. for i in arr:
    31. print(i)
    32. 结果:
    33. this
    34. is
    35. dic = {'aaa': '111', 'bbb': 222, 'ccc': '333'}
    36. for k in dic:
    37. print(k)
    38. 结果:
    39. aaa
    40. bbb
    41. ccc
    42. dic = {'aaa': '111', 'bbb': 222, 'ccc': '333'}
    43. for k in dic.items(): #.items 遍历各个元素
    44. print(k)
    45. 结果:
    46. ('aaa', '111')
    47. ('bbb', 222)
    48. ('ccc', '333')
    49. dic = {'aaa': '111', 'bbb': 222, 'ccc': '333'}
    50. for k,value in dic.items(): # for 循环默认取的是字典的key赋值给变量名k
    51. print(k,value)
    52. 结果:
    53. aaa 111
    54. bbb 222
    55. ccc 333

    else与break语句连用

            break语句会在循环执行后运行。那为什么还要再加一个else呢?

            看如下代码:

    1. dic = {'aaa': '111', 'bbb': '222', 'ccc': '333'}
    2. for k,value in dic.items(): # for 循环默认取的是字典的key赋值给变量名k
    3. if(k == 'ccc'):
    4. print('find it')
    5. else:
    6. print('no find')
    7. 结果:
    8. find it
    9. no find

            添加break语句

    1. dic = {'aaa': '111', 'bbb': '222', 'ccc': '333'}
    2. for k,value in dic.items(): # for 循环默认取的是字典的key赋值给变量名k
    3. if(k == 'ccc'):
    4. print('find it')
    5. break;
    6. else:
    7. print('no find')
    8. 结果:
    9. find it

            也就是说,for与else连用,只有当有break语句的时候才会有效果

    7.while语句

            while与for比较类型,不同的是,while是只要满足条件,就一直循环,条件不满足时则退出循环。

    1. # 计算0-100的和
    2. i = 0
    3. rst = 0
    4. while i < 101:
    5. rst += i
    6. i += 1
    7. print(f"the sum of 0-100:{rst}")
    8. 结果:the sum of 0-100:5050

    8.switch语句

            python中没有switch语句,可以通过dict实现该函数

    1. def one():
    2. print('one')
    3. def two():
    4. print('two')
    5. def three():
    6. print('three')
    7. def none():
    8. print('none')
    9. def num_to_string(num: object) -> object:
    10. numbers = {
    11. 0 : "zero",
    12. 1 : one,
    13. 2 : two,
    14. 3 : three
    15. }
    16. return numbers.get(num, none) #根据num值来获取对应的内容,如果没有匹配到,则执行none
    17. if __name__ == '__main__':
    18. print(num_to_string(0))
    19. num_to_string(1)()
    20. num_to_string(2)()
    21. num_to_string(3)()
    22. num_to_string(4)()
    23. 结果:
    24. zero
    25. one
    26. two
    27. three
    28. none

    9.type 类型

            返回参数中的类型

            例如:

    1. print(type(1)) #整型
    2. print(type('sgsdfas')) #字符串型
    3. print(type([2])) #列表型
    4. print(type({0:'zero'})) #字典型
    5. 结果:
    6. <class 'int'>
    7. <class 'str'>
    8. <class 'list'>
    9. <class 'dict'>

    10.join 方法

            将序列中的元素以指定的字符连接生成一个新的字符串

            例如:

    1. str = '-'
    2. seq = {'a','b','c'}
    3. print(str.join(seq))
    4. 结果:
    5. a-c-b

    11.self

            self在python中代表的是类的实例,而非类。self只有在类的方法中有,独立的方法或函数中可以没有。self在定义类的方法时是必须有的。类中的方法的第一个参数必须是self,否则无法调用。

            例如:

    1. class test:
    2. def prt(self,data):
    3. print(self,data)
    4. print(self.__class__)
    5. t = test()
    6. t.prt("hello")
    7. 结果:
    8. <__main__.test object at 0x0000026F2867BC18> hello
    9. <class '__main__.test'>

    12.关键字

    def  定义函数

    import 引用,相当于C语言中的extern

    class 创建一个类

     13.Slice

            切片(slice)广泛应用于数据截取中。

    1. l_t = list(range(100))
    2. print('l_t[1:5]:%s' %l_t[1:5]) #获取第1-5个数,从0开始
    3. print('l_t[:10]:%s' %l_t[:10]) #获取前10个数
    4. print('l_t[-10:]:%s' %l_t[-10:]) #获取后10个数
    5. print('l_t[40:-40]:%s' %l_t[40:-40]) #从第10个数开始到倒数第10个数(不包括倒数第10个)
    6. print("l_t[:20:2]:%s" %l_t[:20:2]) #从前20个数,每2个取一个数
    7. print("l_t[::5]:%s" %l_t[::5]) #所有数,每5个取一个
    8. 结果:
    9. l_t[1:5]:[1, 2, 3, 4]
    10. l_t[:10]:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    11. l_t[-10:]:[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
    12. l_t[40:-40]:[40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
    13. l_t[:20:2]:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
    14. l_t[::5]:[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

    14.列表生成式

    1. tl = ['A','B','C']
    2. tl = [a.lower() for a in tl] #大写转小写
    3. print(tl)
    4. tl = [a.upper() for a in tl] #小写转大写
    5. print(tl)
    6. tl = [a for a in range(1,10)] #创建一个列表,从1-9
    7. print(tl)
    8. tl = list(range(1,10)) #创建一个列表,从1-9
    9. print(tl)
    10. tl = [a for a in range(1,10) if a % 2 == 0] #创建一个偶数列表
    11. print(tl)
    12. tl = [a if a % 2 == 0 else -a for a in range(1,10)] #创建一个负奇数,正偶数列表
    13. print(tl)
    14. name = ['tom','jack','lisa']
    15. age = ['18','22','25']
    16. tl = [a + ':' + b for a in name for b in age] #创建一个列表,双重循环组成的排列组合,两个都必须是字符串类型
    17. print(tl)
    18. 结果:
    19. ['a', 'b', 'c']
    20. ['A', 'B', 'C']
    21. [1, 2, 3, 4, 5, 6, 7, 8, 9]
    22. [1, 2, 3, 4, 5, 6, 7, 8, 9]
    23. [2, 4, 6, 8]
    24. [-1, 2, -3, 4, -5, 6, -7, 8, -9]
    25. ['tom:18', 'tom:22', 'tom:25', 'jack:18', 'jack:22', 'jack:25', 'lisa:18', 'lisa:22', 'lisa:25']

  • 相关阅读:
    SpringSecurity - 启动流程分析(三)
    namespace“cv“成员没有“putText“
    牛客刷题<18>3-8译码器
    java 枚举
    异步请求与中断 ( XHR,Axios,Fetch对比 )
    本地部署AutoGPT
    Go语言中的IO
    【Python】不是内部或外部命令,cmd指令报错,path环境配置
    记CVE-2022-39227-Python-JWT漏洞
    vscode离线下载对应版本的插件,避免版本兼容问题
  • 原文地址:https://blog.csdn.net/qq_26226375/article/details/123430156