Python 容許在一行中將多個值賦給多個變量。python
x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z) ---- output ------ PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py Orange Banana Cherry
在一行中能夠將一個值同時賦給多個變量。git
x = y = z = "Orange" print(x) print(y) print(z)
若是你有一個 list 或 tuple 集合,python 容許你將集合的值肢解到多個變量中。github
fruits = ["apple", "banana", "cherry"] x, y, z = fruits print(x) print(y) print(z) ----- output ------- PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py apple banana cherry
Python 使用 print
語句進行變量打印,還可使用 +
將 text 和 變量 進行鏈接。markdown
x = "awesome" print("Python is " + x)
固然也可使用 +
對兩個變量進行鏈接。app
x = "Python is " y = "awesome" z = x + y print(z)
對於 數字型 ,這就是一個數學運算,以下所示:函數
x = 5 y = 10 print(x + y)
若是用 +
把字符串和數字組合起來,Python 將會拋出一個錯誤。ui
x = 5 y = "John" print(x + y) ----- output ----- PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py Traceback (most recent call last): File "e:/dream/markdown/python/app/app.py", line 3, in <module> print(x + y) TypeError: unsupported operand type(s) for +: 'int' and 'str'
若是一個變量定義在函數以外,那麼它就是 全局變量,全局變量能夠被任何地方所調用,函數內或者函數外。code
x = "awesome" def myfunc(): print("Python is " + x) myfunc()
若是你在函數內部建立了一個和 全局變量
同樣名字的變量,那麼函數內的變量會做爲局部變量,全局變量仍是原樣在那,只是在函數體內默認狀況下你是沒法訪問的。ip
x = "awesome" def myfunc(): x = "fantastic" print("Python is " + x) myfunc() print("Python is " + x) ----- output ---- PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py Python is fantastic Python is awesome
一般狀況下,在函數體內建立一個變量,這個變量就是局部的,也就是說只能在函數內訪問,有時候你腦洞大開,能不能在函數體內建立一個全局變量呢? 能夠的哈,用 global
關鍵詞便可。字符串
def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x) ---- output ---- PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py Python is fantastic
一樣,你也能夠在函數體內用 global 去改變全局變量的值。
x = "awesome" def myfunc(): global x x = "fantastic" myfunc() print("Python is " + x)
譯文連接: https://www.w3schools.com/pyt...
更多高質量乾貨:參見個人 GitHub: python