win7, 64位, Python3.6.3.
代码注释
注释以#开头,代码块以冒号:开始。Python程序是大小写敏感的。
数据类型和变量
整数运算永远是精确的,包括除法,而浮点数运算则可能会有四舍五入的误差;
字符串是以单引号'或双引号"括起来的任意文本,如果'本身也是一个字符,那就可以用""括起来,如果单双引号也是字符,需要使用转义符\;
布尔值只有True、False两种值;
逻辑运算:and、or和not;
空值是Python里一个特殊的值,用None表示。None不能理解为0,因为0是有意义的,而None是一个特殊的空值;
变量名必须是大小写英文、数字和_的组合,且不能用数字开头,类似_xxx这样的函数或变量,外部是可以访问的,但按照约定俗成“虽然我可以被访问,但是请把我视为私有变量,不要随意访问”;
变量名类似__xxx__的是特殊变量,不是private变量,可以直接访问,但是自定义变量一般不要用这种变量名;
在Python中,实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问;
这种变量本身类型不固定的语言称之为动态语言。静态语言在定义变量时必须指定变量类型,如果赋值的时候类型不匹配,就会报错。例如Java是静态语言;
Python 3版本中,字符串是以Unicode编码的;
要注意区分'ABC'和b'ABC',前者是str类型,后者是byte类型,内容显示一样,但bytes的每个字符都只占用一个字节,
if条件语句
布尔型,False表示False,其他为True;
整数和浮点数,0表示False,其他为True;
字符串和类字符串类型(包括bytes和unicode),空字符串表示False,其他为True;
序列类型(包括tuple,list,dict,set等),空表示False,非空表示True;
None永远表示False。
age = int(input('Input your age: '))
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
for循环语句
names = ['zhangsan', 'lisi', 'wangwu']
for name in names:
print(name)
# range(n)生成0到n-1个整数
for x in range(5):
print(x)
while循环语句
sum = 0
n = 1
while n <= 100:
sum = sum + n
n = n + 1
print(sum)
列表(有序集合)
# -*- coding: utf-8 -*-
classmates = ['zhangsan', 'lisi', 'wangwu']
print('classmates =', classmates)
print('len(classmates) =', len(classmates)) # 获取长度
print('classmates[0] =', classmates[0]) # 正序获取元素
print('classmates[1] =', classmates[1])
print('classmates[2] =', classmates[2])
print('classmates[-1] =', classmates[-1]) # 倒序获取元素
print('classmates[-2] =', classmates[-2])
print('classmates[-3] =', classmates[-3])
classmates.append("zhaoliu") # 末尾追加元素
print('classmates=', classmates)
classmates.pop() # 弹出末尾元素
print('classmates =', classmates)
classmates.insert(1, "lucy") # 指定下标插入元素
print('classmates =', classmates)
classmates.pop(1) # 指定下标删除元素
print('classmates =', classmates)
classmates[2] = "Tom" # 元素修改
print('classmates =', classmates)
difTypes = ["hello", 34, ["world", 11], '!'] # 列表中数据类型可以不相同
print("difTypes: ", difTypes)
元组tuple(final列表)
classmates = ('zhangsan', 'lisi', 'wangwu')
print('classmates =', classmates)
classmates[0] = 'Adam' # TypeError: 'tuple' object does not support item assignment
print('classmates =', classmates)
set集合
list = [1, 1, 3, 3, 2, 2 ]
print(list)
s1 = set(list) # 参数为list,s1元素不重复
print(s1)
s1.add(4) # 添加元素
print(s1)
s1.remove(4) # 删除元素
print(s1)
s2 = set([2, 3, 4])
print(s1 & s2) # set与运算
print(s1 | s2) # set或运算
字典dict(即Map)
d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
# 通过get方法获取value,不存在则输出不存在
print("d.get('Thomas', -1) =", d.get('Thomas', '不存在'))
# 判断Bob是否存在
if 'Bob' in d:
print('key Bob exists')
d['Bob'] = 70 # 修改值
# 遍历dict方式一:
for key in d:
print(key, "=", d[key])
d.pop('Bob') # 删除值
print("删除Bob后:")
# 遍历dict方式二:
for (key, value) in d.items():
print(key, "=", value)
函数定义与调用
# 调用系统库函数
x = abs(100)
y = abs(-20)
print(x, y)
print('max(1, 2, 3) =', max(1, 2, 3))
print('min(1, 2, 3) =', min(1, 2, 3))
print('sum([1, 2, 3]) =', sum([1, 2, 3]))
print('type(123) =', type(123)) # 判断对象类型
print('type(\'123\') =', type('123'))
print('type(None) =', type(None))
print('type(abs) =', type(abs))
# 数据类型转换
print(int(12.34))
print(int('555'))
print(float(23))
print(str(23))
print(bool(True))
# 自定义函数
def hello(name):
print('hello', name)
# 调用自定义函数
hello("zhangsan")
# 函数返回多个值,即tuple;默认参数必须为不可变对象,例如y=0
def increase(x, y=0):
return x + 1, y + 1
print(increase(2)) # y值使用默认值0
print(increase(3, 4))
# 定义可变参数,参数前面加*,函数调用时自动组装为一个tuple
def add(*numbers):
sum = 0
for i in numbers:
sum = sum + i
return sum
print(add(1, 2, 4, 8)) # 参数可以多个
t = (2, 2, 2, 2)
print(add(*t)) # 参数为tuple类型
# 定义关键字参数,在参数前加**,函数内部自动组装为一个dict
def keyAgrs(**d):
for (key, value) in d.items():
print(key, "=", value)
keyAgrs(name="zhangsan", age="18") # 传入多个key-value对
d = {'name': "zhangsan", 'age': "18"}
keyAgrs(**d) # 传入dict对象
# 利用递归函数计算阶乘: N! = 1 * 2 * 3 * ... * N
def fact(n):
if n == 1:
return 1
return n * fact(n-1)
print('fact(3) =', fact(3)) #6
高级特性
函数式编程
模块导入
import sys #导入内置模块
import requests #导入第三方模块,需要先通过pip安装:pip install requests
类和对象
类名通常是大写开头的单词,紧接着是(object),表示该类是从哪个类继承下来的,继承的概念我们后面再讲,通常,如果没有合适的继承类,就使用object类,这是所有类最终都会继承的类。
定义一个特殊的__init__方法,__init__方法的第一个参数永远是self,表示创建的实例本身,类似Java中构造函数。
要定义一个方法,除了第一个参数是self外,其他和普通函数一样。要调用一个方法,只需要在实例变量上直接调用,除了self不用传递,其他参数正常传入。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Student(object):
charset = "UTF-8" # 类属性,相当于Java中静态变量
def __init__(self, name, score):
self.name = name
self.__score = score # __score为private变量
def print_score(self):
print('%s: %s' % (self.name, self.__score))
def get_score(self):
return self.__score
def set_score(self, score):
self.__score = score
print(Student.charset) # 类属性
bart = Student('Bart Simpson', 59) # self无需传参,为对象本身,类似Java中的this
print('bart.name =', bart.name) # 调用成员变量
# 私有变量无法直接调用,AttributeError: 'Student' object has no attribute '__score'
# print('bart.__score =', bart.__score)
bart.set_score(89) # 通过set方法设置私有变量
print('bart.__score =', bart.get_score()) # 通过get方法获得私有变量
bart.print_score() # 类中可以直接调用私有变量
继承和多态
class Animal(object): # 继承自object类
def run(self):
print('Animal is running...')
class Dog(Animal): # 继承自Animal类
def run(self):
print('Dog is running...')
class Cat(Animal): # 继承自Animal类
def run(self):
print('Cat is running...')
def run_twice(animal):
animal.run()
animal.run()
a = Animal()
d = Dog()
c = Cat()
print('a is Animal?', isinstance(a, Animal)) # True
print('a is Dog?', isinstance(a, Dog)) # False
print('a is Cat?', isinstance(a, Cat)) # False
print('d is Animal?', isinstance(d, Animal)) # True
print('d is Dog?', isinstance(d, Dog)) # True
print('d is Cat?', isinstance(d, Cat)) # False
run_twice(c) # 只要c对象有run()方法即可
参考资料: