基本语法

运算符

Python支持多种运算符,下表大致按照优先级从高到低的顺序列出了所有的运算符,运算符的优先级指的是多个运算符同时出现时,先做什么运算然后再做什么运算。除了我们之前已经用过的赋值运算符和算术运算符,我们稍后会陆续讲到其他运算符的使用。

运算符 描述
[]``[:] 下标,切片
** 指数
~
+``-
按位取反,
正负号
*
/
%
//
乘,
除,
模,
整除
+
-
加,
>>
<<
右移,
左移
& 按位与
^
\\&#124;
按位异或,
按位或
<=
<
>
>=
小于等于,
小于,
大于,
大于等于
==
!=
等于,
不等于
is is not 身份运算符
in not in 成员运算符
not
or
and
逻辑运算符
=
+=
-=
*=
/=
%=
//=
**=
&=
&#124;=
^=
>>=
<<=
(复合)赋值运算符

说明: 在实际开发中,如果搞不清楚运算符的优先级,可以使用括号来确保运算的执行顺序。

print

换行与不换行

  • 在一个字符串中,行末的单独一个反斜杠\表示字符串在下一行继续,而不是开始一个新的行。

    “This is the first sentence.\ This is the second sentence.” 等价于”This is the first sentence. This is the second sentence.”

  • 在 Python 3.x 中print()不换行,我们可以在 print() 函数中添加 end=”” 参数 ```python shoplist = [‘apple’,’banana’,’pear’,’rice’]

print(‘these items are: ‘,end=’’) for item in shoplist: print(item,’ ‘,end=’’)

以下是结果

these items are: apple banana pear rice

  1. - 字符串不可以直接和数字相加,否则出现错误。解决方法:数据类型转换
  2. ```python
  3. info = 'you have tried ' + str(count) + ' times'
  4. print(info)
  5. #以下是结果
  6. #you have tried 6 times

保留原格式输出

