python常量、变量、关键字

常量

  1. python中没有定义常量的关键字,通常用 变量名全大写来标明关键字 ,但是这个变量还是可以改变的
  2. 自定义类来实现常量。

变量

  • 变量命名和其他语言类似,由英文字母、·数字下划线组成,开头不能是数字。
  • python 变量是区分大小写的

# 声明变量
x = "Therre are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)

关键字

KEYWORD DESCRIPTION EXAMPLE
and 逻辑与 True and False == False
as with-as语句的一部分 with X as Y: pass
assert 声明 assert False, "Error!"
break 停止整个循环 while True: break
class 定义一个类 class Person(object)
continue 停止这一次循环,但继续下一次循环 while True: continuev
def 定义一个函数 def X(): pass
del 从字典中删除 del X[Y]
elif Else if 条件 if: X; elif: Y; else: J
else Else 条件 if: X; elif: Y; else: J
except 如果捕获异常,执行该代码块 except ValueError, e: print e
exec 将字符串作为Python代码执行 exec 'print "hello"'
finally 不管是否有异常,finally代码块都执行 finally: pass
for for循环 for X in Y: pass
from 从某一模块中引入特定部分 import X from Y
global 定义一个全局变量 global X
if If 条件 if: X; elif: Y; else: J
import 引入一个模块到当前模块 import os
in for循环的一部分/ 测试X in Y. for X in Y: pass / 1 in [1] == True
is 类似==,判断相等 1 is 1 == True
lambda 创建一个无名函数 s = lambda y: y ** y; s(3)
not 逻辑非 not True == False
or 逻辑或 True or False == True
pass 该代码块为空 def empty(): pass
print 打印一个字符串 print 'this string'
raise 代码出错时,抛出一个异常 raise ValueError("No")
return 退出函数并返回一个返回值 def X(): return Y
try 尝试代签代码块,有异常则进入except代码块 try: pass
while While循环 while X: pass
with 一个变量的别名 with X as Y: pass
yield 暂停, 返回给调用者 def X(): yield Y; X().next()

参考资料

原文地址:https://www.cnblogs.com/gelu/p/11812028.html