程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python] Python basic syntax learning (data structure, module, input and output, exception handling, class)

編輯:Python

Python The official tutorial

from AcWing - Django Course simplification learning

Learning experience : Learning while checking , Read through the commonly used ones first

List of articles

    • Python The official tutorial
  • 5. data structure (python3 Big data structure : list , aggregate , Dictionaries )
    • 5.1 list
    • 5.2 Tuples
    • 5.3 aggregate
    • 5.4 Dictionaries
    • 5.5 The technique of cycling
  • 6. modular
  • 7. Input and output
    • 7.1 Format output
    • 7.2. Read and write files
  • 8. exception handling
  • 9. class

5. data structure (python3 Big data structure : list , aggregate , Dictionaries )

5.1 list

It's an array. , But the type can be different

Common functions :

list.append(x)
len(list)

List derivation

squares = [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Two dimensional array

>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]

5.2 Tuples

Similar list , Just can't change , It can be defined without ()

In [13]: t = (1, 2, 3)
In [14]: t[0]= 4
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-a84d171bf4ef> in <module>
----> 1 t[0]= 4
TypeError: 'tuple' object does not support item assignment
In [15]: t = 1, 2, 3
In [16]: t
Out[16]: (1, 2, 3)

Tuple packing and sequence unpacking , For convenient exchange

Sequence unpacking

5.3 aggregate

Python And support aggregate This data type . A collection is an unordered container of non repeating elements . Corresponding C++ Of set. Basic usage includes member detection 、 Eliminate duplicate elements . Collection objects support collections 、 intersection 、 Difference set 、 Symmetrical difference and other mathematical operations .

Create a collection with curly braces or set() function . Be careful , Creating an empty collection can only use set(), Out-of-service {},{} An empty dictionary is created , The next section introduces the data structure : Dictionaries .

Here are some simple examples

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}

5.4 Dictionaries

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}

5.5 The technique of cycling



Flip reversed() And sort sorted() function

6. modular



Python Many packages have been implemented , Directly install and call

7. Input and output

7.1 Format output

7.2. Read and write files

When processing file objects , Best use with keyword . Advantage is , At the end of the clause body , The file will close correctly , Even if an exception is triggered . and , Use with Compared with the equivalent try-finally The code block is much shorter :
Write

>>> with open('workfile') as f:
... read_data = f.read()
>>> # We can check that the file has been automatically closed.
>>> f.closed
True

read

8. exception handling

>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

As shown above , In any case finally Clause .except Clause does not handle the... Triggered by the division of two strings TypeError, So it will finally Clause is triggered again after execution .

In a real application ,finally Clause for releasing external resources ( For example, file or network connection ) Very useful , Whether or not resources are used successfully .

9. class

Constructors , Constructors can also pass parameters , Even keyword correspondence , Unpacking operation

Define member functions

Inherit , Call the constructor of the base class


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved