博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python学习笔记
阅读量:4565 次
发布时间:2019-06-08

本文共 16176 字,大约阅读时间需要 53 分钟。

print函数

python中的print函数与C语言中printf函数比较相似,但是有以下几点区别:

  • python语句的结尾不需要分号,而且如果添加了分号的话会出现语法错误
  • print函数自动换行,所以不需要像C语言中的printf函数那样在结尾手动换行,但是仍然可以在print函数中使用转义字符。如果不需要它自动换行,可以使用end=“ ”的方式让它以空格分割
  • python的print函数输出变量的格式和C语言中的printf函数不同,且控制变量位数的语句也不相同:
//C语言#include
int main(int argc, char const *argv[]){ int a=6; printf("%6d\n", a); //输出6位整数 return 0;}
#python"""这是一个多行注释3个双引号或者单引号相当于C语言中的/* */注释符"""a = 3.5b = 6print("%.6f"%a,"\t",b) #输出6位小数的浮点数,一个制表符和一个整数               #print中的逗号的位置会在输出中填充一个空格
a = 0while a < 5:    print(a, end = " ")   # 指定以空格结尾,而不需要自动换行    a += 1

C语言中的printf函数可以使用%来将输出格式化,在python中使用format函数代替

基本语法是通过 {} 和 : 来代替以前的 % 。format 函数可以接受不限个参数,位置可以不按顺序。

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序'hello world' >>> "{0} {1}".format("hello", "world")  # 设置指定位置'hello world' >>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置'world hello world'

变量与运算符

 python中有三种类型的变量:数字、字符串和列表

和PHP一样,python中不需要明确的声明一个变量并且定义其变量类型。

常见的运算符和C语言基本都一样,但是python中没有++、--之类的运算符。此外,当需要在一行代码中声明并初始化多个变量时,python有所不同

>>> a=1,b=2SyntaxError: can't assign to literal>>> a,b=1,2>>> a,b(1, 2)

python中的除法运算的结果会自动转换成为浮点数,而且python中有两个不同的运算符:取整除和幂运算符:

>>> 8/42.0>>> 8//32>>> 2**38

字符串拼接运算:

s1="hello"s2="world"print(s1,s2)  #输出结果为hello worldprint(s1+s2)  #输出结果为helloworld

 变量类型转换:使用int()、float()和str()进行类型转换,不过这些转换都必须是单步的,换句话说,如果变量的类型需要多步转换才能转换成目标类型的话就会报错

>>> float(2)2.0>>> int(3.5)3>>> int("2")2>>> int("3.5")Traceback (most recent call last):  File "
", line 1, in
int("3.5")ValueError: invalid literal for int() with base 10: '3.5'

字符与ASCII表值的转换

>>> ord("a")97>>> chr(97)'a'

列表基础

>>> squares = [1, 4, 9, 16, 25]>>> squares[1, 4, 9, 16, 25]

可以使用下标来访问列表中的元素,也可以使用下标将列表生成一个更小的列表

>>> squares[1]

4
>>> squares[1:4]
[4, 9, 16]
>>> squares[-3:]
[9, 16, 25]
>>> squares[:]
[1, 4, 9, 16, 25]

列表也支持拼接运算

>>> squares + [36, 49, 64, 81, 100] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

可以使用append()方法来为列表添加元素

>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here>>> cubes[3] = 64  # replace the wrong value>>> cubes.append(216)  # add the cube of 6>>> cubes.append(7 ** 3)  # and the cube of 7>>> cubes[1, 8, 27, 64, 125, 216, 343]

也可以通过子列表来更改或者删除列表中的元素

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']>>> letters['a', 'b', 'c', 'd', 'e', 'f', 'g']>>> # replace some values>>> letters[2:5] = ['C', 'D', 'E']>>> letters['a', 'b', 'C', 'D', 'E', 'f', 'g']>>> # now remove them>>> letters[2:5] = []>>> letters['a', 'b', 'f', 'g']

可以使用内置函数len()来得到列表的长度

>>> letters = ['a', 'b', 'c', 'd']>>> len(letters)4

列表也是可以进行嵌套的

>>> a = ['a', 'b', 'c']>>> n = [1, 2, 3]>>> x = [a, n]>>> x[['a', 'b', 'c'], [1, 2, 3]]>>> x[0]['a', 'b', 'c']>>> x[0][1]'b'

条件控制

if语句

python中的if语句和C语言中的if语句相似,不过python中没有{ } 符号,而是用制表符来表示这些代码属于这个块;此外,C语言中的 else if 对应于python中 elif,C语言中的  || 、&& 和 ! 符号在python中都用 and 和 or 关键字代替。

a = input()  #等待用户输入a = int(a)   #用户输入的结果是字符串类型的数据,所以需要进行变量类型的转换if a > 5:    print("a > 5")elif a == 5:    print("a = 5")else:    print("a < 5")

python中可以直接在条件语句中对字符串中进行大小比较,而不需要像C语言中那样使用strcmp()函数

>>> if 'apple' <'banana':    print('wow! python is powerful!')wow! python is powerful!

 python中的条件可以直接链接起来,从而省略 and 或者 or 关键字,例如条件语句:a < b == c 用于判断 a 是否小于 b 并且 b 是否等于 c

if条件语句还可以用来对列表或者其他类型的数据结构进行判断处理

>>> t = ['cat','dag','bat']>>> if t:    print('t is not empty')else:    print('t is empty')t is not empty>>> if 'cat' in t:    print('cat is in t')else:    print('cat is not in t')cat is in t

while循环语句

python中的while循环比较简单,和C语言中的while循环没有太大的区别

>>> i = 0>>> while i < 5:    print(i)    i += 101234

 for循环语句

使用列表进行循环

>>> words = ['cat','dog','window']>>> for w in words:    print(w,len(w))cat 3dog 3window 6

 range()函数

>>> for i in range(5):...     print(i)...01234

 range()函数的基本格式是:range(startpoint, endpoint, step),如果只有一个参数,那么range()函数将会把这个参数视为endpoint,startpoint默认为0,step默认为1;如果有两个参数,那么range()函数会将第一个参数赋给startpoint,将第二个参数赋给endpoint,step默认为1;如果有三个参数,则参数对应的方式与range()函数的原型一致。

range(5, 10)   5, 6, 7, 8, 9range(0, 10, 3)   0, 3, 6, 9range(-10, -100, -30)  -10, -40, -70

 使用range()函数进行循环

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']>>> for i in range(len(a)):      print(i,a[i])0 Mary1 had2 a3 little4 lamb

 在python中也可以使用关键字break和continue来进行流程控制,其功能和C语言中的一样。

除此之外,python中还有一个关键字pass,pass不会执行任何操作,通常呗用来当作一个占位符

>>> while True:...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)>>> class MyEmptyClass:...     pass # Create minimal classes>>> def initlog(*args):...     pass   # Used as a placeholder

 数据结构

