python基础语法

251 阅读5分钟

一、数据类型

1. 数据类型

  • Number(数字)

    int, float

  • String(字符串)

占位符替换内容
%d整数
%f浮点数
%s字符串
%x十六进制整数
'Hi, %s, you have $%d.' % ('Michael', 1000000)  //'Hi, Michael, you have $1000000.'

'Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125)    //'Hello, 小明, 成绩提升了 17.1%'
  • List(列表): list是一种有序的集合,可以随时添加和删除其中的元素

classmates = ['Michael', 'Bob', 'Tracy']

len(classmates)     // 3
classmates[0]   // 'Michael'
classmates.append('Adam')   // ['Michael', 'Bob', 'Tracy', 'Adam']
classmates.insert(1, 'Jack')    // ['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']
classmates.pop()    // 'Adam' ['Michael', 'Jack', 'Bob', 'Tracy']
classmates.pop(1)   // 'Jack' ['Michael', 'Bob', 'Tracy']
classmates.remove('Michael')    // ['Bob', 'Tracy']
classmates[1] = 'Sarah'     // ['Sarah', 'Tracy']
myList = [0] * 6    // [0, 0, 0, 0, 0, 0]

def f(x):
    return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
list(r)     // [1, 4, 9, 16, 25, 36, 49, 64, 81]

from functools import reduce
def add(x, y):
    return x + y
reduce(add, [1, 3, 5, 7, 9])    // 25

def is_odd(n):
    return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))    // [1, 5, 9, 15]

def takeSecond(elem):
    return elem[1]
[(2, 2), (3, 4), (4, 1), (1, 3)].sort(key=takeSecond)   // [(4, 1), (2, 2), (1, 3), (3, 4)]

sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)  // ['Zoo', 'Credit', 'bob', 'about']
  • Tuple(元组): 一旦初始化就不能修改
classmates = ('Michael', 'Bob', 'Tracy')
classmates[0]   // 'Michael'
  • Set(集合): 没有重复的key
s = set([1, 2, 3])  // {1, 2, 3}
s.add(4)    // {1, 2, 3, 4}
s.remove(4)   // {1, 2, 3}
s1 = set([1, 2, 3])
s2 = set([2, 3, 4])
s1 & s2     // {2, 3}
s1 | s2     // {1, 2, 3, 4}
  • Dictionary(字典):

d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
d['Michael']    // 95
d['Adam'] = 67  // {'Michael': 95, 'Bob': 75, 'Tracy': 85, 'Adam': 67}
'Thomas' in d   // False
d.get('Thomas', -1) // -1
d.pop('Bob')    // 75 {'Michael': 95, 'Tracy': 85}

2. 类型判断

2.1 is

'abc' is str    \\ True

2.2 isinstance

isinstance(123, (int, str))   \\ True

2.3 type

type'abc')    \\ str

2.4 dir

3. 类型转换

int('123')  // 123
int(12.34)  // 12
float('12.34')  // 12.34
str(1.23)   // '1.23'
str(100)    // '100'
bool(1)     // True
bool('')    // False

二、条件和循环

1. if

age = 3
if age >= 18:
    print('adult')
elif age >= 6:
    print('teenager')
else:
    print('kid')

2. for ... in ...

for x in range(3):
    print(x)
// 0 1 2

3. while

sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 2
print(sum)

4. continue 和 break

  • continue语句,跳过当前的这次循环,直接开始下一次循环。
  • break语句直接退出循环。

三、函数

1. 函数

def my_abs(x):
    if x >= 0:
        return x
    elif:
        return -x
    else:
        pass

2. 参数

2.1 默认参数

def power(x, n=2):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s

power(5)    // 25

2.2 可变参数

传入的参数个数是可变的

def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
    
nums = [1, 2, 3]
calc(*nums)     // 14

2.3 关键字参数

允许传入0个或任意个含参数名的参数

def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)

person('Adam', 45, gender='M', job='Engineer')
// name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}

2.4 命名关键字参数

def person(name, age, *, city, job):
    print(name, age, city, job)
person('Jack', 24, city='Beijing', job='Engineer')  // Jack 24 Beijing Engineer

// 如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了:
def person(name, age, *args, city, job):
    print(name, age, args, city, job)

2.5 参数组合

参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。

3. 函数式编程

3.1 匿名函数

def f(x):
    return x * x
// lambda x: x * x

3.2 装饰器

def w1(func):
  def inner():
    print('...验证权限...')
    func()
  return inner
  
@w1
def f1():
  print('f1 called')
@w1
def f2():
  print('f2 called')
 
f1()    // ...验证权限... f1 called
f2()    // ...验证权限... f2 called

3.3 偏函数

import functools
int2 = functools.partial(int, base=2)
int2('1000000')     // 64

四、高级特性

1. 切片

[start, stop, step]

2. 列表生成式

list(x * x for x in range(1, 11) if x % 2 == 0)
// [4, 16, 36, 64, 100]

3. generator(生成器)

g = (x * x for x in range(3))
// <generator object <genexpr> at 0x000001DD94076480>
next(g)     // 0
next(g)     // 1
next(g)     // 4

def odd():
    print('step 1')
    yield 1
    print('step 2')
    yield(3)
    print('step 3')
    yield(5)
o = odd()
next(o)     // step 1 1
next(o)     // step 2 3
next(o)     // step 3 5
next(o)     // Traceback (most recent call last): File "<stdin

4. 迭代器

可以直接作用于for循环的对象统称为可迭代对象:Iterable。

可以使用isinstance()判断一个对象是否是Iterable对象:

from collections import Iterable
isinstance([], Iterable)    // True
isinstance({}, Iterable)    // True
isinstance('abc', Iterable)     // True
isinstance((x for x in range(10)), Iterable)    // True
isinstance(100, Iterable)   // False

五、条件和循环

1. 类和实例

class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def get_grade(self):
        if self.score >= 90:
            return 'A'
        elif self.score >= 60:
            return 'B'
        else:
            return 'C'
lisa = Student('Lisa', 99)
bart = Student('Bart', 59)
print(lisa.name, lisa.get_grade())
print(bart.name, bart.get_grade())

2. 访问限制

class Student(object):
    def __init__(self, name, score):
        self.__name = name
        self.__score = score

    def print_score(self):
        print('%s: %s' % (self.__name, self.__score))

bart = Student('Bart Simpson', 59)
bart.__name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute '__name'

3. 继承和多态

class Animal(object):
    def run(self):
        print('Animal is running...')
class Dog(Animal):
    pass
dog = Dog()
dog.run()   // Animal is running...

isinstance(dog, Animal)   // True

六、错误处理

1. 错误处理

try:
    print('try...')
    r = 10 / int('a')
    print('result:', r)
except ValueError as e:
    print('ValueError:', e)
except ZeroDivisionError as e:
    print('ZeroDivisionError:', e)
except Exception as e:
    print(e)
finally:
    print('finally...')
print('END')

2. 抛出错误

try:
    10 / 0
except ZeroDivisionError:
    raise ValueError('input error!')

七、OI编程

f = open('test.txt', 'w')
f.write('Hello, world!')
f.close()

八、常用内建模块

1. datetime

from datetime import datetime
datetime.now()  // 2015-05-18 16:28:07.198690
datetime(2015, 4, 19, 12, 20)   // 2015-04-19 12:20:00

dt = datetime(2015, 4, 19, 12, 20)
dt.timestamp()  // 1429417200.0
datetime.fromtimestamp(1429417200.0)    // 2015-04-19 12:20:00

datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S')     //2015-06-01 18:19:59