python基础

来源:互联网 发布:光缆资源软件 编辑:程序博客网 时间:2024/05/21 17:31

Python常用关键字

关键字

1. if/elif/else    ##选择语句2. for             ##循环语句3. while           ##循环语句4. pass            ##跳过5. break           ##结束整个循环6. continue        ##结束本次循环7. def             ##定义函数8. return          ##函数返回9. del             ##销毁变量10. yeild 11. globle         ##全局变量12. raise  13. import         ##加载包14. from           ##加载包15. try/except/finally  ##异常处理16. asserta        ##单元测试17. print a,b,     ##下一个print不换行18. raw_input() input()

逻辑运算

  • and
  • or
  • not
  • is
  • in

特殊赋值

  • a,b=1,2
  • a=1
  • b=2
  • a,b=b,a ##交换两个变量的内容

数字类型

  • import math

  • math.pi

  • math.e
  • math.sin()
  • abs()
  • max()
  • min()
  • int()
  • str()
  • float()
  • list()

字符串定义

a='hello'a="hello"a="""hello"""

转义
\n
切片(可用于list的分页)
a[1:2:2]
索引
a[1]

字符串方法

sort()join()split() ##拆分strip() ##去出空格rstrip() ##右去除lstrip() ##左去除replase() ##替换endwith() ##判断结尾

字符串格式化

  • a+b
  • “%s%s”%(a,b)
  • 基于字典的格式化
  • “%(a)s %(b)s”%(‘a’:’sasa’,’b’:’dad’)

集成开发环境:pycharm

Shift+F6 ##修改变量名
Ctrl+Alt+L ##规范化变量

列表解析

a=[1,2,3]
b=[_ for _ in a if >1] ##是一个变量,结果为2,3

区别和比较 “is” 和 “==”

“==”比的是值
“is” 比的是变量指向的地址

json模块

import jsond="""[    {        "id":1,        "key":1    },    {        "key":"value",        "id":2    }]"""d1={"name":"kang","id":1,"age":20}print json.dumps(d1,indent=4)                   ##把python转换成jsonprint json.loads(d)                             ##把json转换成python

cmd模块

import cmdclass MainCLI(cmd.Cmd):    prompt = ">>>" ##定义提示符    def do_add(self, line): ##line为后面跟的参数行        line = line.split()        print float(line[0]) + float(line[1])    def do_jian(self, line):        line = line.split()        print float(line[0]) - float(line[1])    def do_mul(self, line):        line = line.split()        print float(line[0]) * float(line[1])    def do_dev(self, line):        line = line.split()        print float(line[0]) / float(line[1])    def do_exit(self, line=None):        """ ##help查看的文档            退出        """        return TrueMainCLI().cmdloop()
原创粉丝点击