列表

列表类型的变量具有一些内置的方法,下面是列表对象的一些方法的原型以及功能:

  • list.append(x),在列表的末尾添加一个值为元素
  • list.extend(iterable),将一个列表拼接到目标列表中,可以直接使用 + 运算符来代替
  • list.insert(i, x),在列表下标 i 的位置插入一个值为 x 的元素
  • list.remove(x),删除列表中第一个值为 x 的元素,如果不存在这个元素则会报错
  • list.pop(i),删除列表中下标为 i 的元素,并返回这个元素的值,如果没有指定 i 则默认为最后一个元素
  • list.clear(),删除列表中的所有元素,其功能等价于del list[:]
  • list.index(x, start, end),在下标为start,和end之间的元素中寻找值为 x 的元素,并返回其下标
  • list.count(x),返回列表中值为 x 的元素的个数
  • list.sort(key=None, reverse=False),对一个列表进行排序,一般情况下不需要指定参数,只有当需要进行倒序排序(从大到小排序)的时候,需要指定reverse=True
  • list.reverse(),将一个列表进行倒置
  • list.copy(),复制列表
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']>>> fruits.count('apple')2>>> fruits.count('tangerine')0>>> fruits.index('banana')3>>> fruits.index('banana', 4)  # Find next banana starting a position 46>>> fruits.reverse()>>> fruits['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']>>> fruits.append('grape')>>> fruits['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']>>> fruits.sort()>>> fruits['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']>>> fruits.pop()'pear'

 列表赋值

