Hướng dẫn python capture all output - python nắm bắt tất cả đầu ra

import os 
import glob
import collections
import json

path_list=[]
totalFiles = 0
totalDirectories = 0

def convert_bytes[num]:

    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if num < 1024.0:
            return "%3.1f %s" % [num, x]
        num /= 1024.0
        

for line in open["config.ici",'r']:
    li=line.strip[]
    if not li.startswith["#"]:
        path_list.append[line.rstrip[]]
        
if len[path_list]==0:
    print["No path is Incerted in config file please"]
    path=input["Please enter path to get detailes"]
else:
    for path in path_list:
        print["-"*100]
        print[f"We are proceding with {path}"]
        print["-"*100]
        for base, dirs, files in os.walk[path]:
            for directories in dirs:
                totalDirectories += 1
            for Files in files:
                totalFiles += 1
        print["Directory Information"]
        print[]
        print['Total number of files =',totalFiles]
        print["-"*100]
        print['Total Number of directories =',totalDirectories]
        print["-"*100]
        print['Total:',[totalDirectories + totalFiles]]
        print["-"*100]



        # Get a list of files [file paths] in the given directory 
        list_of_files = filter[ os.path.isfile,
                                glob.glob[path + '/**/*', recursive=True] ]
        # Sort list of files in directory by size 
        list_of_files = sorted[ list_of_files,
                                key =  lambda x: os.stat[x].st_size]
        # Iterate over sorted list of files in directory and 
        # print them one by one along with size
        print["top 10 smalest files in tree"]
        print["-"*100]
        for elem in list_of_files[0:9]:
            file_size  = os.stat[elem].st_size 
            print[convert_bytes [file_size], ' -->', elem]
        print["-"*100]

        print["top 5 largest files in a tree"]
        print["-"*100]
        for elem in list_of_files[:-6:-1]:
            file_size  = os.stat[elem].st_size 
            print[convert_bytes [file_size], ' -->', elem]
        print["-"*100]

        #extantion
        print["all files with extantion detailes"]
        print["-"*100]
        cnt = collections.Counter[]
        for base,dirs,files in os.walk[path]:

            for filename in glob.glob1[base,"*"]:
                name, ext = os.path.splitext[filename]
                cnt[ext] += 1

        #print[str[dict[cnt]]]
        dict = {str[k]:int [v]  for k,v in cnt.items[]}
        json1 = json.dumps[dict,indent=4,sort_keys=False]

        print['extention = {}'.format[ json1]]
        print["-"*100]



** Cần ghi tất cả đầu ra trong tệp văn bản, dựa trên đầu vào đường dẫn từ tệp cấu hình **

Xin chào nhóm!

Tôi đang thực hiện 'Python FILFER_INFO.PY> OUT.TXT'

Tôi có thể ra ngoài nhưng tôi cần đầu ra ở định dạng này

*Nếu chứa tệp cấu hình

#path

  1. c:/temp
  2. c:/new

Mong đợi sản lượng như thế này

  • c/temp.txt --- trong văn bản này điền tất cả thông tin của thư mục phải được hiển thị

  • c/new.txt --- trong văn bản này điền tất cả thông tin của thư mục phải được hiển thị

Trong các ví dụ sau, đầu vào và đầu ra được phân biệt bởi sự hiện diện hoặc vắng mặt của lời nhắc [>>> và Hồi]: Để lặp lại ví dụ, bạn phải nhập mọi thứ sau khi nhắc, khi lời nhắc xuất hiện; Các dòng không bắt đầu bằng lời nhắc là đầu ra từ trình thông dịch. Lưu ý rằng một lời nhắc thứ cấp trên một dòng trong một ví dụ có nghĩa là bạn phải nhập một dòng trống; Điều này được sử dụng để kết thúc một lệnh đa dòng.>>> and ]: to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command.

Bạn có thể chuyển đổi hiển thị lời nhắc và đầu ra bằng cách nhấp vào

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
0 ở góc trên bên phải của hộp ví dụ. Nếu bạn ẩn các lời nhắc và đầu ra cho một ví dụ, thì bạn có thể dễ dàng sao chép và dán các dòng đầu vào vào trình thông dịch của bạn.

