@[TOC]Python上手总结知识点
基础
1.注释行: 利用#进行注释 2.字面常量: a数字:分为整数(integers)和浮点数(Floats); b字符串:可以用单引号(’)双引号(’’)和三引号(’’’ or “”")定义字符串,注意还可以同过format定义字符串,有时如果字符串中含有’时,python会对字符串开始和结束的位置感到困惑如(‘what’s your name’),这时需要用转义序列,变成(‘what’s your name’ or “what\'s your name” or ‘’‘what\‘s your nanme’’); c变量:变量的定义只能有大小写字母、下划线(_)和数字组成。
运算符与表达式1运算符:加(+)减(-)乘(*)乘方(**)除(/)整除(//)取模(%)左移(<<)右移(>>)按位与(&)按位或(||)按位异或(^)按位取反(~)小于(<)大于(>)小于等于(<=)大于等于(>=)等于(==)不等于(!=)布尔非(not)布尔与(and)布尔或(or) 2求值顺序: lambda :Lambda 表达式 if - else :条件表达式 or :布尔“或” and :布尔“与” not x :布尔“非” in, not in, is, is not, <, <=, >, >=, !=, == :比较,包括成员资格测试 (Membership Tests)和身份测试(Identity Tests)。 | :按位或 ^ :按位异或 & :按位与 <<, >> :移动 +, - :加与减 *, /, //, % :乘、除、整除、取余 +x, -x, ~x :正、负、按位取反 ** :求幂 x[index], x[index:index], x(arguments…), x.attribute :下标、切片、调用、属性引 用 (expressions…), [expressions…], {key: value…}, {expressions…} :显示绑定或数 组、显示列表、显示字典、显示设置 3;改变求值顺序加括号()
控制流1 if 如果条件为true执行,如果为flase则执行else-block 中的语句
number = 23
guess = int(input('Enter an integer : '))
if guess == number:
# 新块从这里开始
print('Congratulations, you guessed it.')
print('(but you do not win any prizes!)')
# 新块在这里结束
elif guess < number:
# 另一代码块
print('No, it is a little higher than that')
# 你可以在此做任何你希望在该代码块内进行的事情
else:
print('No, it is a little lower than that')
# 你必须通过猜测一个大于(>)设置数的数字来到达这里。
print('Done')
# 这最后一句语句将在
# if 语句执行完毕后执行。
2 while如果条件为true则重复执行while中的语句,当while条件为flase 时则不成立,跳出while循环
i=0
while(i<5)
i=i+1
print(i)
3 for…in … 循环语句
for i in range(1,5):
print(i)
else:
print('the for loop is over')
break语句,中断循环语句,即使条件成立,但是遇到break时也强制退出循环, conitune语句,告诉pthton跳过coninue后面的语句,并且继续执行下一次迭代。
函数def hello_world():
print('hello world')
hello _world()
注意局部变量和全局变量的区别,当在函数内定义的参数时,属于局部变量,只在函数快内起作用,需要定义全局变量时,需要用global 其次还有默认参数,可变参数,当定义可变参数时需要用(*)如(*phone定义元组,**phonebook定义字典dictionary) 2返回参数值,用return语句,从函数中返回数值到主函数 3文档字符串函数(Docstring)如果在函数中定义了字符串,在输出时可以在末尾调用Docstring进行输出:
def hello():
''' life is a fuching movie'''
print(hello()__doc__)#特别注意这里下下划线应该总共敲击四次,否则报错
模块
1.模块即是通过定义一次重用代码,一段代码保存.py为后缀的文件,可以再另外一段程序中运用import进行调用,如(import sys,)如果希望使用sys中的变量则应该用(.)如(调用sys中的argv变量,sys.argv, 还可以通过from…imprt…调用(from sys import argv). 2.通过__name__找到模块的名称, 通过__dir__函数返回由对象定义的名称列表 3, 自己编写的程序就是一个模块,如果再另外一段程序中需要使用,则只需要使用,import+ 模块名称即可,如(import mymodule) 4,包是指包含模块与一个特殊的__init__.py的文件夹。
数据结构zoo = ('python', 'elephant', 'penguin') #zoo为列表
new_zoo = 'monkey', 'camel', zoo
print('All animals in new zoo are', new_zoo)
print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2]) #结果为penguin,记住Python是从0开始计数的
ab = {
'Swaroop': 'swaroop@swaroopch.com',
'Larry': 'larry@wall.org',
'Matsumoto': 'matz@ruby-lang.org',
'Spammer': 'spammer@hotmail.com'
}
用try…except 去处理异常。 通过raise语句来引发一次异常 try…finall来处理读取文件时出现的异常。 with来处理异常。
标准库1.标准库是指已经封装好的一段代码,在使用时只需要调用就行,如sys,在使用时需哟啊import sys,即可以使用里面的代码。 2. 如果在debugging时,需要将一些重要的信息储存在某个地方,需要使用loggging模块实现。