python基础

xiaoxiao2021-02-28  107

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 ornot is in

特殊赋值

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

数字类型

import math

math.pi

math.emath.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 json d=""" [ { "id":1, "key":1 }, { "key":"value", "id":2 } ] """ d1={"name":"kang","id":1,"age":20} print json.dumps(d1,indent=4) ##把python转换成json print json.loads(d) ##把json转换成python

cmd模块

import cmd class 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 True MainCLI().cmdloop()
转载请注明原文地址: https://www.6miu.com/read-37895.html

最新回复(0)