Nhiều ví dụ trong hướng dẫn này, ngay cả những ví dụ đã nhập tại dấu nhắc tương tác, bao gồm các bình luận. Nhận xét trong Python bắt đầu với ký tự băm,

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
1 và mở rộng đến cuối dòng vật lý. Một nhận xét có thể xuất hiện khi bắt đầu một dòng hoặc theo khoảng trắng hoặc mã, nhưng không phải trong một chuỗi theo nghĩa đen. Một ký tự băm trong một chuỗi theo nghĩa đen chỉ là một ký tự băm. Vì các bình luận là để làm rõ mã và không được giải thích bởi Python, chúng có thể bị bỏ qua khi gõ vào các ví dụ.

Vài ví dụ:

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."

3.1. Sử dụng Python làm máy tính công trìnhUsing Python as a Calculator¶

Hãy để thử một số lệnh Python đơn giản. Bắt đầu thông dịch viên và đợi lời nhắc chính,

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
0. [Nó không nên mất nhiều thời gian.]

3.1.1. SốNumbers¶

Trình thông dịch hoạt động như một máy tính đơn giản: bạn có thể nhập một biểu thức vào nó và nó sẽ viết giá trị. Biểu thức cú pháp rất đơn giản: các toán tử

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
3,
>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
4,
>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
5 và
>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
6 hoạt động giống như trong hầu hết các ngôn ngữ khác [ví dụ: Pascal hoặc C]; Điểm dừng [
>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
7] có thể được sử dụng để nhóm. Ví dụ:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> [50 - 5*6] / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6

Các số nguyên [ví dụ:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
8,
>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
9,
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
0] có loại
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
1, các số có phần phân số [ví dụ:
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
2,
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
3] có loại
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
4. Chúng ta sẽ thấy thêm về các loại số sau này trong hướng dẫn.

Phân chia [

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
6] luôn trả lại một chiếc phao. Để thực hiện phân chia sàn và nhận kết quả số nguyên, bạn có thể sử dụng toán tử
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
6; Để tính toán phần còn lại, bạn có thể sử dụng
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
7:floor division and get an integer result you can use the
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
6 operator; to calculate the remainder you can use
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
7:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # floored quotient * divisor + remainder
17

Với Python, có thể sử dụng toán tử

>>> width = 20
>>> height = 5 * 9
>>> width * height
900
8 để tính toán sức mạnh 1:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

Dấu hiệu bằng nhau [

>>> width = 20
>>> height = 5 * 9
>>> width * height
900
9] được sử dụng để gán giá trị cho một biến. Sau đó, không có kết quả nào được hiển thị trước lời nhắc tương tác tiếp theo:

>>> width = 20
>>> height = 5 * 9
>>> width * height
900

Nếu một biến không được xác định là một giá trị [được gán một giá trị], cố gắng sử dụng nó sẽ cho bạn một lỗi:

>>> n  # try to access an undefined variable
Traceback [most recent call last]:
  File "", line 1, in 
NameError: name 'n' is not defined

Có sự hỗ trợ đầy đủ cho điểm nổi; Các toán tử với các toán hạng loại hỗn hợp chuyển đổi toán hạng số nguyên thành điểm nổi:

Trong chế độ tương tác, biểu thức in cuối cùng được gán cho biến

>>> n  # try to access an undefined variable
Traceback [most recent call last]:
  File "", line 1, in 
NameError: name 'n' is not defined
0. Điều này có nghĩa là khi bạn đang sử dụng Python làm máy tính bàn, ví dụ như tiếp tục tính toán sẽ dễ dàng hơn, ví dụ::

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round[_, 2]
113.06

Biến này nên được coi là người dùng chỉ đọc. Don Tiết rõ ràng gán một giá trị cho nó-bạn sẽ tạo một biến cục bộ độc lập với cùng tên che giấu biến tích hợp với hành vi kỳ diệu của nó.

Ngoài

>>> width = 20
>>> height = 5 * 9
>>> width * height
900
1 và
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
4, Python hỗ trợ các loại số khác, chẳng hạn như
>>> n  # try to access an undefined variable
Traceback [most recent call last]:
  File "", line 1, in 
NameError: name 'n' is not defined
3 và
>>> n  # try to access an undefined variable
Traceback [most recent call last]:
  File "", line 1, in 
