python指南(1): 基礎語法和數據結構

安裝

在官網安裝,最新版本是: https://www.python.org/downloads/release/python-380/

Hello world

打開命令行終端,在windows下一般爲win+r然後輸入cmd,在linux下一般爲alt+t。

查看python版本

>> python --version
Python 3.7.2

直接鍵入python可以進入交互模式,hello world很簡單

>> python
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("hello world")
hello world

當然也可以在一個文件裏寫

# a.py
if __name__ == '__main__':
    print("hello world")
>> python a.py
hello world

編輯器/IDE

推薦兩款編輯器

pycharm

如果未來想繼續使用python編程,推薦安裝這個ide,比vscode功能強很多。並且是免費的 下載鏈接

vscode

適合小型化python編程,下載鏈接

只需要安裝一個python插件就能上手,不安裝插件也自帶高亮。

Python 基礎語法

type類

>>> type
<class 'type'>

暫時不需要知道這個東東是怎麼工作的,我們只需要知道當給一個object時,type可以返回它的類型。

常量類型

>>> type(1) # 整數
<class 'int'>
>>> type(1.0) # 小數
<class 'float'>
>>> type(0x123) # 十六進制數
<class 'int'>
>>> type(0xfef) # fef = 15 * 16^2 + 14 * 16 + 15
<class 'int'>
>>> 0xfef
4079
>>> 15 * (16**2) + 14 * 16 + 15
4079
>>> type("123") # 字符串
<class 'str'>
>>> type('123') # 字符串
<class 'str'>
>>> type("""123""") # 可以換行的字符串
<class 'str'>
>>> type('''123''')  # 可以換行的字符串
<class 'str'>
>>> type(True) # boolean
<class 'bool'>
>>> type(False) # boolean
<class 'bool'>
>>> type(None) # 空
<class 'NoneType'>

運算

# 布爾運算
>>> False and True
False
>>> True or False
True
>>> not False
True
>>> 1 == 2 # 判等號
False
>>> 1 != 2 # 判不等號
True

# 賦值運算
>>> a = 5
5
>>> b = 2
2

# 算術運算
>>> a + b # 加法
7
>>> a - b # 減法
2
>>> a * b # 乘法
10
>>> a / b # 浮點除法
2.5

