Python編程:日常練習-1
1.運算符的優先級
print(3*1**3) #3 相當于:3*(1**3)
1
2.小整數池
a = 1 b = 1 print(a is b) # True a = 300 b = 300 print(a is b) # True # 在shell里是False # [-5, 256]之間的整數,值相同的整數共享一個對象 # is 比較內存地址 # == 比較對象的值
1
2
3
4
5
6
7
8
9
10
11
12
3.字符串
def foo1(a): a = a +"2" a = a * 2 return a print(foo1("hello")) # hello2hello2 # 操作符重載 # __add__(+) # __mul__(*) #例如: class Point(object): def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __mul__(self, other): return Point(self.x * other.x, self.y * other.y) def __repr__(self): return "Point({}, {})".format(self.x, self.y) p1=Point(1,2) p2=Point(3,4) print(p1+p2) # Point(4, 6) print(p1*p2) # Point(3, 8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
4.浮點數
print(0.3) # 0.3 print(0.1 + 0.2) # 0.30000000000000004 print(0.1 + 0.2 == 0.3) # False
1
2
3
5.取反操作
print(~5) # -6 print(~~5) # 5 print(~~~5) # -6 # ~按位取反,計算機以補碼存儲
1
2
3
4
6.布爾
print(bool("Flase")) # True
1
7.鏈式比較
print(True == False ) # False print(False ==False) # True print(True == False ==False) # False # 相當于 (True == False) and (False == False)
1
2
3
4
8.循環語句
i = 0 while i < 5: print(i) i += 1 if i ==3: break else: print(0) """ 0 1 2 """
1
2
3
4
5
6
7
8
9
10
11
12
13
14
9.作用域
x = 12 def f1(): x = 3 print(x) def f2(): global x # 沒有這個聲明報錯,local variable 'x' referenced before assignment x += 1 print(x) f1() f2()
1
2
3
4
5
6
7
8
9
10
11
12
10.python關鍵字
eval("1-1") # eval不是關鍵字,是內建函數 assert(1 == 1) pass # nonlocal import keyword print(keyword.kwlist) """33 ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] """
1
2
3
4
5
6
7
8
9
10
11
12
13
習題來源:《Python知識沖頂大會》
http://mp.weixin.qq.com/s/4FfwEdPYhPoCAlKiz2Hk8w
習題解答:《這10個題,有 68% 的人答不對》
http://mp.weixin.qq.com/s/9PFo10K5xXYUZlL9x8QjBA
Python
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。