NameError: name 'n' is not defined
4. Python cũng có hỗ trợ tích hợp cho các số phức tạp và sử dụng hậu tố
>>> n  # try to access an undefined variable
Traceback [most recent call last]:
  File "", line 1, in 
NameError: name 'n' is not defined
5 hoặc
>>> n  # try to access an undefined variable
Traceback [most recent call last]:
  File "", line 1, in 
NameError: name 'n' is not defined
6 để chỉ ra phần tưởng tượng [ví dụ:
>>> n  # try to access an undefined variable
Traceback [most recent call last]:
  File "", line 1, in 
NameError: name 'n' is not defined
7].complex numbers, and uses the
>>> n  # try to access an undefined variable
Traceback [most recent call last]:
  File "", line 1, in 
NameError: name 'n' is not defined
5 or
>>> n  # try to access an undefined variable
Traceback [most recent call last]:
  File "", line 1, in 
NameError: name 'n' is not defined
6 suffix to indicate the imaginary part [e.g.
>>> n  # try to access an undefined variable
Traceback [most recent call last]:
  File "", line 1, in 
NameError: name 'n' is not defined
7].

3.1.2. Dây¶Strings¶

Bên cạnh các con số, Python cũng có thể thao tác các chuỗi, có thể được thể hiện theo nhiều cách. Chúng có thể được đặt trong các trích dẫn đơn [

>>> n  # try to access an undefined variable
Traceback [most recent call last]:
  File "", line 1, in 
NameError: name 'n' is not defined
8] hoặc trích dẫn kép [
>>> n  # try to access an undefined variable
Traceback [most recent call last]:
  File "", line 1, in 
NameError: name 'n' is not defined
9] với cùng một kết quả 2.
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round[_, 2]
113.06
0 có thể được sử dụng để thoát khỏi trích dẫn:

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'

Trong trình thông dịch tương tác, chuỗi đầu ra được đặt trong các trích dẫn và các ký tự đặc biệt được thoát khỏi dấu gạch chéo ngược. Mặc dù điều này đôi khi có thể trông khác với đầu vào [các trích dẫn kèm theo có thể thay đổi], hai chuỗi tương đương. Chuỗi được đặt trong các trích dẫn kép nếu chuỗi chứa một trích dẫn duy nhất và không có trích dẫn kép, nếu không nó được đặt trong các trích dẫn đơn. Hàm

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round[_, 2]
113.06
1 tạo ra đầu ra dễ đọc hơn, bằng cách bỏ qua các trích dẫn kèm theo và bằng cách in các ký tự đã thoát ra và đặc biệt:

>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print['"Isn\'t," they said.']
"Isn't," they said.
>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print[], \n is included in the output
'First line.\nSecond line.'
>>> print[s]  # with print[], \n produces a new line
First line.
Second line.

Nếu bạn không muốn các ký tự được mở đầu bởi

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round[_, 2]
113.06
0 được hiểu là ký tự đặc biệt, bạn có thể sử dụng các chuỗi thô bằng cách thêm
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round[_, 2]
113.06
3 trước khi trích dẫn đầu tiên:

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
0

Chuỗi chữ có thể trải dài nhiều dòng. Một cách là sử dụng Triple-Rotes:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round[_, 2]
113.06
4 hoặc
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round[_, 2]
113.06
5. Kết thúc của các dòng được tự động bao gồm trong chuỗi, nhưng nó có thể ngăn chặn điều này bằng cách thêm
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round[_, 2]
113.06
0 ở cuối dòng. Ví dụ sau:

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
1

tạo ra đầu ra sau [lưu ý rằng dòng mới ban đầu không được bao gồm]:

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
2

Chuỗi có thể được nối [dán lại với nhau] với toán tử

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
3 và lặp lại với
>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
5:

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
3

Hai hoặc nhiều chuỗi chữ [nghĩa là các chữ cái được đặt giữa các trích dẫn] bên cạnh nhau được tự động kết hợp.

Tính năng này đặc biệt hữu ích khi bạn muốn phá vỡ chuỗi dài:

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
4

Điều này chỉ hoạt động với hai nghĩa đen, không phải với các biến hoặc biểu thức:

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
5

Nếu bạn muốn kết hợp các biến hoặc một biến và nghĩa đen, hãy sử dụng

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
3:

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
6

