python语法
1、变量
变量使用需要先实例化才可以进行计算
spam_amount = 0
spam_amount += 1
多种赋值方法:
datestr = '1956-01-31'
year, month, day = datestr.split
new_labels = ['${}'.format(int(amt)) for amt in ticks]
变量作用域:
- L (Local) 局部作用域
- E (Enclosing) 闭包函数外的函数中
- G (Global) 全局作用域
- B (Built-in) 内置作用域(内置函数所在模块的范围)
内置作用域是通过一个名为 builtin 的标准模块来实现的,但是这个变量名自身并没有放入内置作用域内,所以必须导入这个文件才能够使用它
内部作用域修改外部作用域变量时使用global
num = 1
def fun1():
global num # 需要使用 global 关键字声明
print(num) -> 1
num = 123
print(num) -> 123
修改嵌套作用域的变量使用nonlocal
def outer():
num = 10
def inner():
nonlocal num # nonlocal关键字声明
print(num) -> 10
num = 100
print(num) -> 100
2、条件语句
if x == 0:
...
elif x > 0:
...
if-else用一行代码解决:
a = [1,2,3]
b = a if len(a) != 0 else ""
print(b)
使用in的if-else:
if card in ['J', 'Q', 'K']:
total += 10
三元表达式
outcome = 'failed' if grade < 50 else 'passed'
3、循环
for
for a in range(5):
...
for … else
else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行
for num in range(10,20): # 迭代 10 到 20 之间的数字
for i in range(2,num): # 根据因子迭代
if num%i == 0: # 确定第一个因子
j=num/i # 计算第二个因子
print '%d 等于 %d * %d' % (num,i,j)
break # 跳出当前循环
else: # 循环的 else 部分
print num, '是一个质数'
ele > thresh for ele in L
while
while i < 10:
print(i, end=' ')
while-else
条件为false导致循环终止时,执行else的语句块
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
while一行代码格式:
while (flag): print 'Given flag is really true!'
4、函数
def least_difference(a, b = 1, *c)
# a为必须参数,b为可选默认参数,c为不定长参数,通过元组形式被导入
# *c为元组形式,**c为字典形式
"""
# docstrings(说明文档)
>>> 例子
"""
...
匿名函数
# 函数说明
sum = lambda arg1,arg2: arg1 + arg2
print("相加的值为:", sum(10, 20)) -> 相加的值为:30
5、list
通过下标访问列表元素
planets[-1] # 列表倒数第一个元素
切割
planets[0:3] # 访问下标从0到2 不包括3
sorted sum max等可对list使用的方法
通过del删除列表元素
del planets[1]
通过remove删除列表元素
planets.remove('Earth') #如果指定元素有多个,只删除第一个
和in结合使用:
planets = ["Earth", "Mars", ...]
"Earth" in planets -> True
列表解析
square = [n**2 for in range(10)]
short_planets = [planet for planet in planets if len(planet) < 6]
6、Tuples(元组)
t = (1, 2, 3)
t = 1, 2, 3 #也可以不用括号
同list 但元素不可修改
只能通过del删除整个tuple
del t
7、string
'abc '
"abc "
""" a
b"""
切割
planet = 'pluto'
string[-3:] = 'uto'
使用.format()格式化
print("{:.3f}".format(2.1415)) -> 2.142
8、dictionaries(字典)
值可取任意数据类型 但键必须是不可变的 如字符串,数字,元组
numbers = {'one':1, 'two':2, 'three':3}
通过key增加新内容或修改
numbers['eleven'] = 11
通过in和key确定是否存在键值对
'one' in numbers -> True
通过del删除对应的键值对
del number['eleven']
9、import
用法
import math as mt
from math import *
10、set(集合)
a = set('abcde') # 创建空集合必须用set()
或
a = {'a', 'b', 'c', 'd', 'e'}
集合适用于数学中集合的操作:
<= >= | & - ^
11、 迭代器和生成器
迭代器是一个可以记住遍历位置的对象,从集合的第一个元素开始访问直到所有元素被访问完,只能往前不能后退
list = [1, 2, 3, 4]
it = iter(list)
for x in it:
print(x, end=" ") -> 1 2 3 4
生成器(待补充)
import sys
def fibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()
12、 异常处理
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
raise # 抛出异常
else: # try没有发生任何异常时执行
print("result is", result)
finally:
print("executing finally clause")
13、 类
class People:
#定义基本属性
name = ''
age = 0
#定义私有属性,私有属性在类外部无法直接进行访问
__weight = 0
#定义构造函数
#self代表一个类的实例
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("Hello")
继承
class Student(people):
grade = ''
def __init__(self,n,a,w,g):
#调用父类的构造函数
people.__init__(self,n,a,w)
self.grade = g
#重写父类的方法
def speak(self):
print("Hi")
可以通过super()调用父类方法
s = Student("Mark", 20, 60, 2)
s.speak() -> Hi
super(Student,s).speak() ->Hello