>>> a // b # 整數除法(向下取整)
2
>>> a % b # 取模
1
>>> a == (a // b) * b + a % b
True

>>> a ** b # 冪 a ^ b
25

>>> a << b # 左移 a * 2^b
20
>>> a * 2 ** b
20
>>> a >> b # 右移 a // 2^b
1
>>> a // 2 ** b
1

比較簡單,懶得打了…全集在此 https://www.runoob.com/python/python-operators.html#ysf1

循環

for 循環,對於[1, 2, 3]中的每一個做一組循環語句:

>>> for i in [1, 2, 3]:
...     print(i)
...
1
2
3

while循環,做循環語句直到跳出

>>> i = 1
>>> while i < 4:
...     print(i)
...     i += 1
...
1
2
3

break控制語句,在break處跳出循環

>>> i = 1
>>> while True:
...     print(i)
...     i += 1
...     if i == 4:
...         break
...
1
2
3

continue控制語句,在continue重新進入下一次循環

>>> i = 0
>>> i = 0
>>> while i < 4:
...     i += 1
...     if i == 2:
...         continue
...     print(i)
...
1
3
4

python 的弱類型是什麼意思

意思就是一個a變量可以包打天下。

>>> a = 1
>>> type(a)
<class 'int'>
>>> a = '123'
>>> type(a)
<class 'str'>
>>> a = 1.
>>> type(a)
<class 'float'>

原因是什麼?簡略說一下。

在python中,所有的變量都相當於一個指針

>>> id(a) # 用id函數獲取一個變量的內存地址(也就是指針)
2369715220816

在內存的這個地方里,存有a的相關信息。

有可能是這樣的:

id(a) ID(a)+8 ID(a)+9 ID(a)+10
a是str(字符串) a的字符串第一個字符是’1’ a的字符串第二個字符是’2’ a的字符串第三個字符是’3’

那麼只需要改變a的id,那麼它就會變成另外一個類型的變量,這樣在編程者的視角看來,a是何種類型的變量變得不那麼確定了。

python 數據結構

這邊着重講一下。先講一下四個基本的類型數據結構list, set, dict, tuple。

用type查看用基本語法是如何構造這四種基本數據結構的?

>>> type([1, 2, 3])
<class 'list'>
>>> type({1, 2, 3})
<class 'set'>
>>> type({1: 'this is 1', 2: 'this is 2', 3: 'this is 3'})
<class 'dict'>
>>> type((1, 2, 3))
<class 'tuple'>
list
>>> a = [1, '2', .1, 2, 3] # 用[ element1, element2, element3, ... ]聲明一個list
>>> a[0] # 獲取第1個元素
1
>>> a[2] # 獲取第3個元素
0.1
>>> a[-1] # 獲取最後一個元素
3
>>> a[-4] # 獲取倒數第4個元素
'2'
>>> a[1:3] # 獲取第[2,4)個元素
['2', 0.1]
>>> a[2:] # 獲取第3個元素以後所有元素
[0.1, 2, 3]
>>> a[:] # 獲取所有元素
[1, '2', 0.1, 2, 3]
>>> a[1::3] # 從第2個元素開始,每三個取三個中的第一個元素
['2', 3]
>>> a[::-1] # 對於a[:]中的每一個元素,倒着操作,每一個取一箇中的第一個元素
[3, 2, 0.1, '2', 1]
>>> len(a) # 長度
5
>>> a + [123123, 414414, 4] # 連接
[1, '2', 0.1, 2, 3, 123123, 414414, 4]
>>> a * 3 # 重複3次並連接,可以自己腦補一下a + a + a = a * 3
[1, '2', 0.1, 2, 3, 1, '2', 0.1, 2, 3, 1, '2', 0.1, 2, 3]
>>> 0.1 in a # 存在性
True

對於a[i:j:k]如果k爲負數會如何,可以自己查閱一下(動手試試自己解決問題的能力)

對於list的方法,比較常用的有append, sort,extend, count, insert, pop, reverse

>>> a.append(1) ; print(a) # 添加一個元素
[1, '2', 0.1, 2, 3, 1]
>>> a.sort() # 排序,但是報錯, 字符串不能和數字比較
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'
>>> a.pop(1) # 從列表刪除下標爲1的元素
'2'
>>> a.sort(); print(a) # 排序,雖然0.1和1不是同一種類型,但是它們之間可以比較
[0.1, 1, 1, 2, 3]
>>> a.reverse(); print(a) # 反轉
[3, 2, 1, 1, 0.1]
>>> a.index(1) # 索引,意思是find the index of 1 in a
2
>>> a.index(0.1) # 索引,意思是find the index of 0.1 in a
4
>>> a.remove(1); print(a) #刪除第一個1
[3, 2, 1, 0.1]

dict

dict,即字典(dictionary)

>>> a = {1: 'this is 1', '2': 'this is 2', int: 'this is 3'} # 用[ key1: value1, key2: value2, key3: value3, ... ]聲明一個list
# 鍵的類型不做限制,只要是類型即可!
>>> a['2'] # 獲取key爲'2'的值
'this is 2'
>>> a[int] = 'modified 3' # 修改
>>> a[int]
'modified 3'
>>> int in a
True

對於dict的方法,比較常用的有update, pop, popitem, copy, clear

所有的builtin方法和類型都可以在python的官方文檔中找到。

這是首頁:https://www.python.org/doc/

在首頁裏找到自己python對應版本的documentation

這是python 3.8.0的首頁https://docs.python.org/3/

自行搜索,可以找到dict的所有基本使用方法https://docs.python.org/3.8/library/stdtypes.html#dict

對於大部分內置數據結構類型,python官網的資料已經足夠充足!

set

講解一個學習python類型的方法。如果編寫這個類型的人足夠良心,那麼內置函數help足以幫助你瞭解關於這個類型最基本的使用方法。

>>> help(set)
Help on class set in module builtins:

class set(object)
 |  set() -> new empty set object
 |  set(iterable) -> new set object
 |
 |  Build an unordered collection of unique elements.
 |
 |  Methods defined here:
 |
 |  __and__(self, value, /)
 |      Return self&value.
 |
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x.
 |
 |  __eq__(self, value, /)
 |      Return self==value.
 |
 |  __ge__(self, value, /)
 |      Return self>=value.
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __gt__(self, value, /)
 |      Return self>value.
 |
 |  __iand__(self, value, /)
 |      Return self&=value.
 |
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __ior__(self, value, /)
 |      Return self|=value.
 |
 |  __isub__(self, value, /)
 |      Return self-=value.
 |
 |  __iter__(self, /)
 |      Implement iter(self).
 |
 |  __ixor__(self, value, /)
 |      Return self^=value.
 |
 |  __le__(self, value, /)
 |      Return self<=value.
 |
 |  __len__(self, /)
 |      Return len(self).
 |
 |  __lt__(self, value, /)
 |      Return self<value.
 |
 |  __ne__(self, value, /)
 |      Return self!=value.
 |
 |  __or__(self, value, /)
 |      Return self|value.
 |
 |  __rand__(self, value, /)
 |      Return value&self.
 |
 |  __reduce__(...)
 |      Return state information for pickling.
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  __ror__(self, value, /)
 |      Return value|self.
 |
 |  __rsub__(self, value, /)
 |      Return value-self.
 |
 |  __rxor__(self, value, /)
 |      Return value^self.
 |
 |  __sizeof__(...)
 |      S.__sizeof__() -> size of S in memory, in bytes
 |
 |  __sub__(self, value, /)
 |      Return self-value.
 |
 |  __xor__(self, value, /)
 |      Return self^value.
 |
 |  add(...)
 |      Add an element to a set.
 |
 |      This has no effect if the element is already present.
 |
 |  clear(...)
 |      Remove all elements from this set.
 |
 |  copy(...)
 |      Return a shallow copy of a set.
 |
 |  difference(...)
 |      Return the difference of two or more sets as a new set.
 |
 |      (i.e. all elements that are in this set but not the others.)
 |
 |  difference_update(...)
 |      Remove all elements of another set from this set.
 |
 |  discard(...)
 |      Remove an element from a set if it is a member.
 |
 |      If the element is not a member, do nothing.
 |
 |  intersection(...)
 |      Return the intersection of two sets as a new set.
 |
 |      (i.e. all elements that are in both sets.)
 |
 |  intersection_update(...)
 |      Update a set with the intersection of itself and another.
 |
 |  isdisjoint(...)
 |      Return True if two sets have a null intersection.
 |
 |  issubset(...)
 |      Report whether another set contains this set.
 |
 |  issuperset(...)
 |      Report whether this set contains another set.
 |
 |  pop(...)
 |      Remove and return an arbitrary set element.
 |      Raises KeyError if the set is empty.
 |
 |  remove(...)
 |      Remove an element from a set; it must be a member.
 |
 |      If the element is not a member, raise a KeyError.
 |
 |  symmetric_difference(...)
 |      Return the symmetric difference of two sets as a new set.
 |
 |      (i.e. all elements that are in exactly one of the sets.)
 |
 |  symmetric_difference_update(...)
 |      Update a set with the symmetric difference of itself and another.
 |
 |  union(...)
 |      Return the union of sets as a new set.
 |
 |      (i.e. all elements that are in either set.)
 |
 |  update(...)
 |      Update a set with the union of itself and others.
 |
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  __hash__ = None

怎麼這麼多?

先關注非魔法方法。所謂魔法方法,也就是__XXX__的那些函數方法。刪除了以後還剩這些

class set(object)
 |  set() -> new empty set object
 |  set(iterable) -> new set object
 |
 |  Build an unordered collection of unique elements.
 |
 |  Methods defined here:
 |
 |  add(...)
 |      Add an element to a set.
 |
 |      This has no effect if the element is already present.
 |
 |  clear(...)
 |      Remove all elements from this set.
 |
 |  copy(...)
 |      Return a shallow copy of a set.
 |
 |  difference(...)
 |      Return the difference of two or more sets as a new set.
 |
 |      (i.e. all elements that are in this set but not the others.)
 |
 |  difference_update(...)
 |      Remove all elements of another set from this set.
 |
 |  discard(...)
 |      Remove an element from a set if it is a member.
 |
 |      If the element is not a member, do nothing.
 |
 |  intersection(...)
 |      Return the intersection of two sets as a new set.
 |
 |      (i.e. all elements that are in both sets.)
 |
 |  intersection_update(...)
 |      Update a set with the intersection of itself and another.
 |
 |  isdisjoint(...)
 |      Return True if two sets have a null intersection.
 |
 |  issubset(...)
 |      Report whether another set contains this set.
 |
 |  issuperset(...)
 |      Report whether this set contains another set.
 |
 |  pop(...)
 |      Remove and return an arbitrary set element.
 |      Raises KeyError if the set is empty.
 |
 |  remove(...)
 |      Remove an element from a set; it must be a member.
 |
 |      If the element is not a member, raise a KeyError.
 |
 |  symmetric_difference(...)
 |      Return the symmetric difference of two sets as a new set.
 |
 |      (i.e. all elements that are in exactly one of the sets.)
 |
 |  symmetric_difference_update(...)
 |      Update a set with the symmetric difference of itself and another.
 |
 |  union(...)
 |      Return the union of sets as a new set.
 |
 |      (i.e. all elements that are in either set.)
 |
 |  update(...)
 |      Update a set with the union of itself and others.

可以自行查看註釋並試驗函數方法。

tuple

知道了python style的學習方法。要不要試試你的自學能力?當然還有一些比較通用的方法。比如百度,谷歌,菜鳥教程, w3cschool, bilibili… (搜索python tuple)

其他數據結構

學完了上面4種數據結構,我希望你先看看python的面向對象方法,這樣更循序漸進。不過也並不妨礙我在這裏列舉一些我覺得比較強大的pythonic類型

# 無需import的類型
>>> int
<class 'int'> # 整數類型,推薦指數:★★★★★★
>>> float
<class 'int'> # 小數類型,推薦指數:★★★★★
>>> str
<class 'str'> # 字符串類型,推薦指數:★★★★★★
>>> bytes # 字節類型,推薦指數:★★★★★
<class 'bytes'>
>>> bytearray # 字節數組類型,推薦指數:★★★★★
<class 'bytearray'>
>>> memoryview # 視圖類型,推薦指數:★★★
<class 'memoryview'>
>>> BaseException # 視圖類型,推薦指數:★★
<class 'BaseException'>
>>> Exception # 視圖類型,推薦指數:★★★★★
<class 'Exception'>
>>> import datetime
>>> datetime.datetime # 長時間類型,推薦指數:★★★★★
<class 'datetime.datetime'>
>>> datetime.date # 日期類型,推薦指數:★★★★★
<class 'datetime.date'>
>>> datetime.time # 短時間類型,推薦指數:★★★★★
<class 'datetime.time'>
>>> import collections
>>> collections.deque # 雙端隊列,推薦指數:★★★
<class 'collections.deque'>
>>> collections.namedtuple # 命名元組,推薦指數:★★★★★
<function namedtuple at 0x00000227BFF0DD08>
>>> import enum
>>> enum.Enum # 枚舉類型,推薦指數:★★★★★
>>> import decimal
>>> decimal.Decimal # 十進制小數類型,推薦指數:★★★★
<class 'decimal.Decimal'>
<enum 'Enum'>
>>> import logging
>>> logging.Logger # 日誌類型,推薦指數:★★★★★
<class 'logging.Logger'>

示例 1

輸入三個整數x,y,z,請把這三個數由小到大輸出

# input() 從輸入獲取一行字符串
# str有一個字符串方法str.split(),如果不給參數,默認按空白字符分隔
line = input().split()
# eval 接受一個字符串,返回字符串執行的結果
# eval('1') = 1,可以在交互式中自己試一下,輸入1,會返回int類型的變量1
# int('2') = 2,將字符串強制轉換爲數字
a, b, c = eval(line[0]), int(line[1]), int(line[2])

# if (表達式):
#空4格 執行語句
if b > c:
    b, c = c, b

# if (表達式):
#空4格 執行語句
# else:
#空4格 否則執行這些語句
if a > b:
    a, b = b, a
else:
    # 如果什麼都不做, 用pass佔位
    pass

# X if (表達式) else Y
# 等價於
# if (表達式):
#    X
# else:
#    Y
# b, c = (X if (表達式) else Y)
b, c = [c, b] if b > c else [b, c]

# print 打印
print(a, b, c)

這裏賣個關子。爲什麼b, c = [b, c]是可行的,這是pythonic魔法的一部分,以後講。

當然,熟練以後,這道題也許只用一句話:

print(*list(sorted(map(eval, input().split()))))

這大概就是python的魅力了?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章