Các chuỗi có thể được lập chỉ mục [đăng ký], với ký tự đầu tiên có chỉ số 0. không có loại ký tự riêng biệt; Một ký tự chỉ đơn giản là một chuỗi có kích thước một:

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
7

Các chỉ số cũng có thể là số âm, để bắt đầu đếm từ bên phải:

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
8

Lưu ý rằng vì -0 giống như 0, các chỉ số âm bắt đầu từ -1.

Ngoài việc lập chỉ mục, cắt lát cũng được hỗ trợ. Mặc dù lập chỉ mục được sử dụng để có được các ký tự riêng lẻ, việc cắt cho phép bạn có được chuỗi con:

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
9

Chỉ số lát cắt có mặc định hữu ích; Chỉ số đầu tiên bị bỏ qua mặc định về 0, một chỉ số thứ hai bị bỏ qua mặc định theo kích thước của chuỗi được cắt.

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> [50 - 5*6] / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
0

Lưu ý cách bắt đầu luôn được bao gồm và kết thúc luôn bị loại trừ. Điều này đảm bảo rằng

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
0 luôn bằng
>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
1:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> [50 - 5*6] / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
1

Một cách để nhớ cách thức hoạt động của các lát cắt là nghĩ về các chỉ số như chỉ giữa các ký tự, với cạnh trái của ký tự đầu tiên được đánh số 0. Sau đó, cạnh phải của ký tự cuối cùng của chuỗi N ký tự có chỉ mục N, ví dụ:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> [50 - 5*6] / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
2

Hàng số đầu tiên cho vị trí của các chỉ số 0 6 6 trong chuỗi; Hàng thứ hai đưa ra các chỉ số âm tương ứng. Các lát từ I đến J bao gồm tất cả các ký tự giữa các cạnh được dán nhãn I và J, tương ứng.

Đối với các chỉ số không âm, độ dài của một lát là sự khác biệt của các chỉ số, nếu cả hai đều nằm trong giới hạn. Ví dụ, độ dài của

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
2 là 2.

Cố gắng sử dụng một chỉ mục quá lớn sẽ dẫn đến một lỗi:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> [50 - 5*6] / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
3

Tuy nhiên, các chỉ số lát cắt phạm vi được xử lý một cách duyên dáng khi được sử dụng để cắt:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> [50 - 5*6] / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
4

Chuỗi Python không thể thay đổi - chúng là bất biến. Do đó, việc gán cho một vị trí được lập chỉ mục trong chuỗi kết quả trong một lỗi:immutable. Therefore, assigning to an indexed position in the string results in an error:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> [50 - 5*6] / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
5

Nếu bạn cần một chuỗi khác, bạn nên tạo một chuỗi mới:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> [50 - 5*6] / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
6

Hàm tích hợp

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
3 trả về độ dài của chuỗi:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> [50 - 5*6] / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
7

3.1.3. Danh sáchLists¶

Python biết một số loại dữ liệu hỗn hợp, được sử dụng để nhóm các giá trị khác với nhau. Tính linh hoạt nhất là danh sách, có thể được viết làm danh sách các giá trị [mục] được phân tách bằng dấu phẩy giữa các dấu ngoặc vuông. Danh sách có thể chứa các mục thuộc các loại khác nhau, nhưng thường thì các mục đều có cùng loại.

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> [50 - 5*6] / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
8

Giống như các chuỗi [và tất cả các loại trình tự tích hợp khác], danh sách có thể được lập chỉ mục và cắt lát:sequence types], lists can be indexed and sliced:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> [50 - 5*6] / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6
9

Tất cả các hoạt động lát cắt trả về một danh sách mới có chứa các yếu tố được yêu cầu. Điều này có nghĩa là lát cắt sau trả về một bản sao nông của danh sách:shallow copy of the list:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # floored quotient * divisor + remainder
17
0

Danh sách cũng hỗ trợ các hoạt động như Concatenation:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # floored quotient * divisor + remainder
17
1

Không giống như các chuỗi, là bất biến, danh sách là một loại có thể thay đổi, tức là có thể thay đổi nội dung của chúng:immutable, lists are a mutable type, i.e. it is possible to change their content:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # floored quotient * divisor + remainder
17
2

Bạn cũng có thể thêm các mục mới ở cuối danh sách, bằng cách sử dụng phương thức

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
4 [chúng ta sẽ thấy thêm về các phương thức sau]:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # floored quotient * divisor + remainder
17
3