>>> a = list(range(10))  # 使用list()和range()函数生成列表>>> a[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> squares = []>>> for x in range(10):   # 常规的方法还是使用循环语句为列表赋值             squares.append(x**2)>>> squares[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]>>># 上面的循环还可以用下列语句替换>>> a = [x**2 for x in range(10)]>>> a[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

 子列表的处理

>>> vec = [-4, -2, 0, 2, 4]>>> # create a new list with the values doubled>>> [x*2 for x in vec][-8, -4, 0, 4, 8]>>> # filter the list to exclude negative numbers>>> [x for x in vec if x >= 0][0, 2, 4]>>> # apply a function to all the elements>>> [abs(x) for x in vec][4, 2, 0, 2, 4]

 del语句

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]>>> del a[0]>>> a[1, 66.25, 333, 333, 1234.5]>>> del a[2:4]>>> a[1, 66.25, 1234.5]>>> del a[:]>>> a[]del a   # 删除变量a,如果再次访问a则会报错

元组

元组是多个由逗号分割的数据组成的

>>> t = 12345, 54321, 'hello!'>>> t[0]12345>>> t(12345, 54321, 'hello!')>>> # Tuples may be nested:... u = t, (1, 2, 3, 4, 5)>>> u((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))

但是可以通过为元组重新赋值的方式来改变元组中的元素

>>> s = (1,2,3,4)>>> s(1, 2, 3, 4)>>> s = (4,3,2,1)>>> s(4, 3, 2, 1)

元组中的元素是不可变的,但是元组中如果有可变的数据结构类型的元素的话,那么可以改变该元素中的内容

>>> # Tuples are immutable:... t[0] = 88888Traceback (most recent call last):  File "
", line 1, in
TypeError: 'tuple' object does not support item assignment>>> # but they can contain mutable objects:>>> v = ([1, 2, 3], [3, 2, 1])>>> v([1, 2, 3], [3, 2, 1])>>> v[1][0] = 4>>> v([1, 2, 3], [4, 2, 1])

 需要注意当元组中只有 1 个或 0 个元素的时候,声明元组的语法会比较特殊

>>> empty = ()>>> singleton = 'hello',    # <-- note trailing comma>>> len(empty)0>>> len(singleton)1>>> singleton('hello',)>>> empty()

 集合

集合是python中的一种数据结构,其中的元素没有排序也不会有重复的元素,集合类型的数据对象仍然支持一些数学上的运算,比如并、交、差和对称差

创建一个集合可以使用{}符号将其中的元素放在{}中来进行初始化,也可以使用set()函数来创建,不过当需要创建一个空集合的时候只能使用set()函数

>>> basket = {
'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}>>> print(basket) # show that duplicates have been removed{
'orange', 'banana', 'pear', 'apple'}>>> 'orange' in basket # fast membership testingTrue>>> 'crabgrass' in basketFalse>>> # Demonstrate set operations on unique letters from two words...>>> a = set('abracadabra')>>> b = set('alacazam')>>> a # unique letters in a{
'a', 'r', 'b', 'c', 'd'}>>> a - b # letters in a but not in b{
'r', 'd', 'b'}>>> a | b # letters in a or b or both{
'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}>>> a & b # letters in both a and b{
'a', 'c'}>>> a ^ b # letters in a or b but not both{
'r', 'd', 'b', 'm', 'z', 'l'}

 集合也可以像列表那样使用for循环语句进行初始化

>>> a = {x for x in 'abracadabra' if x not in 'abc'}>>> a{
'r', 'd'}

 字典

python中的字典与PHP中的关联数组非常相似,类似于C语言中的数组,不过这个数组中的每个元素都由一个键值对组成,访问数组中的元素的时候需要使用键来访问相应的值

需要注意的是,python中的字典的键是不可以进行更改的。所以通常字典中的键都是数字或者字符串,当元组中只含有数字或者字符串类型的元素的时候,元组也可以作为字典的键;否则无法使用元组作为某个字典的键。

在python中可以使用list()函数来查看字典中的所有键,如果想要将这些键进行排序,可以直接使用sort()函数。也可以使用关键字 in 来判断字典中是否存在某个键 

>>> tel = {
'jack': 4098, 'sape': 4139}>>> tel['guido'] = 4127>>> tel{
'jack': 4098, 'sape': 4139, 'guido': 4127}>>> tel['jack']4098>>> del tel['sape']>>> tel['irv'] = 4127>>> tel{
'jack': 4098, 'guido': 4127, 'irv': 4127}>>> list(tel)['jack', 'guido', 'irv']>>> sorted(tel)['guido', 'irv', 'jack']>>> 'guido' in telTrue>>> 'jack' not in telFalse

 可以使用dict()函数直接将一系列键值对生成字典,此外,字典也可以像列表那样使用for循环进行初始化

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]){
'sape': 4139, 'guido': 4127, 'jack': 4098}>>> {x: x**2 for x in (2, 4, 6)}{
2: 4, 4: 16, 6: 36}>>> # When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments>>> dict(sape=4139, guido=4127, jack=4098){
'sape': 4139, 'guido': 4127, 'jack': 4098}

 python中的循环

  • 遍历一个字典
>>> knights = {
'gallahad': 'the pure', 'robin': 'the brave'}>>> for k, v in knights.items():... print(k, v)...gallahad the purerobin the brave
  • 遍历一个列表以及其下标,使用enumerate()函数
>>> for i, v in enumerate(['tic', 'tac', 'toe']):...     print(i, v)...0 tic1 tac2 toe
  • 遍历两个及两个以上的列表,使用zip()函数
>>> questions = ['name', 'quest', 'favorite color']>>> answers = ['lancelot', 'the holy grail', 'blue']>>> for q, a in zip(questions, answers):...     print('What is your {0}?  It is {1}.'.format(q, a))...What is your name?  It is lancelot.What is your quest?  It is the holy grail.What is your favorite color?  It is blue.
  • 倒序遍历一个列表,使用reverse()函数
>>> for i in reversed(range(1, 10, 2)):...     print(i)...97531
  • 以从小到大的顺序遍历一个列表,使用sort()函数
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> for f in sorted(set(basket)):...     print(f)...applebananaorangepear
  • 如果在遍历一个列表的时候需要改变这个列表,通常需要重新创建一个新的列表
>>> import math>>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]>>> filtered_data = []>>> for value in raw_data:...     if not math.isnan(value):...         filtered_data.append(value)...>>> filtered_data[56.2, 51.7, 55.3, 52.5, 47.8]

 函数

在python中可以直接使用def function_name(): 来创建一个函数

>>> def fib(n):    # write Fibonacci series up to n...     """Print a Fibonacci series up to n."""...     a, b = 0, 1...     while a < n:...         print(a, end=' ')...         a, b = b, a+b...     print()...>>> # Now call the function we just defined:... fib(2000)0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

 需要注意的是,如果函数中的局部变量和全局变量重名,函数并不会自动调用全局变量,如果需要在调用全局变量,那么需要使用global关键字

此外,将并没有返回结果的函数的值赋给一个变量并不会报错,并且这个变量中的值为None