1、采用"""

string = """
dog runs to cat.
I run to dog."""

print(string)
#以下是结果
'''

dog runs to cat.
I run to dog.
'''

2、在字符串的最前面加上字母r

s1 = r'\'hello, world!\''

占位符

print('%d  %d = %d' % (a, b, a  b))
'''
上面的print函数中输出的字符串使用了占位符语法,
其中`%d`是整数的占位符,`%f`是小数的占位符,`%%`表示百分号,
字符串之后的`%`后面跟的变量值会替换掉占位符然后输出到终端中
'''

循环

  • 注意 Python 是使用缩进表示程序的结构

    example_list = [1,2,3,4]
    for i in example_list:
      print(i)
      print('inner of for')
    print('outer of for')
    ...
    以下是结果
    1
    inner of for
    2
    inner of for
    3
    inner of for
    4
    inner of for
    outer of for
    ...
    

    range函数

  • range(start, stop)

其中 start 是序列的起始值stop结束值,但不包括该值。类似数学中左闭右开。

  • range(stop)

如果省略了start ,那么将从 0 开始,相当于 range(0, stop)

  • range(start, stop, step)

step步长。从 start 开始,依次增加 step 的值,直至等于或者大于 stop,同理不包括stop的值

continue & break

continue不会执行else后面的语句,会直接进行下一个循环
break会直接跳出循环

判断

  • python 可以通过 if-else 的行内表达式完成类似三目操作符的功能

    var = var1 if condition else var2
    
  • 多个判断

    if condition1:
      true1_expressions
    elif condition2:
      true2_expressions
    elif condtion3:
      true3_expressions
    elif ...
      ...
    else:
      else_expressions
    

数据结构

字符串

切片运算

[][:]为切片运算;左闭右开、双冒号表示步长

# *重复字符串内容
s1 = 'hello ' * 3
print(s1) # hello hello hello 

# +运算
s2 = 'world'
s1 += s2
print(s1) # hello hello hello world

# in运算
print('ll' in s1) # True
print('good' in s1) # False

# 从字符串中取出指定位置的字符(下标运算)
str2 = 'abc123456'
print(str2[2]) # c
# 字符串切片,开始下标为0
print(str2[2:5]) # c12
print(str2[2:]) # c123456
#双冒号表示步长
print(str2[2::2]) # c246
print(str2[::2]) # ac246
# 负数表示从右往左,开始下标为-1
print(str2[::-1]) # 654321cba
print(str2[-3:-1]) # 45

格式化字符串

a, b = 5, 10
print('{0} * {1} = {2}'.format(a, b, a * b)) # 5 * 10 = 50
# Python 3.6以后,格式化字符串还可在字符串前加上字母f
print(f'{a} * {b} = {a * b}') # 5 * 10 = 50

列表 list

切片操作

索引从左开始的值为0,从右开始值为-1

fruits = ['grape', 'apple', 'strawberry', 'waxberry']
fruits += ['pitaya', 'pear', 'mango']
# 列表切片
fruits2 = fruits[1:4]
print(fruits2) # apple strawberry waxberry
fruits4 = fruits[-3:-1]
print(fruits4) # ['pitaya', 'pear']

# 可以通过完整切片操作来复制列表
fruits3 = fruits[:]
print(fruits3) # ['grape', 'apple', 'strawberry', 'waxberry', 'pitaya', 'pear', 'mango']
# 可以通过反向切片操作来获得倒转后的列表的拷贝
fruits5 = fruits[::-1]
print(fruits5) # ['mango', 'pear', 'pitaya', 'waxberry', 'strawberry', 'apple', 'grape']
print(a.index(2)) # 显示列表a中第一次出现的值为2的项的索引
print(a.count(-1)) # 统计列表中某值出现的次数

添加

list1 = [1, 3, 5, 7, 100]
# 尾部添加元素
list1.append(200)
# 指定第二个位置插入400
list1.insert(1, 400) 
# 合并两个列表
# list1.extend([1000, 2000])
list1 += [1000, 2000]
print(list1) # [1, 400, 3, 5, 7, 100, 200, 1000, 2000]
print(len(list1)) # 9

删除

list1 = [1, 3, 5, 7, 100]
# 先通过成员运算判断元素是否在列表中,如果存在就删除该元素
if 3 in list1:
    list1.remove(3)
if 1234 in list1:
    list1.remove(1234)
print(list1) # [1, 400, 5, 7, 100, 200, 1000, 2000]
# 从指定的位置删除元素
list1.pop(0)
list1.pop(len(list1) - 1)
print(list1) # [400, 5, 7, 100, 200, 1000]
# 清空列表元素
list1.clear()
print(list1) # []

排序

list1 = ['orange', 'apple', 'zoo', 'internationalization', 'blueberry']
# 从小到大排,这里是默认的字母表顺序
list2 = sorted(list1)
# 从大到小排
list3 = sorted(list1, reverse=True) 
# 通过key关键字参数指定根据字符串长度进行排序
list4 = sorted(list1, key=len)
print(list1) # ['orange', 'apple', 'zoo', 'internationalization', 'blueberry']
print(list2) # ['apple', 'blueberry', 'internationalization', 'orange', 'zoo']
print(list3) # ['zoo', 'orange', 'internationalization', 'blueberry', 'apple']
print(list4) # ['zoo', 'apple', 'orange', 'blueberry', 'internationalization']

生成式和生成器

f = [x for x in range(1, 10)]
print(f)
f = [x + y for x in 'ABCDE' for y in '1234567']
print(f)
# 用列表的生成表达式语法创建列表容器
# 用这种语法创建列表之后元素已经准备就绪所以需要耗费较多的内存空间
f = [x ** 2 for x in range(1, 1000)]
print(sys.getsizeof(f))  # 查看对象占用内存的字节数
print(f)
# 请注意下面的代码创建的不是一个列表而是一个生成器对象
# 通过生成器可以获取到数据但它不占用额外的空间存储数据
# 每次需要数据的时候就通过内部的运算得到数据(需要花费额外的时间)
f = (x ** 2 for x in range(1, 1000))
print(sys.getsizeof(f))  # 相比生成式生成器不占用存储数据的空间
print(f)
for val in f:
    print(val)

多维列表

multi_dim_a = [[1,2,3],
               [2,3,4]] # 二行三列

元组

元组的元素无法修改

# 定义元组
t = ('骆昊', 38, True, '四川成都')
print(t)
# 获取元组中的元素
print(t[0])
# 遍历元组中的值
for member in t:
    print(member)
# 变量t重新引用了新的元组原来的元组将被垃圾回收
t = ('王大锤', 20, True, '云南昆明')
print(t)

# 将元组转换成列表
person = list(t)
print(person)
# 列表是可以修改它的元素的
person[0] = '李小龙'
person[1] = 25
print(person)

# 将列表转换成元组
fruits_list = ['apple', 'banana', 'orange']
fruits_tuple = tuple(fruits_list)
print(fruits_tuple)

集合

# 创建集合的字面量语法
set1 = {1, 2, 3, 3, 3, 2}  
print(set1)                                  # {1, 2, 3}
print('Length =', len(set1)) # Length = 3

# 创建集合的构造器语法(面向对象部分会进行详细讲解)
set2 = set(range(1, 10))
set3 = set((1, 2, 3, 3, 2, 1))
print(set2, set3)            # {1, 2, 3, 4, 5, 6, 7, 8, 9} {1, 2, 3}

# 创建集合的推导式语法(推导式也可以用于推导集合)
set4 = {num for num in range(1, 100) if num % 3 == 0 or num % 5 == 0}
print(set4)

函数

内置函数

filter(function, iterable)

筛选:序列list中的所有元素,符合function的元素,并放到新的序列中

def is_odd(n):
    return n % 2 == 1

tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)

enumerate(list)

# 通过enumerate函数处理列表之后再遍历可以同时获得元素索引和值
for index, elem in enumerate(list1):
    print(index, elem)

自定义函数

  • 可变参数:传入参数的数量是可变的

用法:参数名前加*

def report(name, *grades):
    total_grade = 0
    for grade in grades:
        total_grade += grade
    print(name, 'total grade is ', total_grade)

可以这样调用函数 report(‘Mike’, 8, 9),输出的结果为 Mike total grade is 17, 也可以这样调用 report(‘Mike’, 8, 9, 10),输出的结果为 Mike total grade is 27

  • 关键字参数:关键字参数可以传入0个或者任意个含参数名的参数,这些参数名在函数定义中并没有出现,这些参数在函数内部自动封装成一个字典(dict). 参数前加**
    def portrait(name, **kw):
      print('name is', name)
      for k,v in kw.items():
          print(k, v)
    
    如果调用参数 portrait(‘Mike’, age=24, country=’China’, education=’bachelor’) 输出:

    name is Mike age 24 country China education bachelor

读写文件

写文件

  • 用法: open('文件名','形式') 如果没有指定文件,会新创建一个文件

    text = 'This is a file'
    my_file = open('my file.txt','w')   #其中形式有'w':write;'r':read.
    my_file.write(text)               #该语句会写入先前定义好的 text
    my_file.close()                   #关闭文件
    
    append_text = '\nThis is appended file.'  # 为这行文字提前空行 "\n"
    my_file = open('my file.txt','a')   # 'a'=append 以增加内容的形式打开
    my_file.write(append_text)
    my_file.close()
    

    读文件

  • 读取到文本的所有内容:file.read()

    file= open('my file.txt','r') 
    content=file.read()  
    print(content)
    
  • 按行读取文本:file.readline()

使用第一次时,读取第一行;使用第二次时, 读取到的是文本的第二行, 以此类推

  • 读取文本的所有行:file.readlines()

优势:可以将读取的内容存储在一个list里,便于遍历

calss

class Calculator:       #首字母要大写,冒号不能缺
    name='Good Calculator'  #该行为class的属性
    price=18
    def add(self,x,y):
        print(self.name)
        result = x + y
        print(result)
    def minus(self,x,y):
        result=x-y
        print(result)
    def times(self,x,y):
        print(x*y)
    def divide(self,x,y):
        print(x/y)
cal = cal=Calculator()  #注意这里运行class的时候要加"()",否则导致无法调用.
cal.name
cal.add(20,30)

def __init__(self,...):

1、开头和结尾各有 2 个下划线,且中间不能有空格
2、__init__(self,...)方法可以包含多个参数,但必须包含一个名为 self 的参数

if __name__ == '__main__':

如果我们导入的模块除了定义函数之外还有可以执行代码,那么Python解释器在导入这个模块时就会执行这些代码,事实上我们可能并不希望如此。
因此如果我们在模块中编写了执行代码,最好是将执行代码放入如下所示的条件中,这样的话除非直接运行该模块,if条件下的这些代码是不会执行的,因为只有直接执行的模块的名字才是”main

def foo():
    pass


def bar():
    pass


# __name__是Python中一个隐含的变量它代表了模块的名字
# 只有被Python解释器直接执行的模块的名字才是__main__
if __name__ == '__main__':
    print('call foo()')
    foo()
    print('call bar()')
    bar()
import function1

print('不会执行function1中的执行代码')

import

import xx # 导入整个xx模块
from xx import yy # 引入xx模块的yy方法
import xx as yy # 引入xx模块,同时为该模块取别名为yy

import time
print(time.localtime())  #这样就可以print 当地时间了

from time import *
print(localtime()) #无需在方法前填写包的名字

装饰器

用于拓展原来函数功能的一种函数,它的返回值也是一个函数。在不用更改原函数的代码前提下给函数增加新的功能
使用时,在需要的函数前加上@demo即可

def debug(func):
    def wrapper():
        print("[DEBUG]: enter {}()".format(func.__name__))
        return func()
    return wrapper

@debug
def hello():
    print("hello")

hello()
-----------------------------
>>>[DEBUG]: enter hello()
>>>hello

try except

try:
    file=open('eeee.txt','r')  #会报错的代码
except Exception as e:  # 将报错存储在 e 中
    print(e)
"""
[Errno 2] No such file or directory: 'eeee.txt'
"""

实用的函数

zip

zip函数接受任意多个(包括0个和1个)序列作为参数,合并后返回一个tuple列表

a=[1,2,3]
b=[4,5,6]
ab=zip(a,b)
print(list(ab))  #需要加list来可视化这个功能
"""
[(1, 4), (2, 5), (3, 6)]
"""

lambda

lambda定义一个简单的函数,实现简化代码的功能。
fun = lambda x,y : x+y, 冒号前的x,y为自变量,冒号后x+y为具体运算。

fun= lambda x,y:x+y
x=int(input('x='))    #这里要定义int整数,否则会默认为字符串
y=int(input('y='))
print(fun(x,y))

"""
x=6
y=6
12
"""

map

map是把函数和参数绑定在一起。

>>> def fun(x,y):
    return (x+y)
>>> list(map(fun,[1],[2]))
"""
[3]
"""
>>> list(map(fun,[1,2],[3,4]))
"""
[4,6]
"""

set

寻找一个句子或者一个 list 当中不同的元素

char_list = ['a', 'b', 'c', 'c', 'd', 'd', 'd']

sentence = 'Welcome Back to This Tutorial'

print(set(char_list))
# {'b', 'd', 'a', 'c'}

print(set(sentence))
# {'l', 'm', 'a', 'c', 't', 'r', 's', ' ', 'o', 'W', 'T', 'B', 'i', 'e', 'u', 'h', 'k'}

print(set(char_list+ list(sentence)))
# {'l', 'm', 'a', 'c', 't', 'r', 's', ' ', 'd', 'o', 'W', 'T', 'B', 'i', 'e', 'k', 'h', 'u', 'b'}

定义好一个 set 之后我们还可以对其添加需要的元素,使用 add 就能添加某个元素。
但是不是每一个东西都能添加,比如添加一个列表会出错。

unique_char = set(char_list)
unique_char.add('x')
# unique_char.add(['y', 'z']) this is wrong
print(unique_char)

# {'x', 'b', 'd', 'c', 'a'}

清除一个元素可以用remove 或者 discard,而清除全部可以用 clear

unique_char.remove('x')
print(unique_char)
# {'b', 'd', 'c', 'a'}

unique_char.discard('d')
print(unique_char)
# {'b', 'c', 'a'}

unique_char.clear()
print(unique_char)
# set()

我们还能进行一些筛选操作
比如对比另一个东西,使用difference看看 set 里有没有和他不同的
或者对比另一个东西,使用intersection看看 set 里有没有相同的

unique_char = set(char_list)
print(unique_char.difference({'a', 'e', 'i'}))
# {'b', 'd', 'c'}

print(unique_char.intersection({'a', 'e', 'i'}))
# {'a'}