Việc gán cho các lát cũng có thể, và điều này thậm chí có thể thay đổi kích thước của danh sách hoặc xóa hoàn toàn nó:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # floored quotient * divisor + remainder
17
4

Chức năng tích hợp

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
3 cũng áp dụng cho danh sách:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # floored quotient * divisor + remainder
17
5

Có thể làm tổ danh sách [tạo danh sách chứa các danh sách khác], ví dụ:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # floored quotient * divisor + remainder
17
6

3.2. Những bước đầu tiên hướng tới Lập trình bàiFirst Steps Towards Programming¶

Tất nhiên, chúng ta có thể sử dụng Python cho các nhiệm vụ phức tạp hơn so với việc thêm hai và hai lại với nhau. Chẳng hạn, chúng ta có thể viết một chuỗi con ban đầu của loạt Fibonacci như sau:

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # floored quotient * divisor + remainder
17
7

Ví dụ này giới thiệu một số tính năng mới.

  • Dòng đầu tiên chứa nhiều bài tập: các biến

    >>> 'spam eggs'  # single quotes
    'spam eggs'
    >>> 'doesn\'t'  # use \' to escape the single quote...
    "doesn't"
    >>> "doesn't"  # ...or use double quotes instead
    "doesn't"
    >>> '"Yes," they said.'
    '"Yes," they said.'
    >>> "\"Yes,\" they said."
    '"Yes," they said.'
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    
    6 và
    >>> 'spam eggs'  # single quotes
    'spam eggs'
    >>> 'doesn\'t'  # use \' to escape the single quote...
    "doesn't"
    >>> "doesn't"  # ...or use double quotes instead
    "doesn't"
    >>> '"Yes," they said.'
    '"Yes," they said.'
    >>> "\"Yes,\" they said."
    '"Yes," they said.'
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    
    7 đồng thời nhận được các giá trị mới 0 và 1. Trên dòng cuối cùng, điều này được sử dụng lại, chứng minh rằng các biểu thức ở phía bên phải đều được đánh giá trước khi bất kỳ bài tập nào diễn ra. Các biểu thức bên phải được đánh giá từ bên trái sang phải.

  • Vòng lặp

    >>> 'spam eggs'  # single quotes
    'spam eggs'
    >>> 'doesn\'t'  # use \' to escape the single quote...
    "doesn't"
    >>> "doesn't"  # ...or use double quotes instead
    "doesn't"
    >>> '"Yes," they said.'
    '"Yes," they said.'
    >>> "\"Yes,\" they said."
    '"Yes," they said.'
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    
    8 thực thi miễn là điều kiện [ở đây:
    >>> 'spam eggs'  # single quotes
    'spam eggs'
    >>> 'doesn\'t'  # use \' to escape the single quote...
    "doesn't"
    >>> "doesn't"  # ...or use double quotes instead
    "doesn't"
    >>> '"Yes," they said.'
    '"Yes," they said.'
    >>> "\"Yes,\" they said."
    '"Yes," they said.'
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    
    9] vẫn đúng. Trong Python, giống như trong C, bất kỳ giá trị số nguyên khác không là đúng; Zero là sai. Điều kiện cũng có thể là một chuỗi hoặc giá trị danh sách, trên thực tế bất kỳ chuỗi nào; Bất cứ điều gì có độ dài không khác là đúng, các chuỗi trống là sai. Các thử nghiệm được sử dụng trong ví dụ là một so sánh đơn giản. Các toán tử so sánh tiêu chuẩn được viết giống như trong C:
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    >>> print['"Isn\'t," they said.']
    "Isn't," they said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
    >>> s  # without print[], \n is included in the output
    'First line.\nSecond line.'
    >>> print[s]  # with print[], \n produces a new line
    First line.
    Second line.
    
    0 [nhỏ hơn],
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    >>> print['"Isn\'t," they said.']
    "Isn't," they said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
    >>> s  # without print[], \n is included in the output
    'First line.\nSecond line.'
    >>> print[s]  # with print[], \n produces a new line
    First line.
    Second line.
    
    1 [lớn hơn],
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    >>> print['"Isn\'t," they said.']
    "Isn't," they said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
    >>> s  # without print[], \n is included in the output
    'First line.\nSecond line.'
    >>> print[s]  # with print[], \n produces a new line
    First line.
    Second line.
    
    2 [bằng],
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    >>> print['"Isn\'t," they said.']
    "Isn't," they said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
    >>> s  # without print[], \n is included in the output
    'First line.\nSecond line.'
    >>> print[s]  # with print[], \n produces a new line
    First line.
    Second line.
    
    3 [nhỏ hơn hoặc bằng],
    >>> '"Isn\'t," they said.'
    '"Isn\'t," they said.'
    >>> print['"Isn\'t," they said.']
    "Isn't," they said.
    >>> s = 'First line.\nSecond line.'  # \n means newline
    >>> s  # without print[], \n is included in the output
    'First line.\nSecond line.'
    >>> print[s]  # with print[], \n produces a new line
    First line.
    Second line.
    
    4 [lớn hơn hoặc bằng]. không bằng].

  • Cơ thể của vòng lặp được thụt vào: thụt lề là cách nhóm của Python. Tại dấu nhắc tương tác, bạn phải nhập một tab hoặc không gian cho mỗi dòng thụt lề. Trong thực tế, bạn sẽ chuẩn bị đầu vào phức tạp hơn cho Python với trình soạn thảo văn bản; Tất cả các biên tập viên văn bản tốt có một cơ sở tự động. Khi một câu lệnh ghép được nhập tương tác, nó phải được theo sau bởi một dòng trống để chỉ ra sự hoàn thành [vì trình phân tích cú pháp không thể đoán khi bạn đã nhập dòng cuối cùng]. Lưu ý rằng mỗi dòng trong một khối cơ bản phải được thụt vào cùng một lượng.

  • Hàm

    >>> tax = 12.5 / 100
    >>> price = 100.50
    >>> price * tax
    12.5625
    >>> price + _
    113.0625
    >>> round[_, 2]
    113.06
    
    1 ghi giá trị của [các] đối số được đưa ra. Nó khác với việc chỉ viết biểu thức bạn muốn viết [như chúng ta đã làm trước đó trong các ví dụ máy tính] theo cách nó xử lý nhiều đối số, số lượng điểm nổi và chuỗi. Chuỗi được in mà không có dấu ngoặc

    >>> 17 / 3  # classic division returns a float
    5.666666666666667
    >>>
    >>> 17 // 3  # floor division discards the fractional part
    5
    >>> 17 % 3  # the % operator returns the remainder of the division
    2
    >>> 5 * 3 + 2  # floored quotient * divisor + remainder
    17
    
    8

    Kết thúc đối số từ khóa có thể được sử dụng để tránh dòng mới sau đầu ra hoặc kết thúc đầu ra bằng một chuỗi khác:

    >>> 17 / 3  # classic division returns a float
    5.666666666666667
    >>>
    >>> 17 // 3  # floor division discards the fractional part
    5
    >>> 17 % 3  # the % operator returns the remainder of the division
    2
    >>> 5 * 3 + 2  # floored quotient * divisor + remainder
    17
    
    9