>>> a = fib(2000)0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 >>> print(a)None

 函数中的默认参数往往只赋值一次,但是当参数为可变的数据结构,类似于列表、字典或者某个类时,情况就有所不同

>>> def f(a, L=[]):    L.append(a)    return L>>> f(1)[1]>>> f(2)[1, 2]>>> f(3)[1, 2, 3]

 如果不想让默认参数多次赋值,那么可以这样写

>>> def f(a, L=None):

if L is None:
L = []
L.append(a)
return L

>>> f(1)

[1]
>>> f(2)
[2]
>>> f(3)
[3]

 模块

python中的模块就是包含了一些列用python语句定义的函数或者其他数据结构,和其他的python文件一样是以.py为后缀名的文件,这一点和PHP相似。

编写一个名为test的.py文件

def max_func(a,b):    if a >= b:        return a    else:        return b

然后使用关键字import来引用test模块

>>> import test>>> test.max_func(1,2)2

 也可以使用from……import语句进行引用,不过在引用模块中的函数时的语句会与import引用模块中的不同

>>> from test import *>>> max_func(1,2)2

 上面代码中的 * 号也可以用某个具体的函数名称代替

也可以使用关键字as对模块或者模块中的函数进行重命名

>>># 重命名模块>>> import test as t>>> t.max_func(1,2)2>>># 重命名模块中的函数>>> from test import max_func as m>>> m(1,2)2

 dir()函数

dir()函数是python内置函数,用于获取模块被定义的名称,它的返回值是一个字符串列表

>>> ====================== RESTART: D:\Python\Code\test.py ======================>>> import test>>> dir(test)['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'max_func']>>> test.max_func(1,2)2>>> dir()['__annotations__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'max_func', 'test']

 类与对象

 python中的类与其他编程语言中的类基本上没有区别,现在定义一个简单的类

>>> class Human:    #类的属性    name =  'none'    age = 70    #类的方法    def my_name(self): #这里的self参数类似于java中的this,用于指向当前对象自己        print('my name is',self.name)    def eat():    # 注意python中的类的方法必须要添加self参数,尽管方法中并不会使用到这个参数        print('eat')    def think(self,a,b):        print('a + b =',a+b)>>> a = Human()>>> a.my_name()my name is none

 在python中的类使用__init()__方法进行初始化

>>> class Complex:     def __init__(self, realpart, imagpart):         self.r = realpart         self.i = imagpart>>> x = Complex(3.0, -4.5)>>> x.r, x.i(3.0, -4.5)

 类的继承,在python中,子类继承了父类的所有属性和方法,并且可以在自己的定义中重新定义父类的方法,或者定义属于自己的新的方法

>>> class Student(Human):    def __init__(self,school='ECNU',grade=3):        super().__init__()   # 调用父类的初始化方法        self.school = school        self.grade = grade        print('Student initial')    def learn():   # 定义属于自己的方法        print('learning')    def think(self,a,b):      # 重写父类的方法        print('a * b =',a*b)>>> stud = Student()Human initialStudent initial>>> stud.grade3>>> stud.think(1,2)a * b = 2

文件读写

文件读写有两种方式,一种是使用先用open打开文件在进行读写操作,最后一定要记得使用close关闭文件;另一种方式是使用with关键字进行操作,最后则不需要关闭这个文件

>>> my_file = open('file1.txt','w')   # 指定以写的方式打开文件,如果不存在则新建一个文件,还可以在文件名的参数中指定文件的存储位置>>> my_file.write('Hello world!\n')13>>> my_file.close()>>> my_file.read()  # 无法对已关闭的文件进行操作Traceback (most recent call last):  File "
", line 1, in
my_file.read()ValueError: I/O operation on closed file.>>> my_file = open('file1.txt','r') # 指定以读的方式打开文件>>> content = my_file.read()>>> print(content)Hello world!>>> my_file.close()
>>> with open('file1.txt','w') as f1:    # 使用with中的w方式打开文件在进行写操作时,会将原有的内容删除掉    f1.write('emmmmm?\nWhere is my helloworld?\n')32>>> with open('file1.txt','r') as f1:    content = f1.read()    print(content)emmmmm?Where is my helloworld?>>> with open('file1.txt','a') as f1:    # 如果想要追加新的内容,则需要使用a方式打开文件    f1.write('fine, hello world Again\n')24>>> with open('file1.txt','r') as f1:    content = f1.read()    print(content)emmmmm?Where is my helloworld?fine, hello world Again

 还可以使用readline()方法来读取文件的第一行,或者使用readlines()方法来读取文件中的所有行

