注意: 这篇文章针对的版本是Python 2.7,但大多也可使用于其他Python 2的版本
""" 多行字符串可以用
三个引号包裹,不过这也可以被当做
多行注释
"""
3 1 + 1 8 - 1 10 * 2 35 / 5 5 / 2 2.0 11.0 / 4.0 (1 + 3) * 2 True
False
not True not False 1 == 1 2 == 1 1 != 1 2 != 1 1 < 10 1 > 10 2 <= 2 2 >= 2 1 < 2 < 3 2 < 3 < 2 "This is a string."
'This is also a string.'
Python学习交流 643692991 群内每天更新相关资料
"Hello " + "world!" "This is a string"[0] "%s can be %s" % ("strings", "interpolated")
"{0} can be {1}".format("strings", "formatted")
"{name} wants to eat {food}".format(name="Bob"
, food="lasagna")
None "etc" is None None is None 0 == False "" == False print "I'm Python. Nice to meet you!"
some_var = 5 some_var some_other_var "yahoo!" if 3 > 2 else 2 li = []
other_li = [4, 5, 6]
li.append(1) li.append(2) li.append(4) li.append(3) li.pop() li.append(3) li[0] li[-1] li[4] li[1:3] li[2:] li[:3] del li[2] li + other_li li.extend(other_li) 1 in li len(li) tup = (1,
2, 3)
tup[0] tup[0] = 3 len(tup) tup + (4, 5, 6) tup[:2] 2 in tup a, b, c = (1, 2, 3) d, e, f = 4, 5, 6
e, d = d, e empty_dict = {}
filled_dict = {"one": 1, "two": 2, "three": 3}
filled_dict["one"] filled_dict.keys() filled_dict.values() "one"
in filled_dict 1 in filled_dict filled_dict["four"] filled_dict.get("one") filled_dict.get("four") filled_dict.get("one", 4) filled_dict.get("four", 4) filled_dict.setdefault("five", 5) filled_dict.setdefault("five", 6) empty_set = set()
some_set = set([1, 2, 2, 3, 4]) filled_set = {1, 2, 2, 3, 4} filled_set.add(5) other_set = {
3, 4, 5, 6}
filled_set & other_set filled_set | other_set {1, 2, 3, 4} - {2, 3, 5} 2 in filled_set 10 in filled_set some_var = 5
if some_var > 10:
print "some_var is totally bigger than 10."
elif some_var < 10:
print "some_var is smaller than 10."
else:
print "some_var is indeed 10."
"""
用for循环遍历列表
输出:
dog is a mammal
cat is a mammal
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
print "%s is a mammal" % animal
"""
`range(number)` 返回从0到给定数字的列表
输出:
0
1
2
3
"""
Python学习交流 643692991 群内每天更新相关资料
for i in range(4):
print i
"""
while 循环
输出:
0
1
2
3
"""
x = 0
while x < 4:
print x
x += 1 try:
raise IndexError("This is an index error")
except IndexError as e:
pass def add(x, y):
print "x is %s and y is %s" % (x, y)
return x + y add(5, 6) add(y=6, x=5) def varargs(*args):
return args
varargs(1, 2, 3) def keyword_args(**kwargs):
return kwargs
keyword_args(big="foot", loch="ness") def all_the_args(*args, **kwargs):
print args
print kwargs
"""
all_the_args(1, 2, a=3, b=4) prints:
(1, 2)
{"a": 3, "b": 4}
"""
args = (1, 2, 3, 4