Chú thích

1

>>> width = 20
>>> height = 5 * 9
>>> width * height
900
8 có ưu tiên cao hơn
>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128
4,
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print['"Isn\'t," they said.']
"Isn't," they said.
>>> s = 'First line.\nSecond line.'  # \n means newline
>>> s  # without print[], \n is included in the output
'First line.\nSecond line.'
>>> print[s]  # with print[], \n produces a new line
First line.
Second line.
9 sẽ được hiểu là
# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
00 và do đó dẫn đến
# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
01. Để tránh điều này và nhận
# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
02, bạn có thể sử dụng
# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
03.

2

Không giống như các ngôn ngữ khác, các ký tự đặc biệt như

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
04 có cùng ý nghĩa với cả trích dẫn đơn [
>>> n  # try to access an undefined variable
Traceback [most recent call last]:
  File "", line 1, in 
NameError: name 'n' is not defined
8] và Double [
>>> n  # try to access an undefined variable
Traceback [most recent call last]:
  File "", line 1, in 
NameError: name 'n' is not defined
9]. Sự khác biệt duy nhất giữa hai là trong các trích dẫn duy nhất, bạn không cần phải trốn thoát
# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
07 [nhưng bạn phải trốn thoát
# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."
08] và ngược lại.

Bài Viết Liên Quan

Chủ Đề