2016/05/09 11:47

# 注释

## 单行注释（前置井号）

``````# this is comment
``````

Python 不允许使用关键字作为变量的名称

## 关键字

``````and 	exec	not
assert	finally	or
break	for	pass
class	from	print
continue	global	raise
def	if	return
del	import	try
elif	in	while
else	is	with
except	lambda	yield
``````

## 数字

``````0, 90, 0xff
``````

## 字符串

``````'abc'
"abc"
"""
abc
"""
``````

## 变量

``````print = 3 # print(1) would throw error
int = 4    # int("34g") 会报错
``````

## 常量

``````PI = 3.14
``````

## 字符串常用函数

``````ord('A') # 65
chr(65)  # A
len('abc')  # 3
print('abc') # abc
``````

## list and touple 列表和元组

``````range(5)   # range(0,5)
list(range(5))  # [0,1,2,3,4,5]
``````

``````>>> list = [1,2,3,4]
>>> list[0]
1
>>> list[1:]
[2, 3, 4]
>>> list[:1]
[1]
>>> list[1:3]
[2, 3]
``````

``````if x:
print('True')
``````

``````age = 20
if age >= 6:
print('teenager')
elif age >= 18:
else:
print('kid')
``````

if + else 判断表达式

``````age = 3
if age >= 18:
print('your age is', age)
else:
print('your age is', age)
print('teenager')
``````

## 循环

for ... in list:

``````names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
``````

list 也可以是惰性列表 range(int):

``````sum = 0
for x in range(101):
sum = sum + x
print(sum)
``````

while 循环模式：

``````sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
``````

``````def func(a=None):
if a is None:
a = []
print a
a.append(0)

def func(*args):
print type(args), args
``````

``````def f4(): return 1, 2, 3
``````

``````a = 1
def f():
global a
return a
``````

``````raw_input("hello")
``````

2
0 收藏

0 评论
0 收藏
2