>>> with open('file1.txt','r') as f1:    content = f1.readline() # 读取文件的第一行    print(content)emmmmm?>>> with open('file1.txt','r') as f1:    content = f1.readlines() # 读取文件的所有行,并放入一个列表中    print(content)['emmmmm?\n', 'Where is my helloworld?\n', 'fine, hello world Again\n']

 也可以使用for循环来遍历文件中的每一行

>>> with open('file1.txt') as f:    for line in f:        print(line,end='')emmmmm?Where is my helloworld?fine, hello world Again

 异常处理

 python中的异常处理与Java中的异常处理一样,使用try和except语句进行异常处理,如果try中的语句出现错误,则会执行except中的语句

>>> try:    file = open('temp.txt','r+')  # 如果打开成功,则可以进行读也可以进行写,如果不存在这个文件,则会打开失败,并出现错误except Exception as e:    print(e)[Errno 2] No such file or directory: 'temp.txt'

 也可以在except语句中添加相应的处理机制,来处理这个错误

>>> try:    file_name='temp.txt'    file = open(file_name,'r+')  # 如果打开成功,则可以进行读也可以进行写except Exception as e:    print(e)    r = input('Do you want to create a file named {}?(yes/no)'.format(file_name))    if r == 'yes':        with open(file_name,'w'):            pass        print('File created successfully!')    else:        pass[Errno 2] No such file or directory: 'temp.txt'Do you want to create a file named temp.txt?(yes/no)yesFile created successfully!

 还可以在后面添加else语句,用于执行当没有错误发生的时候的代码

>>> try:    file_name='temp.txt'    file = open(file_name,'r+')  # 如果打开成功,则可以进行读也可以进行写except Exception as e:    print(e)    r = input('Do you want to create a file named {}?(yes/no)'.format(file_name))    if r == 'yes':        with open(file_name,'w'):            pass        print('File created successfully!')    else:        passelse:   # try语句中没有发生错误时可以执行下面的语句    file.write('Python is so cool!\n')    file.close()19>>> with open(file_name,'r') as f:    content = f.read()    print(content)Python is so cool!

 

转载于:https://www.cnblogs.com/Hahahang/p/11115905.html

你可能感兴趣的文章
20181227 新的目标
查看>>
androidtab
查看>>
php 事件驱动 消息机制 共享内存
查看>>
剑指offer 二叉树的bfs
查看>>
LeetCode Maximum Subarray
查看>>
让我们再聊聊浏览器资源加载优化
查看>>
underscore demo
查看>>
CSS hack
查看>>
每日一小练——数值自乘递归解
查看>>
qq登陆错误提示
查看>>
bzoj 1192: [HNOI2006]鬼谷子的钱袋 思维 + 二进制
查看>>
没写完,没调完,咕咕咕的代码
查看>>
Android Studio使用技巧:导出jar包
查看>>
Problem E. TeaTree - HDU - 6430 (树的启发式合并)
查看>>
Kafka序列化和反序列化与示例
查看>>
win10下VS2010中文输入法切换为英文卡死
查看>>
retinex相关代码汇总
查看>>
Cortex-M3 异常返回值EXC_RETURN
查看>>
kettle 转换字段遇到问题(couldn't get row from result set)——摘
查看>>
nginx首页根据IP跳转
查看>>