Toán tử Matlab trong Python

Tổng / tối đa / tối thiểu của mỗi cột

sum[A, 1]
max[A, [], 1]
min[A, [], 1]

sum[A, 0]
np.amax[A, 0]
np.amin[A, 0]

sum[A, dims = 1]
maximum[A, dims = 1]
minimum[A, dims = 1]

Tổng / tối đa / tối thiểu của mỗi hàng

sum[A, 2]
max[A, [], 2]
min[A, [], 2]

sum[A, 1]
np.amax[A, 1]
np.amin[A, 1]

sum[A, dims = 2]
maximum[A, dims = 2]
minimum[A, dims = 2]

Tổng/tối đa/tối thiểu của toàn bộ ma trận

sum[A[:]]
max[A[:]]
min[A[:]]

np.sum[A]
np.amax[A]
np.amin[A]

________số 8_______

Tổng cộng / tối đa / tối thiểu theo hàng

cumsum[A, 1]
cummax[A, 1]
cummin[A, 1]

sum[A, 0]
np.amax[A, 0]
np.amin[A, 0]
0

sum[A, 0]
np.amax[A, 0]
np.amin[A, 0]
1

Tổng cộng / tối đa / tối thiểu theo cột

sum[A, 0]
np.amax[A, 0]
np.amin[A, 0]
2

sum[A, 0]
np.amax[A, 0]
np.amin[A, 0]
3

sum[A, 0]
np.amax[A, 0]
np.amin[A, 0]
4

NumPy và Matlab rất giống nhau, cả hai đều được tạo ra để tính toán khoa học và toán học. Nhưng vẫn có nhiều điểm khác biệt, numPy được tạo ra để thực hiện các phép tính khoa học với python bằng cách sử dụng mảng trong khi Matlab sử dụng ma trận. Bài viết này sẽ cung cấp cho chúng ta một ý tưởng sâu sắc về sự tương đồng và khác biệt giữa NumPy và Matlab và làm thế nào để người dùng Matlab có thể thành thạo NumPy

NumPy sử dụng cả mảng và ma trận. NumPy cung cấp một loại ma trận đặc biệt, numpy. ma trận và nó là một lớp con của ndarray [đó là mảng n chiều]. Kiểu dữ liệu cơ bản của NumPy là mảng n chiều trong đó các thao tác được thực hiện theo phần tử. người ta phải sử dụng các hàm cụ thể để thực hiện các phép toán đại số tuyến tính trong NumPy. Trong khi kiểu dữ liệu cơ bản của Matlab là mảng đa chiều của các số dấu phẩy động có độ chính xác kép. Các thao tác trên các thể hiện của các kiểu dữ liệu đó được thực hiện giống như ma trận trong đại số tuyến tính, hầu hết các hàm dựng sẵn trong Matlab đều nhận và trả về kiểu mảng đó. NumPy được thiết kế cho python, ngôn ngữ lập trình có mục đích chung và nó sử dụng chỉ mục dựa trên 0 [không]. Mặc dù ngôn ngữ kịch bản của Matlab được tạo để thực hiện các phép toán đại số tuyến tính nhưng cú pháp của Matlab cho một số thao tác mảng phức tạp hơn thì của NumPy. Ngoài ra Matlab sử dụng lập chỉ mục dựa trên 1 [một], nghĩa là phần tử đầu tiên của mảng được lập chỉ mục tại 1.  

Từ cuộc nói chuyện cơ bản này, câu hỏi đặt ra là chúng ta nên sử dụng mảng hay ma trận?

NumPy cung cấp cả lớp mảng và lớp ma trận, lớp mảng cung cấp các phép tính mảng n chiều cơ bản trong khi lớp ma trận cung cấp các phép tính đại số tuyến tính cụ thể. Một số khác biệt chính giữa đối tượng mảng và đối tượng ma trận là

MATLAB® được biết đến rộng rãi như một môi trường chất lượng cao cho mọi công việc liên quan đến mảng, ma trận hoặc đại số tuyến tính. Python mới hơn trong lĩnh vực này nhưng ngày càng trở nên phổ biến cho các nhiệm vụ tương tự. Như bạn sẽ thấy trong bài viết này, Python có tất cả sức mạnh tính toán của MATLAB cho các nhiệm vụ khoa học và giúp phát triển các ứng dụng mạnh mẽ một cách nhanh chóng và dễ dàng. Tuy nhiên, có một số khác biệt quan trọng khi so sánh MATLAB với Python mà bạn cần tìm hiểu để chuyển đổi hiệu quả

Trong bài viết này, bạn sẽ học cách

  • Đánh giá sự khác biệt của việc sử dụng MATLAB so với Python
  • Thiết lập môi trường cho Python sao chép phần lớn các hàm MATLAB
  • Chuyển đổi tập lệnh từ MATLAB sang Python
  • Tránh các vấn đề phổ biến mà bạn có thể gặp phải khi chuyển từ MATLAB sang Python
  • Viết mã trông giống như Python

Tiền thưởng miễn phí. hướng dẫn bạn các hướng dẫn, video và sách tốt nhất để cải thiện kỹ năng NumPy của bạn

MATLAB so với Python. So sánh các tính năng và triết lý

Python là ngôn ngữ lập trình đa năng, cấp cao được thiết kế để con người dễ sử dụng khi hoàn thành tất cả các loại nhiệm vụ. Python được tạo bởi Guido van Rossum và phát hành lần đầu tiên vào đầu những năm 1990. Python là một ngôn ngữ trưởng thành được phát triển bởi hàng trăm cộng tác viên trên khắp thế giới

Python được sử dụng bởi các nhà phát triển làm việc trên các dự án nhỏ, cá nhân cho đến một số công ty internet lớn nhất trên thế giới. Python không chỉ chạy Reddit và Dropbox mà còn được viết bằng Python. Ngoài ra, Django Framework dựa trên Python chạy Instagram và nhiều trang web khác. Về mặt khoa học và kỹ thuật, dữ liệu để tạo ra bức ảnh lỗ đen năm 2019 đã được xử lý bằng Python và các công ty lớn như Netflix sử dụng Python trong công việc phân tích dữ liệu của họ

Ngoài ra còn có một sự khác biệt triết học quan trọng trong so sánh MATLAB với Python. MATLAB là phần mềm độc quyền, mã nguồn đóng. Đối với hầu hết mọi người, giấy phép sử dụng MATLAB khá đắt, điều đó có nghĩa là nếu bạn có mã trong MATLAB thì chỉ những người có đủ khả năng mua giấy phép mới có thể chạy nó. Ngoài ra, người dùng bị tính phí cho mỗi hộp công cụ bổ sung mà họ muốn cài đặt để mở rộng chức năng cơ bản của MATLAB. Ngoài chi phí, ngôn ngữ MATLAB được phát triển độc quyền bởi Mathworks. Nếu Mathworks ngừng kinh doanh, thì MATLAB sẽ không thể phát triển được nữa và cuối cùng có thể ngừng hoạt động

Mặt khác, Python là phần mềm mã nguồn mở và miễn phí. Bạn không chỉ có thể tải xuống Python miễn phí mà còn có thể tải xuống, xem và sửa đổi mã nguồn. Đây là một lợi thế lớn cho Python vì nó có nghĩa là bất kỳ ai cũng có thể tiếp tục phát triển ngôn ngữ này nếu các nhà phát triển hiện tại không thể tiếp tục vì một lý do nào đó.

Nếu bạn là nhà nghiên cứu hoặc nhà khoa học, thì việc sử dụng phần mềm nguồn mở có một số lợi ích khá lớn. Paul Romer, người đoạt giải Nobel Kinh tế năm 2018, là một người mới chuyển đổi sang Python. Theo ước tính của anh ấy, việc chuyển sang phần mềm nguồn mở nói chung và Python nói riêng đã mang lại tính toàn vẹn và trách nhiệm giải trình cao hơn cho nghiên cứu của anh ấy. Điều này là do tất cả các mã có thể được chia sẻ và chạy bởi bất kỳ độc giả quan tâm nào. giáo sư. Romer đã viết một bài báo xuất sắc, Jupyter, Mathicala, and the Future of the Research Paper, về trải nghiệm của anh ấy với phần mềm nguồn mở

Hơn nữa, vì Python được cung cấp miễn phí nên nhiều đối tượng hơn có thể sử dụng mã do bạn phát triển. Như bạn sẽ thấy ở phần sau của bài viết, Python có một cộng đồng tuyệt vời có thể giúp bạn bắt đầu với ngôn ngữ này và nâng cao kiến ​​thức của bạn. Có hàng chục ngàn hướng dẫn, bài báo và sách về phát triển phần mềm Python. Dưới đây là một số để giúp bạn bắt đầu

  • Giới thiệu về Python3
  • Lộ trình học Python 3 cơ bản

Ngoài ra, với rất nhiều nhà phát triển trong cộng đồng, có hàng trăm nghìn gói miễn phí để hoàn thành nhiều tác vụ mà bạn muốn thực hiện với Python. Bạn sẽ tìm hiểu thêm về cách nhận các gói này sau trong bài viết này

Giống như MATLAB, Python là một ngôn ngữ thông dịch. Điều này có nghĩa là mã Python có thể được chuyển giữa tất cả các nền tảng hệ điều hành chính và kiến ​​trúc CPU hiện có, chỉ với những thay đổi nhỏ cần thiết cho các nền tảng khác nhau. Có các bản phân phối Python cho CPU máy tính để bàn và máy tính xách tay và bộ vi điều khiển như Adaf nhung. Python cũng có thể nói chuyện với các bộ vi điều khiển khác như Arduino với giao diện lập trình đơn giản gần như giống hệt nhau bất kể hệ điều hành máy chủ là gì

Vì tất cả những lý do này và nhiều lý do khác, Python là một lựa chọn tuyệt vời để thay thế MATLAB làm ngôn ngữ lập trình bạn chọn. Bây giờ bạn đã bị thuyết phục để dùng thử Python, hãy đọc tiếp để tìm hiểu cách tải nó trên máy tính của bạn và cách chuyển đổi từ MATLAB

Ghi chú. GNU Octave là một bản sao mã nguồn mở và miễn phí của MATLAB. Theo nghĩa này, GNU Octave có cùng những lợi thế triết học mà Python có xung quanh khả năng tái tạo mã và quyền truy cập vào phần mềm

Cú pháp của Octave hầu như tương thích với cú pháp MATLAB, vì vậy nó cung cấp một lộ trình học tập ngắn cho các nhà phát triển MATLAB muốn sử dụng phần mềm mã nguồn mở. Tuy nhiên, Octave không thể phù hợp với cộng đồng của Python hoặc số lượng các loại ứng dụng khác nhau mà Python có thể phục vụ, vì vậy chúng tôi khuyên bạn nên chuyển toàn bộ sang Python

Ngoài ra, trang web này được gọi là Real Python, không phải Real Octave 😀

Loại bỏ các quảng cáo

Thiết lập môi trường của bạn cho Python

Trong phần này, bạn sẽ học

  • Cách cài đặt Python trên máy tính của bạn để chuyển đổi liền mạch từ MATLAB
  • Cách cài đặt thay thế cho môi trường phát triển tích hợp MATLAB
  • Cách sử dụng phần mềm thay thế cho MATLAB trên máy tính

Bắt Python qua Anaconda

Python có thể được tải xuống từ một số nguồn khác nhau, được gọi là bản phân phối. Chẳng hạn, Python mà bạn có thể tải xuống từ trang web chính thức của Python là một bản phân phối. Một bản phân phối Python rất phổ biến khác, đặc biệt cho các ứng dụng toán học, khoa học, kỹ thuật và khoa học dữ liệu, là bản phân phối Anaconda

Có hai lý do chính mà Anaconda rất phổ biến

  1. Anaconda phân phối các gói dựng sẵn cho Windows, macOS và Linux, điều đó có nghĩa là quá trình cài đặt thực sự dễ dàng và giống nhau cho cả ba nền tảng chính

  2. Anaconda bao gồm tất cả các gói phổ biến nhất cho khối lượng công việc loại khoa học dữ liệu và kỹ thuật trong một trình cài đặt duy nhất

Với mục đích tạo một môi trường rất giống với MATLAB, bạn nên tải xuống và cài đặt Anaconda. Khi viết bài này, có hai phiên bản chính của Python. Trăn 2 và Trăn 3. Bạn chắc chắn nên cài đặt phiên bản Anaconda cho Python 3, vì Python 2 sẽ không được hỗ trợ sau ngày 1 tháng 1 năm 2020. Trăn 3. 7 là phiên bản mới nhất tại thời điểm viết bài này, nhưng Python 3. 8 sẽ ra mắt vài tháng sau khi bài viết này được xuất bản. hoặc 3. 7 hoặc 3. 8 sẽ hoạt động tương tự với bạn, vì vậy hãy chọn phiên bản mới nhất bạn có thể

Khi bạn đã tải xuống trình cài đặt Anaconda, bạn có thể làm theo các quy trình thiết lập mặc định tùy thuộc vào nền tảng của bạn. Bạn nên cài đặt Anaconda trong một thư mục không yêu cầu quyền quản trị viên để sửa đổi, đây là cài đặt mặc định trong trình cài đặt

Sau khi cài đặt Anaconda, có một vài chương trình cụ thể mà bạn nên biết. Cách dễ nhất để khởi chạy ứng dụng là sử dụng Anaconda Navigator. Trên Windows, bạn có thể tìm thấy mục này trong Menu Bắt đầu và trên macOS, bạn có thể tìm thấy mục này trong Launchpad. Đây là ảnh chụp màn hình của Anaconda Navigator trên Windows

Trong ảnh chụp màn hình, bạn có thể thấy một số ứng dụng đã cài đặt, bao gồm JupyterLab, Jupyter Notebook và Spyder, mà bạn sẽ tìm hiểu thêm về sau trong hướng dẫn này

Trên Windows còn một ứng dụng khác mà bạn nên biết. Đây được gọi là Dấu nhắc Anaconda và là dấu nhắc lệnh được thiết lập đặc biệt để hoạt động với

In [2]: import antigravity
32 trên Windows. Nếu bạn muốn nhập
In [2]: import antigravity
32 lệnh trong thiết bị đầu cuối, thay vì sử dụng GUI của Bộ điều hướng, thì bạn nên sử dụng Dấu nhắc Anaconda trên Windows

Trên macOS, bạn có thể sử dụng bất kỳ ứng dụng đầu cuối nào, chẳng hạn như Terminal mặc định. app hoặc iTerm2 để truy cập

In [2]: import antigravity
32 từ dòng lệnh. Trên Linux, bạn có thể sử dụng trình giả lập thiết bị đầu cuối mà bạn chọn và trình giả lập cụ thể nào được cài đặt sẽ phụ thuộc vào bản phân phối Linux của bạn

Lưu ý thuật ngữ. Bạn có thể hơi bối rối về

In [2]: import antigravity
32 so với Anaconda. Sự khác biệt là tinh tế nhưng quan trọng. Anaconda là một bản phân phối của Python bao gồm nhiều gói cần thiết cho các loại công việc khoa học.
In [2]: import antigravity
32 là phần mềm quản lý gói đa nền tảng đi kèm với bản phân phối Anaconda của Python.
In [2]: import antigravity
32 là phần mềm mà bạn sử dụng để xây dựng, cài đặt và gỡ bỏ các gói trong bản phân phối Anaconda

Bạn có thể đọc tất cả về cách sử dụng

In [2]: import antigravity
32 trong Thiết lập Python cho Machine Learning trên Windows. Mặc dù hướng dẫn đó tập trung vào Windows nhưng các lệnh
In [2]: import antigravity
32 giống nhau trên Windows, macOS và Linux

Python cũng bao gồm một cách khác để cài đặt các gói, được gọi là

In [2]: import antigravity
40. Nếu bạn đang sử dụng Anaconda, bạn nên luôn ưu tiên cài đặt các gói bằng cách sử dụng
In [2]: import antigravity
32 bất cứ khi nào có thể. Tuy nhiên, đôi khi, một gói chỉ có sẵn với
In [2]: import antigravity
40 và đối với những trường hợp đó, bạn có thể đọc Pip là gì?

Có được một môi trường phát triển tích hợp

Một trong những ưu điểm lớn của MATLAB là nó bao gồm một môi trường phát triển với phần mềm. Đây là cửa sổ mà bạn thường làm việc nhất. Có một bảng điều khiển ở trung tâm nơi bạn có thể nhập lệnh, trình khám phá biến ở bên phải và danh sách thư mục ở bên trái

Không giống như MATLAB, bản thân Python không có môi trường phát triển mặc định. Tùy thuộc vào mỗi người dùng để tìm một cái phù hợp với nhu cầu của họ. May mắn thay, Anaconda đi kèm với hai môi trường phát triển tích hợp [IDE] khác nhau tương tự như MATLAB IDE để giúp quá trình chuyển đổi của bạn trở nên liền mạch. Chúng được gọi là Spyder và JupyterLab. Trong hai phần tiếp theo, bạn sẽ thấy phần giới thiệu chi tiết về Spyder và tổng quan ngắn gọn về JupyterLab

gián điệp

Spyder là một IDE dành cho Python được phát triển dành riêng cho công việc Python khoa học. Một trong những điều thực sự thú vị về Spyder là nó có một chế độ được thiết kế dành riêng cho những người như bạn đang chuyển đổi từ MATLAB sang Python. Bạn sẽ thấy rằng một lát sau

Trước tiên, bạn nên mở Spyder. Nếu bạn đã làm theo hướng dẫn trong phần trước, bạn có thể mở Spyder bằng Anaconda Navigator. Chỉ cần tìm biểu tượng Spyder và nhấp vào nút Launch. Bạn cũng có thể khởi chạy Spyder từ Menu Bắt đầu nếu đang sử dụng Windows hoặc từ Launchpad nếu đang sử dụng macOS

Thay đổi bố cục cửa sổ mặc định trong Spyder

Cửa sổ mặc định trong Spyder trông như hình bên dưới. Đây là phiên bản 3. 3. 4 của Spyder chạy trên Windows 10. Nó sẽ trông khá giống trên macOS hoặc Linux

Trước khi xem qua giao diện người dùng, bạn có thể làm cho giao diện trông giống MATLAB hơn một chút. Trong menu View → Window layouts chọn MATLAB layout. Điều đó sẽ tự động thay đổi cửa sổ để nó có cùng các khu vực mà bạn đã sử dụng từ MATLAB, được chú thích trên hình bên dưới

Ở trên cùng bên trái của cửa sổ là File Explorer hoặc danh sách thư mục. Trong khung này, bạn có thể tìm thấy các tệp mà bạn muốn chỉnh sửa hoặc tạo các tệp và thư mục mới để làm việc với

Ở trung tâm trên cùng là trình chỉnh sửa tệp. Trong trình chỉnh sửa này, bạn có thể làm việc trên các tập lệnh Python mà bạn muốn lưu để chạy lại sau này. Theo mặc định, trình chỉnh sửa sẽ mở một tệp có tên

In [2]: import antigravity
43 nằm trong thư mục cấu hình của Spyder. Tệp này có nghĩa là một nơi tạm thời để dùng thử mọi thứ trước khi bạn lưu chúng vào một tệp ở một nơi khác trên máy tính của bạn

Ở trung tâm dưới cùng là bảng điều khiển. Giống như trong MATLAB, bảng điều khiển là nơi bạn có thể chạy các lệnh để xem chúng làm gì hoặc khi bạn muốn gỡ lỗi một số mã. Các biến được tạo trong bảng điều khiển sẽ không được lưu nếu bạn đóng Spyder và mở lại. Bảng điều khiển về mặt kỹ thuật chạy IPython theo mặc định

Bất kỳ lệnh nào bạn nhập vào bảng điều khiển sẽ được ghi vào tệp lịch sử ở ngăn dưới cùng bên phải của cửa sổ. Furthermore, any variables that you create in the console will be shown in the variable explorer in the top right pane

Notice that you can adjust the size of any pane by putting your mouse over the divider between panes, clicking, and dragging the edge to the size that you want. You can close any of the panes by clicking the x in the top of the pane

You can also break any pane out of the main window by clicking the button that looks like two windows in the top of the pane, right next to the x that closes the pane. When a pane is broken out of the main window, you can drag it around and rearrange it however you want. If you want to put the pane back in the main window, drag it with the mouse so a transparent blue or gray background appears and the neighboring panes resize, then let go and the pane will snap into place

Once you have the panes arranged exactly how you want, you can ask Spyder to save the layout. Go to the View menu and find the Window layouts flyout again. Then click Save current layout and give it a name. This lets you reset to your preferred layout at any time if something gets changed by accident. You can also reset to one of the default configurations from this menu

Running Statements in the Console in Spyder

In this section, you’re going to be writing some simple Python commands, but don’t worry if you don’t quite understand what they mean yet. You’ll learn more about Python syntax a little later on in this article. What you want to do right now is get a sense for how Spyder’s interface is similar to and different from the MATLAB interface

You’ll be working a lot with the Spyder console in this article, so you should learn about how it works. In the console, you’ll see a line that starts with

In [2]: import antigravity
44, for input line 1. Spyder [really, the IPython console] numbers all of the input lines that you type. Since this is the first input you’re typing, the line number is 1. In the rest of this article, you’ll see references to “input line X,” where X is the number in the square brackets

One of the first things I like to do with folks who are new to Python is show them the Zen of Python. This short poem gives you a sense of what Python is all about and how to approach working with Python

To see the Zen of Python, type

In [2]: import antigravity
45 on input line 1 and then run the code by pressing Enter . You’ll see an output like below.

>>>

In [1]: import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

This code has

In [2]: import antigravity
45 on input line 1. The output from running
In [2]: import antigravity
45 is to print the Zen of Python onto the console. We’ll return to several of the stanzas in this poem later on in the article

In many of the code blocks in this article, you’ll see three greater-than signs [

In [2]: import antigravity
48] in the top right of the code block. If you click that, it will remove the input prompt and any output lines, so you can copy and paste the code right into your console

Many Pythonistas maintain a healthy sense of humor. This is displayed in many places throughout the language, including the Zen of Python. For another one, in the Spyder console, type the following code, followed by Enter to run it.

>>>

In [2]: import antigravity

That statement will open your web browser to the webcomic called XKCD, specifically comic #353, where the author has discovered that Python has given him the ability to fly

You’ve now successfully run your first two Python statements. Congratulations 😃🎉

If you look at the History Log, you should see the first two commands you typed in the console [

In [2]: import antigravity
45 and
In [2]: import antigravity
50]. Let’s define some variables and do some basic arithmetic now. In the console, type the following statements, pressing Enter after each one.

>>>

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30

In this code, you defined 3 variables.

In [2]: import antigravity
51,
In [2]: import antigravity
52, and
In [2]: import antigravity
53. You assigned
In [2]: import antigravity
51 the value 10,
In [2]: import antigravity
52 the value 20, and
In [2]: import antigravity
53 the sum of
In [2]: import antigravity
51 and
In [2]: import antigravity
52. Then you showed the value of the
In [2]: import antigravity
53 variable by writing it as the only thing on the input line. The output from that statement is shown on the next
In [2]: import antigravity
60 line, and the number on the
In [2]: import antigravity
60 line matches the associated
In [2]: import antigravity
62 line

There are two main things for you to notice in these commands

  1. If a statement does not include an assignment [with an

    In [2]: import antigravity
    
    63], it is printed onto an
    In [2]: import antigravity
    
    60 line. In MATLAB, you would need to include a semicolon to suppress the output even from assignment statements, but that is not necessary in Python

  2. On input lines 3, 4, and 5, the Variable explorer in the top right pane updated

After you run these three commands, your Variable explorer should look like the image below

Trong hình ảnh này, bạn có thể thấy một bảng có bốn cột

  1. Name shows the name that you gave to
    In [2]: import antigravity
    
    51,
    In [2]: import antigravity
    
    52, and
    In [2]: import antigravity
    
    53
  2. Type shows the Python type of the variable, in this case, all
    In [2]: import antigravity
    
    68 for integer numbers
  3. Size shows the size of the data stored variable, which is more useful for lists and other data structures
  4. Value shows the current value of the variable

Running Code in Files in Spyder

The last stop in our brief tour of the Spyder interface is the File editor pane. In this pane, you can create and edit Python scripts and run them using the console. By default, Spyder creates a temporary file called

In [2]: import antigravity
43 which is intended for you to temporarily store commands as you’re working before you move or save them in another file

Let’s write some code into the

In [2]: import antigravity
43 file and see how to run it. The file starts with the following code, which you can just leave in place

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""

In this code, you can see two Python syntax structures

  • Line 1 has a comment. In Python, the comment character is the hash or pound sign [

    In [2]: import antigravity
    
    71]. MATLAB uses the percent symbol [
    In [2]: import antigravity
    
    72] as the comment character. Anything following the hash on the line is a comment and is usually ignored by the Python interpreter

  • Starting on line 2 is a string that provides some context for the contents of the file. This is often referred to as a documentation string or for short. You’ll learn more about docstrings in

Now you can start adding code to this file. Starting on line 8 in

In [2]: import antigravity
43, enter the following code that is similar to what you already typed in the console

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5

Then, there are three ways to run the code

  1. You can use the F5 keyboard shortcut to run the file just like in MATLAB.
  2. You can click the green right-facing triangle in the menu bar just above the Editor and File explorer panes
  3. You can use the Run → Run menu option

The first time you run a file, Spyder will open a dialog window asking you to confirm the options you want to use. For this test, the default options are fine and you can click Run at the bottom of the dialog box

This will automatically execute the following code in the console

>>>

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']

This code will run the file that you were working on. Notice that running the file added three variables into the Variable explorer.

In [2]: import antigravity
74,
In [2]: import antigravity
75, and
In [2]: import antigravity
76. These are the three variables that you defined in the file. You will also see
In [2]: import antigravity
77 added to the History log

In Spyder, you can also create code cells that can be run individually. To create a code cell, add a line that starts with

In [2]: import antigravity
78 into the file open in the editor

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]

In this code, you have created your first code cell on line 11 with the

In [2]: import antigravity
78 code. What follows is a line comment and is ignored by Python. On line 12, you are assigning
In [2]: import antigravity
80 to have the value 42 and then line 13 assigns
In [2]: import antigravity
81 to be
In [2]: import antigravity
80 times two. Line 15 starts another code cell that can be executed separately from the first one

To execute the code cells, click the Run Current Cell or Run Current Cell and Go to the Next One buttons next to the generic Run button in the toolbar. You can also use the keyboard shortcuts Ctrl + Enter to run the current cell and leave it selected, or Shift + Enter to run the current cell and select the next cell.

Spyder also offers easy-to-use debugging features, just like in MATLAB. You can double-click any of the line numbers in the Editor to set a breakpoint in your code. You can run the code in debug mode using the blue right-facing triangle with two vertical lines from the toolbar, or the Ctrl + F5 keyboard shortcut. This will pause execution at any breakpoints you specify and open the

In [2]: import antigravity
83 debugger in the console which is an IPython-enhanced way to run the Python debugger
In [2]: import antigravity
84. You can read more in Python Debugging With pdb.

Summarizing Your Experience in Spyder

Now you have the basic tools to use Spyder as a replacement for the MATLAB integrated development environment. You know how to run code in the console or type code into a file and run the file. You also know where to look to see your directories and files, the variables that you’ve defined, and the history of the commands you typed

Once you’re ready to start organizing your code into modules and packages, you can check out the following resources

  • Python Modules and Packages – An Introduction
  • How to Publish an Open-Source Python Package to PyPI
  • How to Publish Your Own Python Package to PyPI

Spyder is a really big piece of software, and you’ve only just scratched the surface. You can learn a lot more about Spyder by reading the official documentation, the troubleshooting and FAQ guide, and the Spyder wiki

Loại bỏ các quảng cáo

JupyterLab

JupyterLab is an IDE developed by Project Jupyter. You may have heard of Jupyter Notebooks, particularly if you’re a data scientist. Well, JupyterLab is the next iteration of the Jupyter Notebook. Although at the time of this writing JupyterLab is still in beta, Project Jupyter expects that JupyterLab will eventually replace the current Notebook server interface. However, JupyterLab is fully compatible with existing Notebooks so the transition should be fairly seamless

JupyterLab comes preinstalled with Anaconda, so you can launch it from the Anaconda Navigator. Find the JupyterLab box and click Launch. This will open your web browser to the address

In [2]: import antigravity
85

The main JupyterLab window is shown in the picture below

There are two main sections of the interface

  1. Ở bên trái là Trình khám phá tệp cho phép bạn mở tệp từ máy tính của mình
  2. On the right side of the window is how you can open create new Notebook files, work in an IPython console or system terminal, or create a new text file

If you’re interested in learning more about JupyterLab, you can read a lot more about the next evolution of the Notebook in the blog post announcing the beta release or in the JupyterLab documentation. Bạn cũng có thể tìm hiểu về giao diện Notebook trong Jupyter Notebook. An Introduction and the Using Jupyter Notebooks course. One neat thing about the Jupyter Notebook-style document is that the code cells you created in Spyder are very similar to the code cells in a Jupyter Notebook

Learning About Python’s Mathematical Libraries

Now you’ve got Python on your computer and you’ve got an IDE where you feel at home. Vậy làm thế nào để bạn tìm hiểu về cách thực sự hoàn thành một nhiệm vụ trong Python? . Với Python, bạn thường sẽ nhận được kết quả tìm kiếm tốt hơn nếu bạn có thể cụ thể hơn một chút trong truy vấn của mình thay vì chỉ bao gồm

In [2]: import antigravity
87

Trong phần này, bạn sẽ thực hiện bước tiếp theo để thực sự cảm thấy thoải mái với Python bằng cách tìm hiểu về cách chức năng Python được chia thành nhiều thư viện. Bạn cũng sẽ tìm hiểu chức năng của từng thư viện để bạn có thể nhận được kết quả tốt nhất với các tìm kiếm của mình

Python đôi khi được gọi là ngôn ngữ có pin. Điều này có nghĩa là hầu hết các chức năng quan trọng bạn cần đã được bao gồm khi bạn cài đặt Python. For instance, Python has built-in

In [2]: import antigravity
88 and
In [2]: import antigravity
89 libraries that include the basic operations

Tuy nhiên, đôi khi bạn muốn làm điều gì đó không có trong ngôn ngữ. Một trong những lợi thế lớn của Python là người khác có thể đã làm bất cứ điều gì bạn cần làm và xuất bản mã để hoàn thành nhiệm vụ đó. Có hàng trăm nghìn gói miễn phí và có sẵn công khai mà bạn có thể dễ dàng cài đặt để thực hiện các tác vụ khác nhau. Những phạm vi này từ xử lý tệp PDF đến xây dựng và lưu trữ một trang web tương tác để làm việc với các chức năng khoa học và toán học được tối ưu hóa cao

Làm việc với mảng hoặc ma trận, tối ưu hóa hoặc vẽ biểu đồ yêu cầu cài đặt thêm thư viện. May mắn thay, nếu bạn cài đặt Python bằng trình cài đặt Anaconda, các thư viện này đã được cài đặt sẵn và bạn không cần phải lo lắng. Ngay cả khi bạn không sử dụng Anaconda, chúng thường khá dễ cài đặt cho hầu hết các hệ điều hành

Tập hợp các thư viện quan trọng mà bạn cần chuyển từ MATLAB thường được gọi là ngăn xếp SciPy. At the base of the stack are libraries that provide fundamental array and matrix operations [NumPy], integration, optimization, signal processing, and linear algebra functions [SciPy], and plotting [Matplotlib]. Other libraries that build on these to provide more advanced functionality include Pandas, scikit-learn, SymPy, and more

NumPy [Numerical Python]

NumPy is probably the most fundamental package for scientific computing in Python. It provides a highly efficient interface to create and interact with multi-dimensional arrays. Nearly every other package in the SciPy stack uses or integrates with NumPy in some way

NumPy arrays are the equivalent to the basic array data structure in MATLAB. With NumPy arrays, you can do things like inner and outer products, transposition, and element-wise operations. NumPy also contains a number of useful methods for reading text and binary data files, fitting polynomial functions, many mathematical functions [sine, cosine, square root, and so on], and generating random numbers

The performance-sensitive parts of NumPy are all written in the C language, so they are very fast. NumPy can also take advantage of optimized linear algebra libraries such as Intel’s MKL or OpenBLAS to further increase performance

Note

Real Python has several articles that cover how you can use NumPy to speed up your Python code

  • Look Ma, No For-Loops. Array Programming With NumPy
  • NumPy arange[]. How to Use np. arange[]
  • Python Histogram Plotting. NumPy, Matplotlib, Pandas & Seaborn

Loại bỏ các quảng cáo

SciPy [Scientific Python]

The SciPy package [as distinct from the SciPy stack] is a library that provides a huge number of useful functions for scientific applications. If you need to do work that requires optimization, linear algebra or sparse linear algebra, discrete Fourier transforms, signal processing, physical constants, image processing, or numerical integration, then SciPy is the library for you. Since SciPy implements so many different features, it’s almost like having access to a bunch of the MATLAB toolboxes in one package

SciPy relies heavily on NumPy arrays to do its work. Like NumPy, many of the algorithms in SciPy are implemented in C or Fortran, so they are also very fast. Also like NumPy, SciPy can take advantage of optimized linear algebra libraries to further improve performance

Matplotlib [MATLAB-like Plotting Library]

Matplotlib is a library to produce high-quality and interactive two-dimensional plots. Matplotlib is designed to provide a plotting interface that is similar to the

In [2]: import antigravity
90 function in MATLAB, so people switching from MATLAB should find it somewhat familiar. Although the core functions in Matplotlib are for 2-D data plots, there are extensions available that allow plotting in three dimensions with the mplot3d package, plotting geographic data with cartopy, and many more listed in the Matplotlib documentation

Note

Here are some more resources on Matplotlib

  • Python Plotting With Matplotlib [Guide]
  • Matplotlib Examples
  • Matplotlib Gallery

Other Important Python Libraries

With NumPy, SciPy, and Matplotlib, you can switch a lot of your MATLAB code to Python. But there are a few more libraries that might be helpful to know about

  • Pandas provides a DataFrame, an array with the ability to name rows and columns for easy access
  • SymPy provides symbolic mathematics and a computer algebra system
  • scikit-learn provides many functions related to machine learning tasks
  • scikit-image provides functions related to image processing, compatible with the similar library in SciPy
  • Tensorflow provides a common platform for many machine learning tasks
  • Keras provides a library to generate neural networks
  • multiprocessing provides a way to perform multi-process based parallelism. It’s built into Python
  • Pint provides a unit library to conduct automatic conversion between physical unit systems
  • PyTables provides a reader and writer for HDF5 format files
  • PyMC3 provides Bayesian statistical modeling and probabilistic machine learning functionality

Syntax Differences Between MATLAB® and Python

In this section, you’ll learn how to convert your MATLAB code into Python code. You’ll learn about the main syntax differences between MATLAB and Python, see an overview of basic array operations and how they differ between MATLAB and Python, and find out about some ways to attempt automatic conversion of your code

The biggest technical difference between MATLAB and Python is that in MATLAB, everything is treated as an array, while in Python everything is a more general object. For instance, in MATLAB, strings are arrays of characters or arrays of strings, while in Python, strings have their own type of object called

In [2]: import antigravity
91. This has profound consequences for how you approach coding in each language, as you’ll see below

Với cách đó, chúng ta hãy bắt đầu. To help you, the sections below are organized into groups based on how likely you are to run into that syntax

You Will Probably See This Syntax

The examples in this section represent code that you are very likely to see in the wild. These examples also demonstrate some of the more basic Python language features. You should make sure that you have a good grasp of these examples before moving on

Comments Start With
In [2]: import antigravity
71 in Python

In MATLAB, a comment is anything that follows a percent sign [

In [2]: import antigravity
72] on a line. In Python, comments are anything that follow the hash or pound sign [
In [2]: import antigravity
71]. You already saw a Python comment in the earlier section about Spyder. In general, the Python interpreter ignores the content of comments, just like the MATLAB interpreter, so you can write whatever content you want in the comment. One exception to this rule in Python is the example you saw earlier in the section about Spyder

# -*- coding: utf-8 -*-

When the Python interpreter reads this line, it will set the encoding that it uses to read the rest of the file. This comment must appear in one of the first two lines of the file to be valid

Another difference between MATLAB and Python is in how inline documentation is written. In MATLAB, documentation is written at the start of a function in a comment, like the code sample below

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS

However, Python does not use comments in this way. Instead, Python has an idea called documentation strings or docstrings for short. In Python, you would document the MATLAB function shown above like this

def addition[num_1, num_2]:
    """Adds two numbers together.

    Example
    -------
    >>> total = addition[10, 20]
    >>> total
    30

    """

Notice in this code that the docstring is between two sets of three quote characters [

In [2]: import antigravity
95]. This allows the docstring to run onto multiple lines with the whitespace and newlines preserved. The triple quote characters are a special case of . Don’t worry too much about the syntax of defining a function yet. You’ll see more about that

Whitespace at the Beginning of a Line Is Significant in Python

When you write code in MATLAB, blocks like

In [2]: import antigravity
96 statements,
In [2]: import antigravity
97 and
In [2]: import antigravity
98 loops, and function definitions are finished with the
In [2]: import antigravity
99 keyword. It is generally considered a good practice in MATLAB to indent the code within the blocks so that the code is visually grouped together, but it is not syntactically necessary

For example, the following two blocks of code are functionally equivalent in MATLAB

In [2]: import antigravity
0

In this code, you are first creating

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
00 to store the value 10 and then checking whether the value of
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
00 is equal to 10. If it is, you are displaying the phrase
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
02 on the console from line 2. Otherwise, the
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
03 clause will kick in and display
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
04. Of course, if you run this code, you will see the
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
02 output and then
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
06

Now you should modify your code so it looks like the sample below

In [2]: import antigravity
1

In this code, you have only changed lines 3 and 5 by adding some spaces or indentation in the front of the line. The code will perform identically to the previous example code, but with the indentation, it is much easier to tell what code goes in the

In [2]: import antigravity
96 part of the statement and what code is in the
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
03 part of the statement

In Python, indentation at the start of a line is used to delimit the beginning and end of class and function definitions,

In [2]: import antigravity
96 statements, and
In [2]: import antigravity
97 and
In [2]: import antigravity
98 loops. There is no
In [2]: import antigravity
99 keyword in Python. This means that indentation is very important in Python

In addition, in Python the definition line of an

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
13 statement, a
In [2]: import antigravity
97 or
In [2]: import antigravity
98 loop, a function, or a class is ended by a colon. In MATLAB, the colon is not used to end the line

Consider this code example

In [2]: import antigravity
2

On the first line, you are defining

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
00 and setting its value to 10. On line 2, writing
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
17 tests the value of
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
00 compared to 10. Notice the colon at the end of the line

Next, line 3 must be indented in Python’s syntax. On that line, you are using

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19 to display some output to the console, in a similar way to
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
20 in MATLAB. You’ll read more about
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19 versus
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
20

On line 4, you are starting the

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
03 block. Notice that the
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
24 in the
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
03 keyword is vertically aligned with the
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
26 in the
In [2]: import antigravity
96 keyword, and the line is ended by a colon. Because the
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
03 is dedented relative to
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19 on line 3, and because it is aligned with the
In [2]: import antigravity
96 keyword, Python knows that the code within the
In [2]: import antigravity
96 part of the block has finished and the
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
03 part is starting. Line 5 is indented by one level, so it forms the block of code to be executed when the
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
03 statement is satisfied

Lastly, on line 6 you are printing a statement from outside the

In [2]: import antigravity
96/
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
03 block. This statement will be printed regardless of the value of
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
00. Notice that the
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
37 in
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19 is vertically aligned with the
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
26 in
In [2]: import antigravity
96 and the
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
24 in
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
03. This is how Python knows that the code in the
In [2]: import antigravity
96/
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
03 block has ended. If you run the code above, Python will display
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
02 followed by
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
06

Now you should modify the code above to remove the indentation and see what happens. If you try to type the code without indentation into the Spyder/IPython console, you will get an

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
47

>>>

In [2]: import antigravity
3

In this code, you first set the value of

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
00 to 10 and then tried to write the
In [2]: import antigravity
96 statement without indentation. In fact, the IPython console is smart and automatically indents the line after the
In [2]: import antigravity
96 statement for you, so you’ll have to delete the indentation to produce this error

When you’re indenting your code, the official Python style guide called recommends using 4 space characters to represent one indentation level. Most text editors that are set up to work with Python files will automatically insert 4 spaces if you press the Tab key on your keyboard. You can choose to use the tab character for your code if you want, but you shouldn’t mix tabs and spaces or you’ll probably end up with a

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
51 if the indentation becomes mismatched.

Conditional Statements Use
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
52 in Python

In MATLAB, you can construct conditional statements with

In [2]: import antigravity
96,
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
54, and
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
03. These kinds of statements allow you to control the flow of your program in response to different conditions

You should try this idea out with the code below, and then compare the example of MATLAB vs Python for conditional statements

In [2]: import antigravity
4

Trong khối mã này, bạn đang xác định

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
00 bằng 10. Then you are checking if the value of
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
00 is 10, and if it is, using
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
20 to print output to the console. If
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
00 is 20, you are printing a different statement, and if
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
00 is neither 10 nor 20, you are printing the third statement

In Python, the

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
54 keyword is replaced with
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
52

In [2]: import antigravity
5

This code block is functionally equivalent to the previous MATLAB code block. There are 2 main differences. On line 4,

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
54 is replaced with
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
52, and there is no
In [2]: import antigravity
99 statement to end the block. Thay vào đó, khối
In [2]: import antigravity
96 kết thúc khi tìm thấy dòng mã được xác định tiếp theo sau
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
03. You can read more in the for
In [2]: import antigravity
96 statements

Calling Functions and Indexing Sequences Use Different Brackets in Python

In MATLAB, when you want to call a function or when you want to index an array, you use round brackets [

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
69], sometimes also called parentheses. Square brackets [
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
70] are used to create arrays

You can test out the differences in MATLAB vs Python with the example code below

>>>

In [2]: import antigravity
6

In this code, you first create an array using the square brackets on the right side of the equal sign. Then, you retrieve the value of the first element by

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
71, using the round brackets as the indexing operator. On the third input line, you are calling
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
72 and using the round brackets to indicate the parameters that should be passed into
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
72, in this case just
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
74. MATLAB computes the sum of the elements in
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
74 and returns that result

Python uses separate syntax for calling functions and indexing sequences. In Python, using round brackets means that a function should be executed and using square brackets will index a sequence

>>>

In [2]: import antigravity
7

In this code, you are defining a Python list on input line 1. Python lists have some important distinctions from arrays in MATLAB and arrays from the NumPy package. You can read more about Python lists in Lists and Tuples in Python, and you’ll learn more about NumPy arrays in

Trên dòng đầu vào 2, bạn đang hiển thị giá trị của phần tử đầu tiên của danh sách với thao tác lập chỉ mục bằng dấu ngoặc vuông. On input line 3, you are calling

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
72 using round brackets and passing in the list stored in
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
74. Điều này dẫn đến tổng của các phần tử danh sách được hiển thị trên dòng cuối cùng. Notice that Python uses square brackets for indexing the list and round brackets for calling functions

The First Index in a Sequence Is 0 in Python

In MATLAB, you can get the first value from an array by using

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
78 as the index. This style follows the natural numbering convention and starts how you would count the number of items in the sequence. You can try out the differences of MATLAB vs Python with this example

>>>

In [2]: import antigravity
8

In this code, you are creating an array with three numbers.

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
79,
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
80, and
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
81. Then you are displaying the value of the first element with the index
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
78, which is
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
79. Trying to access the zeroth element results in an error in MATLAB, as shown on the last two lines

In Python, the index of the first element in a sequence is 0, not 1

>>>

In [2]: import antigravity
9

In this code, you are defining

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
74 as a Python list with three elements on input line 1. On input line 2, you are displaying the value of the first element of the list, which has the index 0. Then you are displaying the second element of the list, which has the index 1

On input lines 4, 5, and 6, you are defining

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
85 with the contents
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
86 and then getting the first and second elements of the string. Notice that the second element [character] of the string is a space. This demonstrates a general Python feature, that many variable types operate as sequences and can be indexed, including lists, tuples, strings, and arrays

The Last Element of a Sequence Has Index
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
87 in Python

In MATLAB, you can get the last value from an array by using

In [2]: import antigravity
99 as the index. This is really useful when you don’t know how long an array is, so you don’t know what number to access the last value

Try out the differences in MATLAB vs Python with this example

>>>

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
0

In this code, you are creating an array with three numbers,

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
79,
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
80, and
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
81. Then you are displaying the value of the last element with the index
In [2]: import antigravity
99, which is
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
81

In Python, the last value in a sequence can be retrieved by using the index

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
87

>>>

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
1

In this code, you are defining a Python list with three elements on input line 1. On input line 2, you are displaying the value of the last element of the list, which has the index

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
87 and the value 30

In fact, by using negative numbers as the index values you can work your way backwards through the sequence

>>>

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
2

In this code, you are retrieving the second-to-last and third-to-last elements from the list, which have values of

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
80 and
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
79, respectively

Exponentiation Is Done With
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
98 in Python

In MATLAB, when you want to raise a number to a power you use the caret operator [

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
99]. The caret operator is a binary operator that takes two numbers. Other binary operators include addition [
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
00], subtraction [
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
01], multiplication [
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
02], and division [
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
03], among others. The number on the left of the caret is the base and the number on the right is the exponent

Try out the differences of MATLAB vs Python with this example

>>>

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
3

In this code, you are raising 10 to the power of 2 using the caret resulting an answer of 100

In Python, you use two asterisks [

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
98] when you want to raise a number to a power

>>>

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
4

In this code, you are raising 10 to the power of 2 using two asterisks resulting an answer of 100. Notice that there is no effect of including spaces on either side of the asterisks. In Python, the typical style is to have spaces on both sides of a binary operator

The Length of a Sequence Is Found With
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
05 in Python

In MATLAB, you can get the length of an array with

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
06. This function takes an array as the argument and returns back the size of the largest dimension in the array. You can see the basics of this function with this example

>>>

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
5

Trong mã này, trên dòng đầu vào đầu tiên, bạn đang tìm độ dài của một mảng có 3 phần tử. As expected,

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
06 returns an answer of 3. On the second input line, you are finding the length of the string array that contains one element. Notice that MATLAB implicitly creates a string array, even though you did not use the square brackets to indicate it is an array

In Python, you can get the length of a sequence with

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
05

>>>

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
6

In this code, on the input line 1 you are finding the length of a list with 3 elements. As expected,

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
05 returns a length of 3. On input line 2, you are finding the length of a string as the input. In Python, strings are sequences and
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
05 counts the number of characters in the string. In this case,
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
11 has 8 characters

Console Output Is Shown With
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19 in Python

In MATLAB, you can use

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
20,
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
14, and
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
15 to print the value of variables and other output to the console. In Python,
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19 serves a similar function as
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
20. Unlike
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
20,
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19 can send its output to a file similar to
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
14

Python’s

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19 will display any number of arguments passed to it, separating them by a space in the output. This is different from
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
20 in MATLAB, which only takes one argument, although that argument can be an array with multiple values. The following example shows how Python’s
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19 can take any number of arguments, and each argument is separated by a space in the output

>>>

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
7

In this code, the input lines 1, 2, and 3 define

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
24,
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
25, and
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
26, where
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
24 and
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
24 are integers, and
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
26 is a string of text. On input line 4, you are printing the three variables using
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19. The output below this line the value of the three variables are shown in the console output, separated by spaces

You can control the separator used in the output between arguments to

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19 by using the
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
32 keyword argument

>>>

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
8

In this code, you are printing the same three variables but setting the separator to be a semicolon followed by a space. This separator is printed between the first and second and the second and third arguments, but not after the third argument. To control the character printed after the last value, you can use the

In [2]: import antigravity
99 keyword argument to
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19

>>>

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
9

In this code, you have added the

In [2]: import antigravity
99 keyword argument to
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19, setting it to print a semicolon after the last value. This is shown in the output on line below the input

Like

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
20 from MATLAB,
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19 cannot directly control the output format of variables and relies on you to do the formatting. If you want more control over the format of the output, you should use f-strings or
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
39. In these strings, you can use very similar formatting style codes as
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
14 in MATLAB to format numbers

>>>

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
0

In this code, input line 7 includes an f-string, indicated by the

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
41 to start the string. This means that Python will substitute the value of any variables it encounters between
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
42, or curly braces, within the string. You can see that in the output, Python has replaced
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
43 with a floating point number with 8 columns in the output and 3 digits of precision

Input line 9 demonstrates a in Python 3. 8. If a variable name is immediately followed by an equals sign inside curly braces, the name of the variable and the value will be printed automatically

You can take a deep dive into Python’s

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19 by checking out The Ultimate Guide to Python Print

Loại bỏ các quảng cáo

You Will Probably See These, but You Can Learn Them When You Need To

In this section, you’ll find examples of code that you’ll probably see in the wild, but you can wait a little while to understand them if you want. These examples use some intermediate features in Python but are still in the core of how Python works. Just like in the last section, you’ll see comparisons of the MATLAB vs Python syntax differences

Function Definitions Start With
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
45 and
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
46 Values in Python

In MATLAB, you can define a function by placing the

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
47 keyword at the start of a line. This is followed by the name of any output variables, an equals [
In [2]: import antigravity
63] sign, then the name of the function and any input arguments in parentheses. Within the the function you have to assign to any variables you specified in the definition line as outputs. A simple example MATLAB function is shown below

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
1

In this code, you see the

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
47 definition on line 1. There is only one output variable, called
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
50, for this function. The name of the function is
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
51 and it takes two arguments, which will be assigned the names
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
52 and
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
53 in the function body. Line 2 is the implementation of the function. The value of
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
50 is set equal to the sum of
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
52 and
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
53. The last line of the function is the
In [2]: import antigravity
99 keyword that tells the MATLAB interpreter the definition of the function has finished

To use this function in MATLAB, you should save it in a file called

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
58, matching the name of the function. Alternatively, it can be placed in file with other commands provided that the function definition is the last thing in the file and the file is not named
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
58. Then, you can run the function by typing the following code in the MATLAB console

>>>

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
2

In this code, you have defined two variables called

In [2]: import antigravity
51 and
In [2]: import antigravity
52 that hold the values 20 and 10, respectively. Then you created a third variable called
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
62 that stores the output from
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
63. Check out the Variable explorer, and you’ll see that
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
62 has the value 30, as expected. Notice that the name
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
62 did not have to be the same name as the output variable used in the function definition, which was
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
50

MATLAB does not require a function to provide an output value. In this case, you would remove the output variable and the equals sign from the function definition. Modify your

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
58 file so that the code looks like this

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
3

The only change in this code from the earlier code is that you deleted the

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
68 from line 1, the other lines are exactly the same. Now if you try to assign the result of calling this function to a variable, MATLAB will generate an error in the console

>>>

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
4

In this code, you defined the same two variables

In [2]: import antigravity
51 and
In [2]: import antigravity
52 as before and called
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
63 in the same way as before. However, since
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
63 no longer specifies an output variable, MATLAB generates an error message that there are too many output arguments. Clicking on the word
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
51 will open the definition of the function for you to edit or view the source code to fix the problem

In Python, the

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
45 keyword starts a function definition. The
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
45 keyword must be followed by the name of the function and any arguments to the function inside parentheses, similar to MATLAB. The line with
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
45 must be ended with a colon [
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
77]

Starting on the next line, the code that should be executed as part of the function must be indented one level. Trong Python, định nghĩa hàm kết thúc khi một dòng mã bắt đầu ở cùng mức thụt đầu dòng với từ khóa

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
45 trên dòng đầu tiên

If your function returns some output back to the caller, Python does not require that you specify a name for an output variable. Instead, you use the

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
46 statement to send an output value from the function

An equivalent function in Python to your first

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
63 example with an output variable is shown below

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
5

In this code, you see the

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
45 keyword followed by the function name and the two arguments
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
52 and
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
53 on line 1. On line 2 you can see the creation of a new variable
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
50 to store the sum of
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
52 and
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
53, and on line 3 the value of
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
50 is returned to the point where this function was called. Notice that lines 2 and 3 are indented by 4 spaces because they make up the body of the function

The variable that stores the sum of

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
52 and
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
53 can have any name, it doesn’t have to be called
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
50. In fact, you don’t need to create a variable there at all. You can simplify your previous function definition by eliminating
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
50 and simply returning the value of
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
92

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
6

Line 1 in this code is the same as it was before, you have only changed line 2 and deleted line 3. Line 2 now computes the value of

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
92 and returns that value back to the caller of the function. Dòng 2 được thụt vào 4 dấu cách vì nó tạo nên phần thân của hàm

To use this function in Python, you do not need to save it in a file with a special name. You can place the function definition in any Python file, at any point in the file. There is no restriction that the function definition has to be last. In fact, you can even define functions right from the console, which is not possible in MATLAB

Open Spyder and in the Console pane type

>>>

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
7

On this line of code you are creating the function definition. In the Spyder/IPython console, once you start a function definition and press Enter , the start of the line becomes three dots and the cursor is automatically indented. Now you can type the remainder of the function definition. You’ll have to press Enter twice to complete the definition.

>>>

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
8

In this code, you have the definition of the function on the first line and the body of the function on the second line. Bảng điều khiển tự động thêm

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
94 vào đầu các dòng để cho biết đây là các dòng tiếp nối áp dụng cho định nghĩa hàm

Khi bạn đã hoàn thành định nghĩa, bạn cũng có thể thực thi chức năng từ bảng điều khiển. You should type this code

>>>

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
9

In this code, you first create two variables

In [2]: import antigravity
51 and
In [2]: import antigravity
52 that store the values you want to add together. Then, on input line 4, you assign
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
62 to the result that is returned from
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
63. On input line 5, you are outputting the value of
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
62 to the console screen. This displays 30, the sum of 10 and 20

In Python, if you do not explicitly put a

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
46 statement, your function will implicitly return the special value
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
01. You should change your Python definition of
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
63 to see how this works. In the Spyder/IPython console, type the following

>>>

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
0

In this code, you have the same

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
45 line on input line 6. You have changed the first continuation line to assign the result of the addition to
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
50 instead of returning. Now you should see what happens when we execute this modified function

>>>

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
1

In this code, on input line 7 you are assigning

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
62 to be the returned value from
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
63. Then, on input line 8, you are showing the value of
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
62 on the console screen, just like before. This time though, there is no output. By default, Python prints nothing when it outputs a variable whose value is
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
01. You can double check the value of the
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
62 variable by looking at the Variable explorer. In the Type column, it should list
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
10, telling you that
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
62 is the special
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
01 value

Functions Accept Positional and Keyword Arguments in Python

In MATLAB, functions have input arguments specified on the first line, in the

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
47 definition. When you call a function in MATLAB, you can pass from zero up to the number of arguments that are specified. In the body of the function, you can check the number of input arguments the caller actually passed to execute different code. This is useful when you want different arguments to have different meaning, like in the example below

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
2

In this code, you are defining a function with three possible input arguments. On line 7, you are starting a

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
14/
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
15 block that determines how many input arguments were passed to the function by using the special variable
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
16. This variable stores the actual number of arguments the caller passed into the function

In your code above, you are defining three cases

  1. If the number of input arguments is 2, you are adding
     1# -*- coding: utf-8 -*-
     2"""
     3Spyder Editor
     4
     5This is a temporary script file.
     6"""
    
    52 and
     1# -*- coding: utf-8 -*-
     2"""
     3Spyder Editor
     4
     5This is a temporary script file.
     6"""
    
    53 together
  2. If the number of input arguments is 3, you are subtracting
     1# -*- coding: utf-8 -*-
     2"""
     3Spyder Editor
     4
     5This is a temporary script file.
     6"""
    
    53 from
     1# -*- coding: utf-8 -*-
     2"""
     3Spyder Editor
     4
     5This is a temporary script file.
     6"""
    
    52
  3. If fewer than 2 arguments are passed, the output will be
     8var_4 = 10
     9var_5 = 20
    10var_6 = var_4 + var_5
    
    21

If more than 3 arguments are passed, MATLAB will raise an error

Now you should experiment with this function. Save the code above into a file called

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
22 and then on the MATLAB console, try the version with two input arguments

>>>

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
3

In this code, you are calling

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
23 with two arguments, so the arguments are added together, resulting in an answer of
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
81. Next, try calling
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
23 with three arguments

>>>

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
4

In this code, you used three input arguments, and found that the second argument was subtracted from the first, resulting in an answer of

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
26. Third, try calling
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
23 with one argument

>>>

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
5

In this code, you used one input argument and found the answer was 0, because MATLAB only found one argument to the function and used the

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
28 case. Finally, try calling
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
23 with four arguments

>>>

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
6

In this code, you find that MATLAB raises an error because there were more input arguments passed than were defined in the

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
47 line

There are four key takeaways from this example with MATLAB

  1. There is only one kind of argument in a function definition
  2. Ý nghĩa của một đối số trong mã được xác định bởi vị trí của nó trong định nghĩa hàm
  3. The maximum number of arguments that can be passed to a function is determined by the number of arguments specified in the function definition
  4. Any number of arguments up to the maximum can be passed by the caller

In Python, there are two kinds of arguments you can specify when defining a function. These are required and optional arguments. The key difference between these is that required arguments must be passed when a function is called, while optional are given a default value in the function definition

You can see the differences between these two styles in the next example

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
7

In this code, you are defining a function called

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
31 that has three arguments.
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
52,
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
53, and
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
34. In the function definition, you can see the two types of arguments. The first two arguments,
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
52 and
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
53, are required arguments

The third argument,

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
34, has a default value assigned to it by specifying a value after an equals sign in the function definition. This means that when the function is called, passing a value for
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
34 is optional. If no value is passed, the default as defined in the function definition line will be used. In this case, the default value is
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
39

In the body of the function, you are testing the value of

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
34 with the
In [2]: import antigravity
96 statement to determine whether addition or subtraction should be performed. If
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
34 is
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
43,
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
53 will be subtracted from
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
52. Otherwise, if
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
34 is
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
39, then
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
52 will be added to
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
53. In either case, the result of the arithmetic operation will be returned to the caller

In addition to the two types of arguments you can use when defining a function, there are two kinds of arguments you can specify when calling a function. These are called positional and arguments. You can see the difference between these in the following example. First, try passing only two arguments to the function

>>>

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
8

In this code, you passed only two arguments to

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
31,
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
79 and
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
80. In this case, you passed these values as positional arguments, and the meaning of the arguments is defined by their position in the function call

Since only the two required arguments were passed,

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
34 will take on the default value, which is
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
39. Do đó, 10 và 20 sẽ được cộng lại với nhau, bạn có thể thấy điều này trên dòng đầu ra. Next, try passing a value for
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
34

>>>

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
9

In this code, you passed three arguments to

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
31, with two different values for the
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
34 argument. First, you passed
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
39 on input line 2. The result was the addition of 10 and 20. Then, you passed
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
43 on input line 3, resulting in the difference between 10 and 20, or -10

In these examples, you saw that it is possible in Python to define default values for arguments to a function. This means when you call the function, any arguments with default values are optional and do not have to be passed. If no value is passed for any default arguments, the default value will be used. However, you must pass a value for every argument without a default value. Otherwise, Python will raise an error

>>>

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
0

In this code, you have only passed one of the two required arguments to

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
31, so Python raises a
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
61. The error message tells you that you did not pass a value for
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
53, because it does not have a default value

In these last three example, you have used positional arguments, so which parameter is assigned to the variables in the function depends on the order they are passed. There is another method to pass arguments to functions in Python, called keyword arguments. To use keyword arguments, you specify the name of the argument in the function call

>>>

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
1

In this code, you have used keyword arguments for all three arguments to

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
31. Keyword arguments are specified by stating the argument name, then an equals sign, then the value that argument should have. One of the big advantages of keyword arguments is that they make your code more explicit. [As the Zen of Python says, explicit is better than implicit. ] However, they make the code somewhat longer, so it’s up to your judgement when to use keyword arguments or not

Another benefit of keyword arguments is that they can be specified in any order

>>>

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
2

In this code, you have specified the three arguments for

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
31 as keyword arguments, but the order is different from in the function definition. Nonetheless, Python connects the right variables together because they are specified as keywords instead of positional arguments

You can also mix positional and keyword arguments together in the same function call. If positional and keyword arguments are mixed together, the positional arguments must be specified first, before any keyword arguments

>>>

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
3

In this code, you have specified the values for

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
52 and
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
53 using positional arguments, and the value for
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
34 using a keyword argument. This is probably the most common case of using keyword arguments, because it provides a good balance between being explicit and being concise

Finally, there is one last benefit of using keyword arguments and default values. Spyder, and other IDEs, provide introspection of function definitions. This will tell you the names of all of the defined function arguments, which ones have default arguments, and the value of the default arguments. This can save you time and make your code easier and faster to read

There Are No
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
14/
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
15 Blocks in Python

In MATLAB, you can use

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
14/
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
15 blocks to execute code by checking the value of a variable for equality with some constants. This type of syntax is quite useful when you know you want to handle a few discrete cases. Try out a
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
14/
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
15 block with this example

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
4

In this code, you start by defining

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
00 and setting it equal to 10 and on the following lines you test the value of
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
00. This code will result in the output
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
76 being displayed on the console, since
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
00 is equal to 10

This syntax is an interesting comparison of MATLAB vs Python because Python does not have a similar syntax. Thay vào đó, bạn nên sử dụng khối

In [2]: import antigravity
96/______36_______52/
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
03

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
5

In this code, you start by defining

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
00 and setting it equal to
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
79. On the next several lines you are writing an
In [2]: import antigravity
96/
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
52/
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
03 block to check the different values that you are interested in

Namespaces Are One Honking Great Idea in Python

In MATLAB, all functions are found in a single scope. MATLAB has a defined search order for finding functions within the current scope. If you define your own function for something that MATLAB already includes, you may get unexpected behavior

As you saw in the Zen of Python, namespaces are one honking great idea. Namespaces are a way to provide different scopes for names of functions, classes, and variables. This means you have to tell Python which library has the function you want to use. Đây là một điều tốt, đặc biệt trong trường hợp có nhiều thư viện cung cấp cùng một chức năng

Chẳng hạn, thư viện

In [2]: import antigravity
88 tích hợp sẵn cung cấp hàm căn bậc hai, cũng như thư viện NumPy nâng cao hơn. Without namespaces, it would be more difficult to tell Python which square root function you wanted to use

To tell Python where a function is located, you first have to

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
87 the library, which creates the namespace for that library’s code. Then, when you want to use a function from the library, you tell Python which namespace to look in

>>>

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
6

In this code, on input line 1 you imported the

In [2]: import antigravity
88 library that is built-in to Python. Then, input line 2 computes the square root of 4 using the square root function from within the
In [2]: import antigravity
88 library. The
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
90 line should be read as “from within
In [2]: import antigravity
88, find
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
92. ”

The

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
87 keyword searches for the named library and binds the namespace to the same name as the library by default. You can read more about how Python searches for libraries in Python Modules and Packages – An Introduction

You can also tell Python what name it should use for a library. For instance, it is very common to see

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
94 shortened to
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
95 with the following code

>>>

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
7

In this code, input line 3 imports NumPy and tells Python to put the library into the

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
95 namespace. Then, whenever you want to use a function from NumPy, you use the
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
95 abbreviation to find that function. On input line 4, you are computing the square root of 4 again, but this time, using
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
98.
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
98 should be read as “from within NumPy, find
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
92. ”

There are two main caveats to using namespaces where you should be careful

  1. You should not name a variable with the same name as one of the functions built into Python. You can find a complete list of these functions in the Python documentation. The most common variable names that are also built-in functions and should not be used are

    In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    01,
    In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    02,
    In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    03,
    In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    04,
    In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    05,
    In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    06,
    In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    07,
    In [2]: import antigravity
    
    91,
    In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    09, and
    In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    10

  2. You should not name a Python file [one with the extension

    In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    11] with the same name as a library that you have installed. In other words, you should not create a Python file called
    In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    12. This is because Python searches the current working directory first when it tries to import a library. If you have a file called
    In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    12, that file will be found before the built-in
    In [2]: import antigravity
    
    88 library and you will probably see an
    In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    15

The Most Recent Unassigned Result Is Available as
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
16 in Python

The MATLAB console uses

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
17 to store the result of the most recent calculation if that result was not assigned to a variable. This is really useful when you forgot to assign the result of a calculation to a variable or when you just want to chain a few simple calculations together. To see the differences between MATLAB vs Python, try out this example

>>>

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
8

In this code, you use

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
72 to calculate the sum of the array. Since there is no equal sign with a variable name on the left, MATLAB assigns the output from
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
72 to
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
17. You can then use that variable in further calculations, as you do here by adding 10 to the last result. Note that this will only work in the MATLAB console, not in a script file

In the Python console [including the IPython/Spyder console], the output from the most recent calculation is stored in

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
16 [the underscore character]. Try the following code

>>>

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
9

In this code, you use

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
72 to calculate the sum of the list. Since there is no equal sign with a variable name on the left, Python assigns the output from
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
72 to the underscore [
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
16], in addition to printing it on the output line. You can then use that variable in further calculations, as you do here by adding 10 to the last result. Note that this will only work in the Python console, not in a script file

In the IPython console, there is one additional feature enabled. You can append a number after the underscore to retrieve the result of any previous line. Try the following code

>>>

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
0

In this code on input line 3 you are using

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
25 to mean the value of output line 1, the
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
72 line. To that result [60] you are adding 20, producing a result of 80. On input line 4, you are adding 20 to the value of output line 2, accessed with
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
27, so the result is 90

Notice that the Spyder Variable explorer does not show this variable by default, whereas

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
17 is shown in the MATLAB Variable explorer. In , you’ll see why the underscore isn’t shown by default and how you can see it

Anonymous Functions Are Created With the
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
29 Keyword in Python

MATLAB uses the the at-symbol [

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
30] to indicate that what follows is the definition of an anonymous function. Anonymous functions are functions that are not defined in a program file and do not use the
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
47 keyword. A program file is a MATLAB file with a filename ending in
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
32. Anonymous functions are limited to a single statement so they are intended for simple computations

You can try out the differences of anonymous functions in MATLAB vs Python with this example

>>>

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
1

In this code, the first input line defines the anonymous function with one input parameter,

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
33. The body of the function follows, which uses
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
14 to format the input into a string. This function is assigned to
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
35. On the second input line,
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
36 is executed and passed
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
37 as the value. The result the string
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
38 printed on the console

Anonymous functions are most often used when you need to pass one function into another function. In these cases, it is often not necessary to assign the function definition to a variable

>>>

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
2

In this code, the first input line executes

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
39, a function that computes the definite integral of a given function. The first argument to
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
39 must be a function, so this is a perfect place to use an anonymous function. Here, your anonymous function squares whatever the input value is. The other two arguments to
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
39 are the limits of the integration, such that the result of integrating
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
42 from 0 to 9 is 243

Python sử dụng từ khóa

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
29 để định nghĩa các hàm ẩn danh. Other than this syntax difference, anonymous functions work the same way in Python as in MATLAB

>>>

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
3

In this code, input line 1 defines the

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
29 function with one parameter,
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
33. You use
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
19 within the function definition to show an f-string with the value of the input parameter. The function is then stored in
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
47. Input line 2 evaluates
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
47 with the input string
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
37 and produces the
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
38 output

In Python, the official style guide called PEP 8 assigning

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
29 expressions to variable names, as you saw in the last example. If you want to give a function a name to refer to it several times, the preference is to use the
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
45 syntax and define a full function, even for one-line functions

However,

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
29 functions are still useful when they are passed as arguments into another function

>>>

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
4

In this code, input line 3 imports the

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
54 library and stores it in the
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
55 namespace. On input line 4, you are using to compute the integral using quadrature, very similar to
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
39 in MATLAB. The first argument to
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
56 is the function to be integrated, and you use a
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
29 function to specify that
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
61 should be integrated. The second and third arguments to
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
56 specify that the integral should be conducted from 0 to 9

You can see that the result on output line 4 has two values,

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
63 and
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
64. The first value is the result of the integration, and is equal to the result from MATLAB. The second value is an estimate of the absolute error in the result. An error this small is approximately the precision of the numbers used to store the result, so the answer is about as accurate as it can be

You can read more about

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
29 in How to Use Python lambda Functions or watch the videos in the How to Use Python Lambda Functions course

Loại bỏ các quảng cáo

You Will Only Need These in Specialized Situations

In this section, the examples are more advanced concepts that you will need as you become more advanced in Python development. Some of the examples here deal with developing applications or higher-level code than the other sections. When you see these concepts in other code, you can dig in to them when you feel comfortable

Class Definitions Start With
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
66 in Python

MATLAB has two ways to define a class. With the first way, you can put all of the class definition in a single file with the name of the class as the filename. Then within the file, you can use the

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
67 keyword to define the properties and methods that belong to the class

With the second way, you can create a folder that starts with

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
30 and has the same name as the class. In that folder, you can create a single file that has the same name as the class. The function definition in that file will be used as the class initializer, and it should call
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
69 to instantiate the class. Methods of the class can be defined in other files in the same folder, where the name of each file must be the same as the name of the method

Python only has one way to define a class, using the

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
66 keyword. Since Python uses indentation to find the end of the class definition, the entire definition must be contained in a single file

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
5

In this code, the first line defines the name of the class. It starts with the

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
66 keyword, followed by the name of the class and a colon. Underneath this line, all of the code that is part of the class definition [methods and attributes] must be indented. Once a line of code starts in the same column as the
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
72 in
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
66, the class definition will be ended

The second line in this code is a comment to note that the rest of the class definition would follow the

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
66 line

As in all object-oriented code, Python classes can inherit from superclasses. The superclass of a given class can be given as a parameter in the class definition, as shown below

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
6

In this code, the only change is that the name of the superclass is listed inside round brackets before the colon

There Are No Private Properties or Methods in Python

MATLAB allows class properties and method to be set as one of four

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
75 options

  • In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    76. Access to the property or method is unrestricted
  • In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    77. Access to the property or method is only allowed in this class or subclasses
  • In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    78. Access to the property or method is only allowed in this class
  • In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    79 or
    In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
       ...:         wdir='C:/Users/Eleanor/.spyder-py3']
    
    80. Access to the property or method is only allowed in the listed class or classes

This allows you to specifically control the ways that a property or class method can be accessed

In Python, there is no way to set a class or instance attribute or method as protected or private. All classes and class instances can have their attributes and methods changed at runtime. Python’s convention is that attributes and methods that start with an underscore [

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
16] are intended to be private, or at least non-public. However, this convention is not enforced by any checks in the language and all attributes and methods can be modified by the user at runtime

As you saw in the section about , the underscore is not visible by default in the Spyder Variable explorer. This is because Spyder and other tools respect the convention that underscore indicates something should be non-public. However, underscores can be shown in the Spyder Variable explorer if you click the gear icon in the top right of that pane and uncheck the Exclude private variables item. This will also show other non-public variables as well

Python uses several special methods that start with a double-underscore [

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
82], called dunder methods, to implement specific behavior for classes. The most commonly used dunder method is
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
83, which is the class initializer or constructor. You can read a lot more about dunder methods in Enriching Your Python Classes With Dunder [Magic, Special] Methods

If you want more information about Python’s classes, you can read Object-Oriented Programming in Python vs Java. Even though that article is about Java, Java is similar to the MATLAB OOP paradigm in terms of the nature of attributes and methods

A Class Refers to Itself as
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
84 in Python

MATLAB uses the name

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
85 when a class wants to refer to the current instance of itself. The
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
85 should be the first argument passed to an ordinary method. MATLAB also defines static methods that have no reference to the class instance

Python uses the name

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
84 when a class wants to refer to the current instance of itself, but this is actually only a convention. You can call the first argument to an instance method any name you want, but
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
84 is the most common convention. Python also defines static methods that don’t take an argument of the class instance and class methods that take an argument of the class object instead of the instance. You can read more about instance, static, and class methods in Python’s Instance, Class, and Static Methods Demystified

There Is One String Type in Python

Trong MATLAB, các chuỗi ký tự được lưu trữ trong mảng chuỗi khi bạn sử dụng dấu nháy kép [

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
89] hoặc trong mảng ký tự nếu bạn sử dụng dấu nháy đơn [
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
90]. If you use both single and double quotes in an array assignment, the array will be promoted to a string array

In character arrays, each character in the string occupies one column in the array. For multidimensional character arrays, each row of the array must have the same number of characters, which is to say, the same number of columns. This is shown in the example below

>>>

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
7

In this example, line 1 shows an attempt to define a 2-row character array using single quotes. However, the number of characters in

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
91 is not the same as in
In [2]: import antigravity
87, so MATLAB shows an error message that the dimensions are not consistent

On line 4, you successfully create a character array, and on the third input line you are checking the size of the array. The output shows that there are 2 rows, as expected, and 6 columns, since the length of both

In [2]: import antigravity
86 and
In [2]: import antigravity
87 are 6 characters

This is not the case for string arrays. In string arrays, each string occupies one column in the array and each row in a multidimensional array must have the same number of strings, although each string can have different length. This is shown in the example below

>>>

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
8

In this code, line 1 shows an attempt to define a 2-row string array using double quotes. However, the number of strings on the first row [2] does not match the number of strings in the second row [1], so MATLAB raises an error

On line 5, you successfully create a string array. Lưu ý rằng mặc dù số lượng ký tự khác nhau giữa

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
91 và
In [2]: import antigravity
87, MATLAB vẫn có thể tạo mảng chuỗi. On line 6 you are checking the size of the string array, which shows that there are 2 rows and 1 column, as expected

In Python, there is only one string literal type, called

In [2]: import antigravity
91. You can create a string literal using single quotes [
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
90] or double quotes [
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
89], there is no difference between the two definitions. However, there are some good arguments to prefer double quotes when defining string literals in Python, which are well expressed by the

There is one additional way to define strings in Python, using triple-single-quotes [

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
00] or triple-double-quotes [
In [2]: import antigravity
95]. This method of creating strings allows the strings to be defined across multiple lines with the newline characters retained. You can see an example of this in the section about

Bạn có thể đọc thêm về cách xác định chuỗi trong và Dữ liệu chuỗi và ký tự trong Python

You can generate similar data structures to the string arrays and character arrays in MATLAB using NumPy in Python. NumPy has several data types, or dtypes, that are related to strings. In Python 3, the default string dtype for arrays is a fixed-width Unicode string

>>>

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
9

Trong mã này, bạn đang nhập thư viện NumPy trên dòng đầu vào 1 và gán nó cho chữ viết tắt

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
95. Trên dòng đầu vào 2, bạn đang tạo một NumPy
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
03 với 2 phần tử chuỗi,
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
91 và
In [2]: import antigravity
87, đồng thời gán mảng cho
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
74

On input line 3, you are showing the value of

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
74. The output from the third line shows that
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
74 is storing an
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
03 that has 2 elements,
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
10 and
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
11, as expected. Notice that although you defined the array with double-quote strings, Python is displaying them with single-quote strings. Remember that there is no difference between single and double quotes in Python

Output line 3 also shows the dtype of the data in the array. For this array, the dtype is

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
12. The three characters here represent the aspects of how the strings are arranged in memory. The the byte order of the array is . The
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
14 means the string is . Finally, the
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
15 means the maximum length of an element is 6 characters. This was chosen as the length of the longest string in the input

Notice that the string

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
91 only has 4 characters. In NumPy string dtype arrays, elements can have fewer than the maximum number of characters without problems, but assigning to elements with strings that are longer than the maximum length will truncate the input

>>>

# -*- coding: utf-8 -*-
0

In this code, you are attempting to reassign the first element of the array with the string

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
17. Clearly, this string is longer than 6 characters, so it is truncated to only 6 when it is assigned,
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
18. [The space counts as 1 character. ]

If you want to create an array that can hold strings of any length, you should pass the

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
19 dtype when you create the array

>>>

# -*- coding: utf-8 -*-
1

In this code, you are creating a new array,

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20, with two elements again, but this time you specified the dtype to be
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
19, which you confirmed by showing the output on the console. Now you should see how the
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
19 dtype affects assigning long strings to an element

>>>

# -*- coding: utf-8 -*-
2

In this code, you are again assigning the first element of the array to have the value

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
17. You can see from the output line that that string is stored as the first element of the array without truncation, because the dtype is
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
19. The disadvantage of using the
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
19 dtype is that it is usually much slower than the more specific
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
14 dtype, because it has to create a a whole Python object for each element rather than just a NumPy-optimized Unicode object

One other difference you will notice from MATLAB is how the shape or size of the array is determined

>>>

# -*- coding: utf-8 -*-
3

In this code, we are printing the shape of

In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
74 and
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20. Notice that they both have the same shape, two elements in a one-dimensional array. This is similar to the string array from MATLAB, where each string counts as one element in the array. However, the fact that NumPy arrays with the
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
14 dtype have a fixed maximum size behaves more like the character array from MATLAB. You’ll see more about differences in how MATLAB and NumPy compute the shape of arrays

Libraries Are Not Automatically Reloaded in Python

When executing a function or script, MATLAB will always use the most up-to-date copy of the file on the disk. Therefore, as you’re developing a script, you can run it in the console many times and new changes that you make will automatically be picked up

Python operates somewhat differently. Remember that when you want to access code from a file, you have to

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
87 it into a namespace. When Python imports a file or module, it only reads the code the first time it is imported. This saves quite a bit of time if you’re importing the same file several times. However, if you’re testing your code in the interactive console prompt as you work on it, Python will not pick up any changes if you
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
87 it again

When you’re developing a module, you have a few options to have Python reload your code when it is imported. If you’re using the Spyder IDE, this is not a problem at all, since Spyder has an automatic feature enabled by default

Otherwise, if you’re using the IPython console outside of Spyder, or the Jupyter Notebook, you can use a magic command defined in those interpreters called

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
32

>>>

# -*- coding: utf-8 -*-
4

In this code, you are using the

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
33 magic command to load the
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
32 extension. In IPython and Jupyter Notebooks, commands prefixed with the percent sign
In [2]: import antigravity
72 are magic commands. Tiện ích mở rộng
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
32 xác định chức năng ma thuật
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
32 mà bạn sử dụng trên dòng đầu vào 2. You are passing the parameter
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
38 to the
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
32 magic function, which means that all modules should be reloaded every time a line of code is executed

Loại bỏ các quảng cáo

An Overview of Basic Array Operations

As you have seen, Python does not include a high-speed library for arrays in its standard library. However, the excellent NumPy library is easily available if you install Anaconda. NumPy functions as the de facto array and matrix library for Python

NumPy has two array-like types

  1. 11# %% This is a code cell
    12var_7 = 42
    13var_8 = var_7 * 2
    14
    15# %% This is a second code cell
    16print["This code will be executed in this cell"]
    
    40, also known as
    11# %% This is a code cell
    12var_7 = 42
    13var_8 = var_7 * 2
    14
    15# %% This is a second code cell
    16print["This code will be executed in this cell"]
    
    41
  2. 11# %% This is a code cell
    12var_7 = 42
    13var_8 = var_7 * 2
    14
    15# %% This is a second code cell
    16print["This code will be executed in this cell"]
    
    42

The main difference between these two types is that the

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
43 can be any number of dimensions, while the
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
44 is limited to exactly two dimensions. For
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
43, all operations such as addition, subtraction, multiplication, exponentiation, and division operate element-wise. However, for the
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
44 type, operations like multiplication and exponentiation are matrix operations

When you’re converting from MATLAB, the

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
44 type may seem more familiar. It offers similar behavior that you may be used to from MATLAB in terms of operation syntax. However, NumPy that you use the
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
43 type because it is more flexible and because
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
44 will eventually be removed

In the rest of this section, you will get to know the major differences between MATLAB and NumPy arrays. You can go in-depth on how to use NumPy arrays by reading Look Ma, No For-Loops. Array Programming With NumPy

Basic Mathematical Operators Work Element-Wise in NumPy

MATLAB, with its heritage as a matrix scripting language, assumes that all arithmetic operators will be operating on arrays. Therefore, MATLAB treats the multiplication of matrices or vectors as matrix multiplication. Consider this example

>>>

# -*- coding: utf-8 -*-
5

In this code, you are creating two 1x3 matrices,

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50, and
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20. Then, you are attempting to multiply them together. For these 1xN arrays, this is equivalent to taking the dot or scalar product. However, the scalar product only works when the left operand is 1xN and the right is Nx1, so MATLAB produces an error message and suggests the dot-star operator [
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
52] as the proper syntax for element-wise multiplication

>>>

# -*- coding: utf-8 -*-
6

In this code, you are performing the element-wise multiplication of

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 and
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20. This multiplies the first element of
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 with the first element of
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20 [
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
57], second with second [
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
58], and third with third [
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
59]

To perform the scalar product, you can take the transpose of

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20 to convert it to a 3x1 array

>>>

# -*- coding: utf-8 -*-
7

In this code, you are performing matrix multiplication with

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 and the transpose of
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20. Note that you can use either
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
63 or the quote operator [
In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
90] to take the transpose of
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20. Since
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 is 1x3 and
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
67 is 3x1, this results in the scalar, or dot, product

With NumPy arrays, operations like multiplication with the asterisk [

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
02] operate element-wise by default

>>>

# -*- coding: utf-8 -*-
8

In this code, you are first importing the NumPy package and assigning it to the name

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
95. Then you are creating two one-dimensional arrays. Notice the syntax for creating arrays in NumPy. It starts with
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
70, which should be read as “from within
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
95, find
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
72. ” Then, you have to pass a Python list or tuple to the array constructor that contains the elements of the array. In this case, you are passing a Python list, denoted by the square brackets

Finally, on input line 4, you are multiplying

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 and
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20. Notice that the result on output line 4 is another array with the elements 4, 10, and 18, the same result as the element-wise multiplication in MATLAB

If you want to perform the dot or scalar product for two arrays in NumPy, you have two options. The preferred option is to use the matrix multiplication operator [

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
30] added in Python 3. 5. You may see some older code also use
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
76 from the NumPy library and pass the two arrays

>>>

# -*- coding: utf-8 -*-
9

In this code, input line 5 uses the matrix multiplication operator to find the scalar product of

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 and
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20. As expected, the result is 32. Input line 5 uses
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
76 and should be read as “from within
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
95, find
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
76 and pass
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 and
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20. ” You can see that the result is identical

Notice that NumPy did not require you to transpose

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20 before performing the scalar product. You’ll learn more about this feature in the next section

Loại bỏ các quảng cáo

One-Dimensional Arrays Are Vectors in NumPy

As you saw in the last section, MATLAB insists that the dimensions of arrays align when performing matrix multiplication, while NumPy is a little bit more flexible. This is because of how one-dimensional arrays are treated in MATLAB versus in NumPy

In MATLAB, every array always has at least two dimensions, even if only implicitly. You can see this by checking the

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
85 of a single number

>>>

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
0

Here, you are finding the size of the integer 1. You can see that the result is an array with 1 row and 1 column

You can create row vectors or column vectors in MATLAB, and switch between them with the transpose operator [

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
90] or
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
63

>>>

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
1

In this code, you are creating two vectors.

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 and
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20. Arrays with values in one dimension only are called vectors.
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 is a row vector because the elements are arranged in one row and three columns, whereas
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20 is a column vector because the elements are arranged in three rows and one column. In MATLAB, elements are put into different columns by separating them with a comma in the assignment and elements are put into different rows by separating them with a semicolon

Then, you are checking the equality of the transpose of

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 with
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20, and you find that all of the elements are equal and the result is a column vector of logical values. Cuối cùng, bạn đang kiểm tra sự bằng nhau của phép chuyển vị của
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20 với
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 và bạn thấy rằng tất cả các phần tử đều bằng nhau và kết quả là một vectơ hàng của các giá trị logic

You can see that in MATLAB, even vectors have two dimensions associated with them. rows and columns. When the transpose is performed, the rows are switched with the columns, and the shape of the array is changed. This means there are two types of vectors in MATLAB. row-vectors and column-vectors

In NumPy, there are three types of one-dimensional arrays or vectors. The default is an N-element vector with only one dimension. This is different from the default in MATLAB, where every array has at least 2 dimensions. This one-dimensional vector in NumPy does not have a sense of rows and columns, since for a one-dimensional structure, it does not matter in general whether the elements are stored in rows or in columns, only how many elements there are

You can see an example of creating this kind of array in the following example. In the next few examples, there are extra spaces added before and after parentheses to clarify the syntax. These spaces are usually not considered good Python style, but they’re in the example to help you see what’s going on

>>>

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
2

In this code, you are creating a default 3-element vector in NumPy. On input line 1, you import NumPy and make it available under

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
95. On input line 2 you are creating the array and storing it in
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
97. You are passing the list
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
98 to
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
72, where the list has 3 elements and none of the elements are themselves lists. This creates the 3-element array with only one dimension

You can verify that this is the case by displaying the shape of the array, as shown on input line 3. That line should be read as “from within

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
97 [an array], find the
# -*- coding: utf-8 -*-
01. ” The
# -*- coding: utf-8 -*-
01 of the array is equivalent to
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
85 in MATLAB. In this case, the shape is
# -*- coding: utf-8 -*-
04, indicating there are three elements and only one dimension, since there is not a second number after the comma

You can also create row-vectors and column-vectors in NumPy, analogous to the row-vectors and column-vectors in MATLAB. NumPy’s

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
72 takes a flat list or a nested list as input. Using the flat list gets you a one-dimensional, N-element vector. Bằng cách sử dụng danh sách lồng nhau, bạn có thể tạo các mảng có kích thước bất kỳ mà bạn muốn. Danh sách lồng nhau có nghĩa là có một hoặc nhiều danh sách nằm trong danh sách bên ngoài. Đây là một ví dụ về danh sách lồng nhau

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
3

Trong mã này, bạn thấy một danh sách bên ngoài có 2 phần tử. Each of these 2 elements of the outer list is another, nested, list that has three elements, the integers 1-3 and 4-6. In terms of arrays, you can think of the number of elements of each inner list as the number of columns, and the number of nested lists is the number of rows. This is easier to see if you change the formatting

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
4

Mã này vẫn là cú pháp Python hợp lệ, nhưng nó nhấn mạnh cách các danh sách bên trong là một hàng của mảng và số phần tử trong mỗi danh sách bên trong là số cột. In this case, we would have an array with 2 rows and 3 columns. Chúng ta có thể sử dụng các danh sách lồng nhau này để tạo vectơ hàng và vectơ cột trong mảng NumPy

>>>

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
5

Trong mã này, bạn đang tạo một mảng hàng hoặc vectơ bằng cách sử dụng danh sách lồng nhau. Dòng đầu vào 4 đang chuyển

# -*- coding: utf-8 -*-
06 đến
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
72. Bạn có thể tách định dạng của danh sách lồng nhau này để xem nó trông như thế nào

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
6

Như bạn có thể thấy, có một hàng trong danh sách lồng nhau này có ba cột. Trên dòng đầu vào 5, bạn đang hiển thị hình dạng của mảng này. Đúng như dự đoán, hình dạng là

# -*- coding: utf-8 -*-
08, hoặc một hàng ba cột

Cuối cùng, bạn có thể tạo một mảng cột bằng cách đưa ba danh sách lồng nhau vào đầu vào

>>>

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
7

Trong mã này, dòng đầu vào 6 đang chuyển

# -*- coding: utf-8 -*-
09 tới hàm tạo mảng. Bạn có thể tách định dạng của danh sách lồng nhau này để xem nó trông như thế nào

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
8

Như bạn có thể thấy, có ba hàng trong danh sách lồng nhau này, mỗi hàng có một cột. Trên dòng đầu vào 7, bạn đang hiển thị hình dạng của mảng này. Đúng như dự đoán, hình dạng là

# -*- coding: utf-8 -*-
10 hoặc ba hàng một cột

Vì vectơ phần tử N chung không có ý nghĩa về hàng và cột, NumPy có thể định hình vectơ theo bất kỳ cách nào có ý nghĩa đối với thao tác đang được thực hiện. Bạn đã thấy điều này trong phần trước, trong đó mảng NumPy không cần phải hoán vị để thực hiện tích vô hướng, trong khi mảng MATLAB cần được hoán vị

Cố gắng chuyển vị của vectơ phần tử N không làm thay đổi hình dạng của mảng. Bạn có thể thực hiện phép chuyển vị bằng cách sử dụng thuộc tính

# -*- coding: utf-8 -*-
11 hoặc
# -*- coding: utf-8 -*-
12 của mảng

>>>

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
9

Trong mã này, bạn đang thực hiện chuyển vị của vectơ phần tử N

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
97 và in hình dạng của nó. Lưu ý rằng hình dạng giống với hình dạng của bản gốc
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
97

Tuy nhiên, nếu bạn đang sử dụng vectơ hàng và vectơ cột, bạn sẽ cần đảm bảo rằng các kích thước phù hợp với thao tác cụ thể. Chẳng hạn, cố gắng lấy tích vô hướng của vectơ hàng sẽ dẫn đến lỗi

>>>

def addition[num_1, num_2]:
    """Adds two numbers together.

    Example
    -------
    >>> total = addition[10, 20]
    >>> total
    30

    """
0

Trong đoạn mã này, việc cố gắng tìm tích vô hướng của vectơ hàng với chính nó sẽ dẫn đến kết quả là

# -*- coding: utf-8 -*-
15 thông báo cho bạn rằng kích thước của các mảng không được căn chỉnh. Sử dụng
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
76 đưa ra cùng một lỗi nhưng một thông báo hơi khác

>>>

def addition[num_1, num_2]:
    """Adds two numbers together.

    Example
    -------
    >>> total = addition[10, 20]
    >>> total
    30

    """
1

Trong mã này, bạn đang sử dụng

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
76 từ không gian tên
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
95 để cố gắng tìm tích vô hướng của hai vectơ hàng 1x3. Vì thao tác này không được phép, nên NumPy tăng một số
# -*- coding: utf-8 -*-
15, tương tự như toán tử nhân ma trận

Thay vào đó, bạn cần thực hiện chuyển vị của một trong các đối số

>>>

def addition[num_1, num_2]:
    """Adds two numbers together.

    Example
    -------
    >>> total = addition[10, 20]
    >>> total
    30

    """
2

Trên dòng đầu vào 12, bạn đang thực hiện phép chuyển vị của vectơ hàng để biến nó thành vectơ cột bằng cách sử dụng thuộc tính chuyển vị [_______85_______12]. Điều này được thể hiện trong dòng đầu ra tương ứng, trong đó các thành phần được sắp xếp để tạo thành một cột cho mục đích in. Sau đó, bạn đang lấy tích vô hướng của vectơ với phép chuyển vị của nó, tạo ra một mảng có một giá trị duy nhất, 14. Lưu ý rằng đây là mảng 1x1, vì vậy để chỉ truy cập giá trị, bạn cần truy cập phần tử đầu tiên trong mỗi thứ nguyên

>>>

def addition[num_1, num_2]:
    """Adds two numbers together.

    Example
    -------
    >>> total = addition[10, 20]
    >>> total
    30

    """
3

Trong mã này, bạn đang xác minh rằng hình dạng là 1x1, sau đó truy cập phần tử đầu tiên trong mỗi thứ nguyên nằm ở chỉ mục thứ 0. Hãy nhớ rằng Python sử dụng 0 làm chỉ mục đầu tiên, không phải 1

Bạn có thể sử dụng các danh sách lồng nhau để tạo các mảng có hình dạng bất kỳ mà bạn muốn. Để tạo một mảng ba nhân ba [hai chiều], chỉ cần đưa ba phần tử vào mỗi danh sách trong số ba danh sách lồng nhau của bạn

>>>

def addition[num_1, num_2]:
    """Adds two numbers together.

    Example
    -------
    >>> total = addition[10, 20]
    >>> total
    30

    """
4

Trong mã này, bạn đã lồng ba danh sách với ba phần tử vào hàm tạo. Như được hiển thị trong hình, điều này tạo ra một mảng 3x3 với các phần tử từ 1 đến 9

Loại bỏ các quảng cáo

Tạo mảng rất linh hoạt trong NumPy

MATLAB và NumPy đều cho phép bạn chỉ định rõ ràng các phần tử cụ thể trong một mảng, như bạn đã thấy trong phần trước. Ngoài việc tạo mảng trực tiếp này, cả MATLAB và NumPy đều hỗ trợ một số phương pháp khác để tạo mảng mà không chỉ định rõ ràng từng phần tử. Dự án NumPy duy trì một danh sách chi tiết về

Nhiều chức năng hoạt động giống hệt nhau giữa MATLAB và NumPy. Điều này bao gồm các hàm thường được sử dụng như

# -*- coding: utf-8 -*-
21 và
# -*- coding: utf-8 -*-
22 để tạo dữ liệu có khoảng cách đều nhau và
# -*- coding: utf-8 -*-
23 và để tạo các mảng có hình dạng nhất định chứa đầy các số 1 và 0 tương ứng. Danh sách đầy đủ các cách tạo mảng trong NumPy được liệt kê trong tài liệu chính thức

Một điểm khác biệt lớn giữa MATLAB và NumPy về thủ tục tạo mảng là MATLAB chỉ hỗ trợ sử dụng dấu hai chấm để tạo mảng, trong khi NumPy thì không. Thay vào đó, NumPy sử dụng

# -*- coding: utf-8 -*-
25 để tạo một mảng giữa các giá trị được chỉ định

Trong MATLAB, bạn có thể sử dụng dấu hai chấm để tạo phạm vi đặc tả mảng. Nói chung, bạn có thể sử dụng tối đa 2 dấu hai chấm trong một đặc tả. Cú pháp như sau

def addition[num_1, num_2]:
    """Adds two numbers together.

    Example
    -------
    >>> total = addition[10, 20]
    >>> total
    30

    """
5

Trong cú pháp này, phương thức đầu tiên chỉ sử dụng một dấu hai chấm và chỉ định giá trị bắt đầu và kết thúc. Phương pháp thứ hai bao gồm dấu hai chấm thứ hai, trong đó giá trị trước dấu hai chấm đầu tiên là điểm bắt đầu, giá trị ở giữa là bước và giá trị cuối cùng là điểm dừng

Hãy thử những ví dụ này để thử nghiệm với cú pháp này

>>>

def addition[num_1, num_2]:
    """Adds two numbers together.

    Example
    -------
    >>> total = addition[10, 20]
    >>> total
    30

    """
6

Trong ví dụ này, bạn đang sử dụng dấu hai chấm đơn có bắt đầu và dừng để tạo một mảng có các giá trị từ 1 đến 6. Bạn có thể thấy rằng khi bước này bị bỏ qua, nó sẽ mặc định có giá trị là 1. Lưu ý rằng MATLAB bao gồm cả giá trị bắt đầu và kết thúc trong mảng và kích thước của mảng dài 6 phần tử. Tiếp theo, thay đổi giá trị của kích thước bước để tạo một mảng mới

>>>

def addition[num_1, num_2]:
    """Adds two numbers together.

    Example
    -------
    >>> total = addition[10, 20]
    >>> total
    30

    """
7

Trong ví dụ này, bạn đang sử dụng cú pháp hai dấu hai chấm với bắt đầu, bước và dừng. Giá trị bắt đầu là 1, bước là 2 và giá trị dừng là 6, vì vậy MATLAB bắt đầu bằng 1, tăng dần lên 3 rồi đến 5. Bước tiếp theo sẽ vượt quá giá trị dừng, vì vậy MATLAB không bao gồm giá trị dừng trong mảng. Tiếp theo, thay đổi giá trị bắt đầu để tạo một mảng mới khác

>>>

def addition[num_1, num_2]:
    """Adds two numbers together.

    Example
    -------
    >>> total = addition[10, 20]
    >>> total
    30

    """
8

Trong ví dụ này, bạn lại sử dụng phương thức hai dấu hai chấm, nhưng bạn đang chỉ định giá trị bắt đầu là 2 thay vì 1. Trong trường hợp này, MATLAB bắt đầu từ 2, tăng dần lên 4, tăng dần lên 6 và sau đó đạt đến giá trị dừng nên không tiếp tục. Lưu ý rằng trong trường hợp này, giá trị dừng của 6 được bao gồm trong mảng

Với NumPy, bạn có thể sử dụng

# -*- coding: utf-8 -*-
25 để tạo một mảng với các giá trị bắt đầu, dừng và bước cụ thể. Tuy nhiên,
# -*- coding: utf-8 -*-
25 có một điểm khác biệt lớn so với MATLAB, đó là giá trị dừng không được bao gồm trong mảng kết quả. Lý do cho điều này là kích thước của mảng bằng
# -*- coding: utf-8 -*-
28 đối với trường hợp mặc định có kích thước bước là 1. Lưu ý trong MATLAB rằng kích thước của mảng các số nguyên từ 1 đến 6 là 6, nhưng 6 - 1 = 5

Có ba cách để sử dụng

# -*- coding: utf-8 -*-
25

def addition[num_1, num_2]:
    """Adds two numbers together.

    Example
    -------
    >>> total = addition[10, 20]
    >>> total
    30

    """
9

Nếu bạn chỉ chuyển một đối số cho

# -*- coding: utf-8 -*-
25, nó sẽ được hiểu là giá trị dừng. Giá trị bắt đầu mặc định là 0 và bước mặc định là 1. Nếu bạn chuyển hai đối số cho
# -*- coding: utf-8 -*-
25, chúng được hiểu là giá trị bắt đầu và kết thúc. Cuối cùng, bạn có thể vượt qua cả ba điểm bắt đầu, dừng và bước tới
# -*- coding: utf-8 -*-
25

Lưu ý rằng thứ tự của các đối số khác với MATLAB, sẽ là

# -*- coding: utf-8 -*-
33,
# -*- coding: utf-8 -*-
34,
# -*- coding: utf-8 -*-
35 trong Python. Nếu bạn gặp khó khăn trong việc ghi nhớ thứ tự diễn ra của các đối số này, hãy nhớ rằng bạn có thể trình bày rõ ràng về ý nghĩa của từng đối số

Bạn có thể thử

# -*- coding: utf-8 -*-
25 với các ví dụ sau

>>>

In [2]: import antigravity
00

Trong ví dụ này, bạn đang tạo một mảng chứa các giá trị từ 1 đến 6. Như trong MATLAB, nếu bước bị bỏ qua, nó sẽ mặc định là 1. Lưu ý rằng bạn phải chuyển giá trị dừng 7 để mảng dừng ở 6. Tuy nhiên, kích thước của mảng kết quả dài 7 - 1 = 6 phần tử. Tiếp theo, bạn sẽ thấy cách thay đổi kích thước bước

>>>

In [2]: import antigravity
01

Trong đoạn mã này, bạn đang tạo một mảng chứa các giá trị từ 1 đến 6, tăng dần 2 giữa mỗi phần tử. Bước là hai, vì vậy NumPy bắt đầu bằng 1, tăng dần lên 3 rồi đến 5. Bước tiếp theo sẽ bằng giá trị dừng, nhưng NumPy không bao gồm giá trị dừng trong mảng. Lưu ý rằng công thức tính kích thước của mảng hơi khác một chút, vì kích thước bước không phải là 1

Với kích thước bước khác 1, kích thước của mảng có thể được tính bằng

# -*- coding: utf-8 -*-
37 nếu điều này dẫn đến một giá trị số nguyên. Trong trường hợp này, kích thước của mảng là [7 - 1]/2 = 3 phần tử, như mong đợi. Nếu
# -*- coding: utf-8 -*-
37 dẫn đến một số dấu phẩy động, kích thước của mảng bằng số nguyên lớn nhất tiếp theo như minh họa trong ví dụ tiếp theo

>>>

In [2]: import antigravity
02

Trong ví dụ này, bạn đang tạo một mảng chứa các giá trị từ 2 đến 6, tăng dần 2 giữa mỗi phần tử. Bước này là hai, vì vậy NumPy bắt đầu bằng 2, tăng dần lên 4 rồi đến 6. Bước tiếp theo sẽ vượt quá giá trị dừng, vì vậy NumPy dừng ở 6. Lưu ý rằng kích thước của mảng là [7 - 2]/2 = 2. 5, vì vậy số nguyên cao nhất tiếp theo là 3 phần tử, như mong đợi

Cuối cùng, bạn thường nên sử dụng các đối số số nguyên cho

# -*- coding: utf-8 -*-
25 trong NumPy và toán tử dấu hai chấm trong MATLAB. Nếu bạn sử dụng các giá trị dấu phẩy động [số có phần thập phân], đặc biệt là đối với bước này, các phần tử có thể không xuất hiện chính xác như bạn mong đợi. Nếu bạn muốn sử dụng số dấu phẩy động, nói chung,
# -*- coding: utf-8 -*-
21 là lựa chọn tốt hơn

Loại bỏ các quảng cáo

Toán tử dấu hai chấm rất mạnh trong NumPy

Trong MATLAB, toán tử dấu hai chấm được sử dụng để thực hiện một số tác vụ hữu ích. Như bạn đã thấy, nó có thể được sử dụng để tạo mảng và cũng có thể được sử dụng để lập chỉ mục hoặc cắt mảng. Khi lập chỉ mục cho mảng, MATLAB hỗ trợ từ khóa

In [2]: import antigravity
99 để mở rộng phạm vi đã chỉ định đến cuối kích thước đó, khi bạn

>>>

In [2]: import antigravity
03

Trong đoạn mã này, bạn đang lập chỉ mục

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 bắt đầu từ chỉ mục thứ hai và đi đến cuối mảng. Bạn cũng có thể chỉ định một chỉ mục cụ thể làm giá trị dừng

>>>

In [2]: import antigravity
04

In this code, you are creating an array

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20 with the numbers 1 through 6, inclusive. Then, you are specifying the second element as the start value and the fourth element as the stop value in the slice. MATLAB supports the two-colon increment syntax when indexing as well

>>>

In [2]: import antigravity
05

Trong mã này, bạn đang lập chỉ mục cho mảng, bắt đầu từ phần tử thứ hai, bỏ qua mọi phần tử khác, cho đến hết mảng. You can also use

In [2]: import antigravity
99 as the starting point of the slice with a negative step

>>>

In [2]: import antigravity
06

In this code, you are indexing

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20 starting from the last value, decrementing by 1, and ending at the 4th element. Finally, you can slice all of the element in a dimension by using just a bare colon

>>>

In [2]: import antigravity
07

In this code, you are selecting all of the first dimension of the array using just the colon

NumPy and Python in general also use the colon for the slice syntax, but the order of the values is slightly different. In Python, the order is

# -*- coding: utf-8 -*-
46, whereas in MATLAB, it is
# -*- coding: utf-8 -*-
47, as you saw earlier. In addition, in NumPy you can omit start or stop and they will have default a value of 0 [or the first element] for start and the last element for stop. In MATLAB, you must specify start and stop if you want to specify either of them. Thus, Python does not have the
In [2]: import antigravity
99 keyword, since you can omit
# -*- coding: utf-8 -*-
34 to achieve the same behavior

Try out the following examples of the slice syntax in NumPy

>>>

In [2]: import antigravity
08

In this code, you are creating an array with the integers from 1 to 6, inclusive, skipping every other number. Then, you are slicing the array taking the second element [index 1] until the end of the array. Notice that the stop value was omitted, so it defaulted to the last element in the array

You can also specify a specific element as the stop value. You saw in using

# -*- coding: utf-8 -*-
25 that the array did not include the stop value. The same is true of the slice syntax in Python, the slice will include everything up to, but not including, the stop index

>>>

In [2]: import antigravity
09

In this code, you are creating an array with the integers from 1 to 6, inclusive. Then, you are slicing the array starting at the second element [index 1, value 2] until the fourth element [index 3, value 4]. However, you specified the stop index as 4 [the fifth element in the array, value 5]. The reason Python includes up to the [stop - 1] index is the same reason

# -*- coding: utf-8 -*-
25 does not include the stop value, so that the length of the resulting array is equal to
# -*- coding: utf-8 -*-
28. Next, try changing the step of the slice

>>>

In [2]: import antigravity
10

In this code, you are slicing the array starting at the second element [index 1], going until the end of the array, and taking every second element. Điều này dẫn đến một mảng có các giá trị 2, 4 và 6. Notice that the stop value was omitted in the slice syntax, so it defaulted to the last element in the array

You can also use a negative step in the slicing syntax for Python

>>>

In [2]: import antigravity
11

In this code, you are not specifying the start index of the slice, you are specifying the stop value should be index 2, and the step should be -1. Since the start index is not specified and the step is negative, the start value is assumed to be the last element in the array [or the first element in the reversed array]. For the stop value, index 2 has the value of 3 and one index before that [in the reversed array] is index 3 with the value of 4

Finally, just like in MATLAB, a bare colon means to select all of the elements from that dimension

>>>

In [2]: import antigravity
12

Loại bỏ các quảng cáo

Các lát mảng là các dạng xem của mảng trong NumPy

Trong MATLAB, khi bạn truy cập một phần của mảng và gán nó cho một biến, MATLAB sẽ tạo một bản sao của phần mảng đó vào biến mới của bạn. Điều này có nghĩa là khi bạn gán giá trị cho lát cắt, mảng ban đầu không bị ảnh hưởng. Hãy thử ví dụ này để giúp giải thích sự khác biệt giữa MATLAB và Python

>>>

In [2]: import antigravity
13

Trong mã này, bạn đã tạo một mảng 3x3

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 lưu trữ các giá trị từ 1 đến 9. Sau đó, bạn tạo một lát cắt 2x2 của mảng ban đầu lưu trữ từ giá trị thứ hai đến cuối theo cả hai chiều,
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20. Ở dòng đầu vào thứ ba, bạn gán giá trị 10 cho phần tử phía trên bên trái trong
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20. Cuối cùng, bạn in lại
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 để xác minh rằng không có giá trị nào trong
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 thay đổi

Chi tiết kỹ thuật. MATLAB sử dụng hệ thống quản lý bộ nhớ sao chép khi ghi, trong đó một mảng chỉ có thể được sao chép sang một vị trí bộ nhớ mới khi nó được sửa đổi. Bạn có thể đọc thêm về quản lý bộ nhớ MATLAB trong Quản lý bộ nhớ cho hàm và biến trên blog Mathworks và trong Tối ưu hóa bộ nhớ trong Matlab

Trong NumPy, các lát mảng là dạng xem của mảng ban đầu. Hành vi này giúp tiết kiệm bộ nhớ và thời gian, vì các giá trị trong mảng không phải sao chép sang một vị trí mới. Tuy nhiên, điều đó có nghĩa là những thay đổi mà bạn thực hiện đối với một lát cắt từ một mảng sẽ thay đổi mảng ban đầu. Bạn nên thử đoạn mã sau để xem nó hoạt động như thế nào

>>>

In [2]: import antigravity
14

Trong mã này, bạn đang tạo một mảng 3x3

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 lưu trữ các giá trị từ 1 đến 9. Sau đó, bạn tạo một lát cắt 2x2 của mảng ban đầu lưu trữ từ giá trị thứ hai đến cuối theo cả hai chiều,
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20. Lưu ý rằng việc lập chỉ mục Python dựa trên 0, vì vậy phần tử thứ hai có chỉ mục 1. Cuối cùng, bạn đang in
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20 để xác minh rằng đó là một mảng 2x2

Bây giờ bạn sẽ thấy điều gì xảy ra khi bạn thay đổi một giá trị trong

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20. Giống như trong ví dụ MATLAB, bạn nên thay đổi phần tử phía trên bên trái của
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20

>>>

In [2]: import antigravity
15

Trong mã này, trước tiên bạn gán phần tử phía trên bên trái trong

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20, tại chỉ mục [0, 0] để có giá trị là 10. Sau đó, bạn in
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20 để xác minh rằng giá trị phù hợp đã thay đổi. Cuối cùng, bạn in ra
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 và thấy rằng giá trị ở giữa mảng đã thay đổi từ 5 thành 10

Đây là ý nghĩa của việc

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20 là quan điểm của
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50. Vì là một dạng xem, nên
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20 trỏ đến cùng một vị trí bộ nhớ như
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50, do đó, việc cập nhật
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20 cũng cập nhật
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 vì giá trị được lưu trữ trong vị trí bộ nhớ được truy cập bởi cả
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20 và
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 đã được cập nhật. Điều này cũng diễn ra theo một hướng khác, trong đó việc thay đổi giá trị trong
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 sẽ cập nhật giá trị trong
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20

>>>

In [2]: import antigravity
16

Trong mã này, bạn đang gán phần tử dưới cùng bên phải của

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 để có giá trị 42. Hãy nhớ rằng trong Python, chỉ số của
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
87 có nghĩa là giá trị cuối cùng trên thứ nguyên đó. Sau đó, bạn đang in
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 để xác minh rằng giá trị phía dưới bên phải đã thay đổi từ 9 thành 42. Cuối cùng, bạn đang in
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20, và bạn cũng thấy đối với
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20, giá trị dưới cùng bên phải đã thay đổi từ 9 thành 42

Nếu bạn muốn tạo một bản sao của một mảng, bạn có thể sử dụng

# -*- coding: utf-8 -*-
81. Sao chép một mảng sẽ tạo một vị trí mới trong bộ nhớ để lưu trữ bản sao, vì vậy những thay đổi đối với mảng đã sao chép không ảnh hưởng đến bản gốc

>>>

In [2]: import antigravity
17

Trong mã này, bạn đang tạo

# -*- coding: utf-8 -*-
82 dưới dạng bản sao của
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20. Sau đó, bạn đang thay đổi phần tử ở hàng thứ hai, cột đầu tiên để có giá trị là 37. Sau đó, bạn đang in
# -*- coding: utf-8 -*-
82 để xác minh rằng thay đổi được chỉ định đã được thực hiện. Cuối cùng, bạn đang in
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20 để xác minh rằng không có thay đổi nào xảy ra trong
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
20, như mong đợi

Mẹo và thủ thuật để tạo mã Pythonic của bạn

Giống như bất kỳ ngôn ngữ lập trình nào khác, mã Python được viết bởi các nhà phát triển Python có kinh nghiệm thường có giao diện đặc biệt. Điều này là do họ có thể tận dụng các thành ngữ cụ thể trong Python để làm việc với Python thay vì chống lại Python. Các nhà phát triển đến từ các ngôn ngữ khác thường bỏ lỡ điều gì tạo nên mã Pythonic trong các dự án đầu tiên của họ

Trong phần này, bạn sẽ tìm hiểu một số mẹo và thủ thuật để tạo mã Pythonic và nâng cao kỹ năng Python của bạn. Có nhiều mẹo và thủ thuật hơn bạn có thể tìm hiểu ở đây, vì vậy hãy xem Viết thêm mã Pythonic

Bạn không nên sử dụng dấu chấm phẩy để kết thúc dòng trong Python

Trong MATLAB, kết thúc một dòng mã bằng dấu chấm phẩy

# -*- coding: utf-8 -*-
87 sẽ chặn đầu ra từ dòng đó. Chẳng hạn, việc gán một biến sẽ in giá trị của biến sau khi gán nếu dấu chấm phẩy bị bỏ qua

Trong Python, bạn không nên kết thúc các dòng mã bằng dấu chấm phẩy. Điều đó là không cần thiết, vì Python không thay đổi hành vi của nó cho dù dòng có kết thúc bằng dấu chấm phẩy hay không. Vì vậy, bạn có thể tiết kiệm cho mình một lần nhấn phím và không bận tâm đến việc bao gồm dấu chấm phẩy trong tập lệnh và thư viện của mình

Có một trường hợp trong Python mà dấu chấm phẩy hữu ích. Khi bạn muốn thực hiện một số câu lệnh, nhưng bạn không thể đưa ký tự xuống dòng vào đầu vào, bạn có thể phân tách các câu lệnh bằng dấu chấm phẩy. Điều này chủ yếu hữu ích để thực thi các tập lệnh rất ngắn từ dấu nhắc lệnh hoặc thiết bị đầu cuối. Chẳng hạn, để tìm tệp thực thi Python cụ thể đang chạy, bạn có thể nhập lệnh sau

In [2]: import antigravity
18

Trong mã này, bạn đang thực thi trình thông dịch Python trong tệp thực thi

# -*- coding: utf-8 -*-
88 và chuyển công tắc
# -*- coding: utf-8 -*-
89. Công tắc này nhận đối số tiếp theo và thực thi nó trong trình thông dịch. Vì môi trường shell sẽ thực thi nếu bạn nhấn Enter để chèn một dòng mới, nên bạn có thể nhập toàn bộ tập lệnh trên một dòng.

Trong trường hợp này, bạn có hai câu lệnh logic cần được phân tách bằng dấu chấm phẩy. Trước tiên, bạn đang nhập thư viện

# -*- coding: utf-8 -*-
90 tích hợp và sau đó bạn in giá trị của
# -*- coding: utf-8 -*-
91. Trong ví dụ này, trình thông dịch Python mà trình bao đang chạy đến từ tệp
# -*- coding: utf-8 -*-
92

Bạn Không Nên Nhập
 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
02 Từ một Mô-đun trong Python

Trong một , bạn đọc về cách các không gian tên là một ý tưởng tuyệt vời trong Python. Trong MATLAB, theo mặc định, tất cả các hàm là một phần của không gian tên chung, vì vậy mọi hàm và tên lớp phải là duy nhất. Python giải quyết vấn đề này bằng cách sử dụng các không gian tên và yêu cầu bạn chỉ định chức năng sẽ đến từ mô-đun nào

Bạn sẽ tìm thấy các hướng dẫn trên Web gợi ý bạn viết như sau

In [2]: import antigravity
19

Trong mã này, bạn đang sử dụng

 1# -*- coding: utf-8 -*-
 2"""
 3Spyder Editor
 4
 5This is a temporary script file.
 6"""
02 để chỉ ra rằng Python nên nhập mọi thứ có trong
# -*- coding: utf-8 -*-
95 và đặt nó vào phạm vi hiện tại mà không cần tiền tố. Điều này thuận tiện hơn một chút, bởi vì bạn không còn phải thêm tiền tố vào các hàm và lớp từ
# -*- coding: utf-8 -*-
95 với bất kỳ thứ gì, bạn chỉ cần sử dụng chúng trực tiếp. Tuy nhiên, đó không phải là một phương pháp hay vì bạn không biết tên nào được định nghĩa trong
# -*- coding: utf-8 -*-
95 và liệu chúng có ghi đè bất kỳ tên hiện có nào trong phạm vi hiện tại của bạn hay không

Lưu ý kỹ thuật. Khi bạn

# -*- coding: utf-8 -*-
98, Python sẽ nhập tất cả các tên được liệt kê trong một biến đặc biệt có tên là
# -*- coding: utf-8 -*-
99 trong
# -*- coding: utf-8 -*-
95. Tuy nhiên, nếu biến đó không được xác định, Python sẽ nhập tất cả các biến, hàm và lớp được xác định trong
# -*- coding: utf-8 -*-
95

Bạn nên tận dụng các loại dữ liệu khác nhau trong Python

MATLAB, with its heritage as a linear algebra and array focused language, treats most data types as arrays of some sort. Điều này thường gây ra một chút khó khăn khi làm việc với các loại dữ liệu nâng cao hơn như

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
02,
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
03, mảng ô, v.v.

Python has several built-in data types that are very flexible and can be used to accomplish a number of useful tasks. Những cái chính mà bạn sẽ tìm hiểu trong phần này là danh sách và từ điển

danh sách

Python lists are mutable sequences of values. Danh sách có thể chứa dữ liệu không đồng nhất, nghĩa là mỗi phần tử của danh sách có thể thuộc một kiểu khác nhau. Vì danh sách có thể thay đổi nên bạn có thể thay đổi giá trị của bất kỳ thành phần nào trong danh sách hoặc thêm hoặc xóa giá trị khỏi danh sách mà không cần tạo đối tượng danh sách mới

Since lists are sequences, you can create loops that iterate over them. Trong Python, bạn không cần truy cập từng phần tử của danh sách có chỉ mục trong vòng lặp

In [2]: import antigravity
97, như bạn sẽ làm trong MATLAB

>>>

In [2]: import antigravity
20

Trong mã này, bạn đang tạo một mảng

11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 với các số nguyên từ 1 đến 6, lấy mọi số khác. Sau đó, bạn đang tạo một vòng lặp
In [2]: import antigravity
97 trong đó biến vòng lặp đi từ 1 đến độ dài của
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50. Finally, you are displaying the value of the element of
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50 at the loop variable on each step by using the loop variable
In [3]: var_1 = 10
In [4]: var_2 = 20
In [5]: var_3 = var_1 + var_2
In [6]: var_3
Out[6]: 30
26 to index
11# %% This is a code cell
12var_7 = 42
13var_8 = var_7 * 2
14
15# %% This is a second code cell
16print["This code will be executed in this cell"]
50

Trong Python, bạn không nên sử dụng chỉ mục cho danh sách khi lặp qua nó. Thay vào đó, bạn nên lặp trực tiếp các mục trong danh sách

>>>

In [2]: import antigravity
21

Trong mã này, trên dòng đầu vào 1, trước tiên bạn tạo danh sách Python có ba phần tử

  1. Số nguyên
    In [3]: var_1 = 10
    In [4]: var_2 = 20
    In [5]: var_3 = var_1 + var_2
    In [6]: var_3
    Out[6]: 30
    
    78
  2. Chuỗi
    function [total] = addition[num_1,num_2]
    % ADDITION  Adds two numbers together
    %   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
    %
    %   See also SUM and PLUS
    
    12
  3. The float
    function [total] = addition[num_1,num_2]
    % ADDITION  Adds two numbers together
    %   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
    %
    %   See also SUM and PLUS
    
    13

Danh sách này được chỉ định cho

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
14. Sau đó, bạn đang sử dụng vòng lặp
In [2]: import antigravity
97 để lần lượt truy cập từng mục trong danh sách. Trên mỗi lần lặp lại, giá trị tiếp theo trong danh sách được đưa vào biến
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
16 mà bạn đã chỉ định trên dòng
In [2]: import antigravity
97. Sau đó, bạn đang in giá trị của
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
16 trên mỗi lần lặp lại

Lưu ý trong ví dụ trước rằng bạn có thể lặp lại giá trị của từng phần tử trong danh sách mà không cần sử dụng chỉ mục. Tuy nhiên, đôi khi bạn muốn truy cập chỉ mục của từng mục trong danh sách khi bạn đang lặp lại nó. Đối với những trường hợp đó, Python cung cấp

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
19 trả về chỉ mục và giá trị của mục

>>>

In [2]: import antigravity
22

Trong mã này, bạn đang lặp lại

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
14, nhưng lần này, bạn đang sử dụng
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
19 để lấy cả chỉ mục và mục. Sau đó, bạn đang in giá trị của chỉ mục và mục trên mỗi lần lặp lại vòng lặp. Như bạn có thể thấy từ kết quả, các giá trị chỉ mục bắt đầu từ 0 như mong đợi, nhưng bạn không cần sử dụng chỉ mục để truy cập mục từ danh sách

Tóm lại, bạn không nên viết mã Python như thế này

In [2]: import antigravity
23

Trong mã này, bạn đang tạo một dải số nguyên từ 0 đến độ dài của

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
14 và sau đó bạn đang truy cập từng phần tử trong danh sách theo chỉ mục của nó. This can lead to off-by-one and errors. Instead, you should write code that loops over the list directly

In [2]: import antigravity
24

Bạn có thể đọc nhiều hơn về danh sách trong Danh sách và Bộ dữ liệu trong Python và về vòng lặp và phép lặp

In [2]: import antigravity
97 trong Python Vòng lặp “cho” [Lặp lại xác định]. There is also a more advanced concept called list comprehensions that you can learn about in Using List Comprehensions Effectively

từ điển

Trong MATLAB, bạn có thể tạo kiểu dữ liệu bản đồ bằng

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
24. Loại cấu trúc dữ liệu này rất hữu ích khi bạn có hai phần dữ liệu luôn liên quan đến nhau và bạn muốn kết nối chúng lại với nhau. Chẳng hạn, bạn có thể lập bản đồ các thành phố theo dân số của chúng bằng
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
24

>>>

In [2]: import antigravity
25

In this code, you are creating a

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
24 on the first line. Đối số đầu tiên là một mảng ô gồm các mảng ký tự có tên thành phố. Chúng được gọi là các phím của bản đồ. Đối số thứ hai là một mảng các quần thể. Đây được gọi là các giá trị của bản đồ. Then, you are accessing the value of the population in Cleveland by indexing the map with a character array

Bạn có thể gán các giá trị mới vào bản đồ bằng cách gán cho một giá trị khóa không xác định

>>>

In [2]: import antigravity
26

Nếu bạn cố truy cập một khóa không tồn tại, bạn sẽ nhận được thông báo lỗi

>>>

In [2]: import antigravity
27

Python có cấu trúc dữ liệu tương đương được gọi là từ điển. To create a Python dictionary, you can use curly braces and specify the keys and values with each other

>>>

In [2]: import antigravity
28

In this code, on input line 1 you are creating the dictionary of cities using curly braces. Lưu ý rằng khóa và giá trị được chỉ định cùng nhau, được phân tách bằng dấu hai chấm. Các giá trị được chỉ định với

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
16 trong các số, một tính năng có sẵn kể từ Python 3. 6. Điều này không làm thay đổi giá trị của số, nó chỉ giúp đọc các số rất lớn dễ dàng hơn. Sau đó, bạn đang truy cập giá trị tại khóa
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
28 bằng cách sử dụng dấu ngoặc vuông, tương tự như cú pháp lập chỉ mục cho danh sách và mảng

You can add new keys to the dictionary by assigning to them

>>>

In [2]: import antigravity
29

Trong mã này, bạn đã gán một khóa mới

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
29 cho từ điển với giá trị 180.393. Nếu bạn cố gắng truy cập một khóa không có trong từ điển, bạn sẽ nhận được một
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
30

>>>

In [2]: import antigravity
30

Trong đoạn mã này, bạn đang cố truy cập từ điển bằng phím

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
31. Tuy nhiên, khóa này không tồn tại trong từ điển nên Python tăng một số
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
30 để bạn biết rằng
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
31 không phải là một tùy chọn

Bạn có thể đọc nhiều hơn về từ điển Python trong Từ điển trong Python và

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
30 ngoại lệ trong Python KeyError Exceptions and How to Handle Them. Bạn cũng có thể lặp qua từ điển và sử dụng cách hiểu từ điển, tương tự như cách hiểu danh sách. Bạn có thể đọc về các chủ đề này trong Cách lặp qua từ điển trong Python

Ngoại lệ giúp bạn kiểm soát luồng chương trình trong Python

MATLAB và Python đều sử dụng lỗi và ngoại lệ để cho bạn biết khi có lỗi xảy ra trong mã. Trong phần này, bạn sẽ tìm hiểu về các ngoại lệ phổ biến trong Python và cách bạn có thể xử lý chúng một cách thích hợp

Nếu bạn muốn giới thiệu tổng thể về ngoại lệ Python, bạn có thể đọc Ngoại lệ Python. Một lời giới thiệu. Khi một ngoại lệ Python được đưa ra, nó sẽ tạo ra một truy nguyên. Bạn có thể đọc về cách diễn giải truy nguyên trong Tìm hiểu về Truy nguyên Python. Hiểu về truy nguyên là rất hữu ích để giải thích và sửa các ngoại lệ Python nói chung. Có một số trường hợp cụ thể thường có cách giải quyết giống nhau. Bạn sẽ thấy những thứ được mô tả trong phần còn lại của phần này

TênLỗi

Python

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
35 ngoại lệ thường là kết quả của một biến không được xác định. Khi bạn nhìn thấy một
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
35, hãy kiểm tra mã của bạn để tìm lỗi chính tả và tên biến sai chính tả. Bạn có thể sử dụng các tính năng sửa lỗi và trình khám phá biến trong Spyder để tìm ra biến nào được xác định

Lỗi cú pháp

Python

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
37 ngoại lệ có nghĩa là bạn đã nhập một số cú pháp không đúng. Điều này thường do dấu ngoặc không khớp gây ra, khi bạn chỉ có dấu ngoặc mở hoặc dấu ngoặc đóng chứ không phải dấu ngoặc khớp. Những trường hợp ngoại lệ này thường trỏ đến dòng sau nơi xảy ra sự cố

Một

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
37 phổ biến khác là chỉ sử dụng một dấu bằng trong câu lệnh
In [2]: import antigravity
96. Trong trường hợp này, ý của bạn là không bằng [_______86_______40] hoặc bằng [
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
41], vì vậy bạn có thể sửa dòng. Để biết thêm về
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
37 ngoại lệ, hãy xem Cú pháp không hợp lệ trong Python. Lý do phổ biến cho SyntaxError

Lỗi chính

Python

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
30 ngoại lệ xảy ra khi bạn cố gắng truy cập một khóa trong từ điển không tồn tại. Bạn có thể sử dụng để truy xuất khóa từ từ điển nếu khóa tồn tại hoặc trả về giá trị mặc định nếu khóa không tồn tại. Bạn có thể đọc thêm về
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
30 ngoại lệ trong Python KeyError Exceptions and How to Handle Them

Chỉ mụcLỗi

Python

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
46 ngoại lệ xảy ra khi bạn đang cố truy cập vào chỉ mục của một mảng hoặc danh sách không tồn tại. Điều này thường có nghĩa là mảng hoặc danh sách bạn đang cố truy cập có ít phần tử hơn chỉ mục mà bạn đang cố truy cập. Bạn có thể sử dụng các tính năng sửa lỗi và trình khám phá biến trong Spyder để xem kích thước của danh sách và mảng và đảm bảo rằng bạn chỉ truy cập các chỉ mục tồn tại

ImportError/ModuleNotFoundError

Các ngoại lệ của Python

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
47 và
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
48 xảy ra khi bạn cố gắng nhập một mô-đun mà Python không thể tìm thấy. Điều này có thể là do nó được cài đặt trong một môi trường
In [2]: import antigravity
32 hoặc
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
50 khác hoặc có thể là do bạn quên cài đặt gói

Giải pháp cho lỗi này thường là

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
51 hoặc
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
52 gói và đảm bảo kích hoạt đúng môi trường. Nếu bạn không sử dụng môi trường
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
53 trong
In [2]: import antigravity
32, bạn cũng cần đảm bảo cài đặt Spyder hoặc Jupyter vào môi trường của mình

TypeError/ValueError

Python

 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
61 ngoại lệ xảy ra khi một đối số không đúng loại. Điều này thường xảy ra nhất khi bạn chuyển một đối số sai kiểu vào một hàm. Chẳng hạn, một hàm làm việc với các số sẽ tăng giá trị
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
61 nếu một chuỗi được truyền vào

Một ngoại lệ liên quan là

# -*- coding: utf-8 -*-
15. Ngoại lệ này xảy ra khi một đối số thuộc loại chính xác, nhưng có giá trị không chính xác. Chẳng hạn, một hàm chỉ hoạt động với các số dương sẽ tăng
# -*- coding: utf-8 -*-
15 nếu một số âm được truyền vào

Lỗi thuộc tính

Python

In [7]: runfile['C:/Users/Eleanor/.spyder-py3/temp.py',
   ...:         wdir='C:/Users/Eleanor/.spyder-py3']
15 ngoại lệ xảy ra khi bạn cố gắng truy cập một thuộc tính của một đối tượng khi đối tượng không có thuộc tính đó. Bạn sẽ thường thấy lỗi này liên quan đến thông báo
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
60. Thông báo này rất có thể có nghĩa là một hàm đã trả về
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
01 thay vì đối tượng mà bạn mong đợi và bạn đang cố truy cập một thuộc tính sẽ có trên đối tượng thực, nhưng không được xác định cho
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
01

Cách xử lý ngoại lệ trong Python

MATLAB cho phép bạn

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
63 một câu lệnh mã và
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
64 bất kỳ lỗi nào do mã đưa ra. Khi bạn đã phát hiện ra lỗi, bạn có thể xử lý thêm lỗi và gán các biến dựa trên loại lỗi. Tài liệu MATLAB có một số ví dụ hay về giao diện của nó trong MATLAB

Trong Python, một điểm khác biệt lớn so với MATLAB là bạn có thể chọn chỉ bắt một số loại ngoại lệ nhất định và xử lý chúng. Điều này cho phép tất cả các ngoại lệ khác tiếp tục được hiển thị cho người dùng. Nếu bạn muốn tìm hiểu thêm về cách thực hiện điều này trong Python, bạn có thể đọc

Để xem cách thức hoạt động của nó, bạn có thể thử ví dụ sau

>>>

In [2]: import antigravity
31

Trong mã này, trên dòng đầu vào 1, bạn đang nhập thư viện

In [2]: import antigravity
88 tích hợp. Sau đó, bắt đầu từ dòng đầu vào 2, bạn đang xác định một hàm có tên là
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
68 sẽ nhận một đối số, được gọi là
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
69. Bên trong định nghĩa hàm, trước tiên bạn in đối số mà người dùng đã chuyển

Tiếp theo, bạn nhập khối

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
63/
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
66. Đầu tiên, bạn thử lấy căn bậc hai của đối số đầu vào và trả về kết quả. Nếu lấy căn bậc hai của đối số dẫn đến lỗi, Python sẽ bắt lỗi đó và kiểm tra loại lỗi nào đã được đưa ra

Bạn đã xác định mã xử lý hai trường hợp ngoại lệ cụ thể.

# -*- coding: utf-8 -*-
15 và
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
61. Nếu
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
90 tăng
# -*- coding: utf-8 -*-
15, mã của bạn sẽ in thông báo rằng số này không thể thao tác được. Nếu _______61_______90 tăng ____61_______61, mã của bạn sẽ in thông báo rằng đối số không phải là số. Nếu bất kỳ loại ngoại lệ nào khác được đưa ra bởi
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
90, lỗi đó sẽ được chuyển qua mà không có bất kỳ xử lý nào, vì không có trình xử lý nào cho bất kỳ loại lỗi nào khác

Cụ thể hơn, Python kiểm tra bất kỳ lỗi nào do mã đưa ra trong khối

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
63. Trong trường hợp của bạn, bạn chỉ xác định một dòng mã trong khối
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
63, nhưng điều này là không bắt buộc và bạn có thể có bao nhiêu dòng tùy thích ở đó. Tuy nhiên, thông thường nên giảm thiểu số lượng dòng mã trong khối
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
63 để bạn có thể xác định cụ thể mã nào đang gây ra bất kỳ lỗi nào

Trên dòng đầu vào 3, bạn đang kiểm tra

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
68. Đầu tiên, bạn chuyển giá trị 4. 0 vào chức năng. Hàm in đối số và
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
90 không gặp vấn đề gì khi lấy căn bậc hai của 4, kết quả là 2. 0 trên dòng đầu ra

Trên dòng đầu vào 4, bạn đang chuyển -1. 0 làm đối số cho

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
68. Như bạn có thể nhớ lại, việc lấy căn bậc hai của số âm sẽ dẫn đến một số phức mà hàm
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
90 không được trang bị để xử lý. Lấy căn bậc hai của một số âm bằng cách sử dụng
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
90 sẽ tăng một
# -*- coding: utf-8 -*-
15. Trình xử lý ngoại lệ của bạn bắt được
# -*- coding: utf-8 -*-
15 này và in thông báo rằng số này không thể thao tác được

Trên dòng đầu vào 5, bạn đang chuyển

function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
89 làm đối số cho
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
68. Trong trường hợp này,
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
90 không biết cách lấy căn bậc hai của một chuỗi, mặc dù chuỗi đó biểu thị một số. Bạn có thể thấy rằng bạn đã chuyển một chuỗi bằng dấu ngoặc kép trong câu lệnh đưa ra giá trị của đối số.
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
92. Vì
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
90 không thể lấy căn bậc hai của một chuỗi, nên nó sẽ trả về một giá trị
 8var_4 = 10
 9var_5 = 20
10var_6 = var_4 + var_5
61 và hàm của bạn sẽ in ra thông báo rằng đối số không phải là số

Có Hướng dẫn chính thức để viết mã tốt bằng Python

Cộng đồng Python đã phát triển một bộ đề xuất về cách định kiểu mã Python của bạn. Chúng được hệ thống hóa trong một tài liệu có tên PEP 8, viết tắt của Đề xuất cải tiến Python #8. PEP 8 có thể được tìm thấy đầy đủ trên trang web Python. Bạn cũng có thể tìm hiểu thêm về phong cách Python tốt trong Cách viết mã Python đẹp với PEP 8 và Python thành ngữ 101

Có lẽ nguyên tắc quan trọng nhất trong PEP 8 là câu nói rằng “sự nhất quán ngu ngốc là con yêu tinh của những bộ óc nhỏ bé. ” Điều này có nghĩa là bạn nên tuân theo các khuyến nghị trong PEP 8 cho hầu hết tất cả mã của mình, nhưng có thể có một số trường hợp hạn chế mà bạn không nên tuân theo các khuyến nghị của PEP 8. Chẳng hạn, nếu bạn đang làm việc với một cơ sở mã hiện có có phong cách riêng, bạn nên tuân theo phong cách đó khi nó khác với PEP 8. Bạn có thể xem một cuộc thảo luận tuyệt vời về nguyên tắc này từ Raymond Hettinger, một trong những nhà phát triển cốt lõi của Python, trong một

Ngoài việc đọc PEP 8, bạn có thể sử dụng một vài gói Python để tự động đảm bảo rằng mã của bạn phù hợp với các nguyên tắc về kiểu dáng. Flake8 là một kẻ nói dối mã đọc mã của bạn và đưa ra đề xuất về cách bạn có thể cải thiện nó. Điều này tương tự như tính năng trong trình soạn thảo mã MATLAB giúp đưa ra các đề xuất cải tiến. Ngoài ra, các gói như Black, yapf và autopep8 sẽ tự động định dạng mã của bạn để tuân thủ PEP 8 hoặc các quy tắc kiểu của riêng bạn. Sử dụng các gói này có thể giúp mã của bạn có cảm giác Pythonic hơn và giúp bạn học phong cách Python tốt

Python có một cộng đồng hỗ trợ và tuyệt vời

Python được biết đến vì có một cộng đồng rất hỗ trợ, cởi mở và thân thiện. Cho dù bạn là một nhà phát triển hoàn toàn mới hay một nhà phát triển có kinh nghiệm, cho dù bạn là người mới sử dụng Python hay đã tham gia hàng chục hội nghị, cộng đồng luôn sẵn sàng hỗ trợ bạn và những gì bạn muốn làm

Cộng đồng bắt đầu với Chỉ mục gói Python [được gọi là PyPI hoặc CheeseShop, tham chiếu đến bản phác thảo Monty Python], chứa hàng trăm nghìn gói Python khác nhau mà bạn có thể tải xuống miễn phí. Các gói này có thể được cài đặt bằng cách sử dụng

In [2]: import antigravity
40, trình quản lý gói đi kèm với Python. Điều này có nghĩa là việc thêm chức năng bạn cần vào Python có thể đơn giản như
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
96 hoặc nếu bạn đang sử dụng Anaconda,
function [total] = addition[num_1,num_2]
% ADDITION  Adds two numbers together
%   TOTAL = ADDITION[NUM_1,NUM_2] adds NUM_1 and NUM_2 together
%
%   See also SUM and PLUS
97

Vì Python được sử dụng trong rất nhiều lĩnh vực phát triển phần mềm, khoa học dữ liệu, khoa học và kỹ thuật khác nhau, nên luôn có những người xung quanh muốn nói về Python. Hầu hết các thành phố lớn trên thế giới đều có các nhóm gặp gỡ Python. Bạn có thể vào các nhóm này để tìm hiểu về Python bằng cách nghe mọi người nói về công việc của họ hoặc làm việc trên một số mã nguồn mở

Một vài lần trong năm, các nhóm này hợp nhất thành các PyCon khác nhau diễn ra ở mọi châu lục trên toàn cầu. PyCon Bắc Mỹ là lớn nhất trong số này, với vài nghìn người tham dự mỗi năm. Bạn có thể đọc tất cả về những gì nó muốn tham dự trong Cách tận dụng tối đa PyCon

Python cũng có một cộng đồng trực tuyến rất mạnh. Nếu bạn có câu hỏi về lập trình bằng Python, bạn có thể hỏi trên StackOverflow và một số chuyên gia Python hàng đầu thế giới sẽ có thể giúp bạn. Đảm bảo làm theo hướng dẫn về cách đặt câu hỏi trên StackOverflow. Hãy nhớ rằng bạn càng đặt nhiều nỗ lực vào câu hỏi của mình thì bạn càng có nhiều khả năng tự mình tìm ra câu trả lời [hoan hô. ] hoặc nhận được câu trả lời hay từ người khác

Nếu bạn muốn theo dõi quá trình phát triển của Python, bạn có thể đăng ký một trong các danh sách gửi thư bao gồm các khía cạnh khác nhau của cộng đồng Python. Danh sách gửi thư chung để đặt câu hỏi về cách viết chương trình bằng Python được gọi là comp. lang thang. con trăn. Nếu bạn quan tâm đến việc phát triển Python, bạn có thể theo dõi danh sách gửi thư của python-dev

Nếu bạn muốn tìm hiểu nhiều, nhiều hơn nữa về phát triển Python, bạn có thể xem Lộ trình học Python thực

Các lĩnh vực mà bạn vẫn nên sử dụng MATLAB®

Mặc dù có cộng đồng tuyệt vời và các gói tuyệt vời, nhưng vẫn có một hoặc hai lĩnh vực mà MATLAB hoạt động tốt hơn Python. Nơi chính mà Python không thể cạnh tranh với MATLAB là Hộp công cụ Simulink. Hộp công cụ này cung cấp các khả năng nâng cao để xử lý và mô hình hóa tín hiệu trong một giao diện đồ họa thuận tiện

Python không có giao diện đồ họa tương đương với các loại chức năng này. Tuy nhiên, trong phạm vi Simulink là một giao diện thuận tiện cho các bộ giải phương trình vi phân thông thường, Python có các bộ giải tương đương như trong MATLAB và chức năng cơ bản của Simulink chắc chắn có thể được sao chép trong Python

Mặt khác, bạn có thể làm bất cứ điều gì trong Python mà bạn có thể làm trong MATLAB. Nếu bạn có thể nghĩ ra công việc mà bạn có thể làm với MATLAB, nhưng bạn không chắc chắn cách thực hiện nó trong Python, hãy cho chúng tôi biết trong các nhận xét và chúng tôi sẽ có thể trợ giúp với các đề xuất

Phần kết luận

Xin chúc mừng, giờ bạn đã có kiến ​​thức cần thiết để chuyển mã MATLAB sang Python. Trong bài viết này, bạn đã tìm hiểu một chút về Python là gì, cách thiết lập máy tính của bạn để sử dụng Python và cách chuyển đổi mã của bạn từ MATLAB sang Python

Python là một ngôn ngữ và cộng đồng thực sự rộng lớn, có rất nhiều thứ để học và rất nhiều người để học hỏi. Hãy nhớ rằng, bạn không phải là chuyên gia MATLAB khi lần đầu tiên mở môi trường phát triển MATLAB và điều này cũng đúng với lần đầu tiên bạn viết mã Python. Hãy quay lại bài viết này thường xuyên nếu bạn cần cải thiện kỹ năng của mình và tìm hiểu thêm về cách trở thành một thuật sĩ Python

Đọc thêm

Có rất nhiều tài nguyên trên Web đề cập đến sự khác biệt giữa MATLAB và Python. Dưới đây là một số tài nguyên mà tôi thấy hữu ích khi chuyển đổi từ MATLAB sang Python

  • Hội thảo trực tuyến. Python dành cho người dùng MATLAB, Những điều bạn cần biết [Video]
  • Sách trắng MATLAB sang Python
  • Matlab so với. Julia vs. con trăn
  • Tám ưu điểm của Python so với MATLAB
  • 10 lý do khiến Python thành công trong nghiên cứu [và một số lý do khiến nó không]

Đánh dấu là đã hoàn thành

🐍 Thủ thuật Python 💌

Nhận một Thủ thuật Python ngắn và hấp dẫn được gửi đến hộp thư đến của bạn vài ngày một lần. Không có thư rác bao giờ. Hủy đăng ký bất cứ lúc nào. Được quản lý bởi nhóm Real Python

Gửi cho tôi thủ thuật Python »

Giới thiệu về Bryan Weber

Bryan là nhà phát triển cốt lõi của Cantera, nền tảng mã nguồn mở cho nhiệt động lực học, động học hóa học và vận chuyển. Là một nhà phát triển nói chung, Bryan thực hiện Python từ web đến khoa học dữ liệu và mọi nơi ở giữa

» Thông tin thêm về Bryan

Mỗi hướng dẫn tại Real Python được tạo bởi một nhóm các nhà phát triển để nó đáp ứng các tiêu chuẩn chất lượng cao của chúng tôi. Các thành viên trong nhóm đã làm việc trong hướng dẫn này là

Aldren

Geir Arne

Joanna

Bậc thầy Kỹ năng Python trong thế giới thực Với quyền truy cập không giới hạn vào Python thực

Tham gia với chúng tôi và có quyền truy cập vào hàng nghìn hướng dẫn, khóa học video thực hành và cộng đồng các Pythonistas chuyên gia

Nâng cao kỹ năng Python của bạn »

Chuyên gia Kỹ năng Python trong thế giới thực
Với quyền truy cập không giới hạn vào Python thực

Tham gia với chúng tôi và có quyền truy cập vào hàng ngàn hướng dẫn, khóa học video thực hành và cộng đồng Pythonistas chuyên gia

Nâng cao kỹ năng Python của bạn »

Bạn nghĩ sao?

Đánh giá bài viết này

Tweet Chia sẻ Chia sẻ Email

Bài học số 1 hoặc điều yêu thích mà bạn đã học được là gì?

Mẹo bình luận. Những nhận xét hữu ích nhất là những nhận xét được viết với mục đích học hỏi hoặc giúp đỡ các sinh viên khác. và nhận câu trả lời cho các câu hỏi phổ biến trong cổng thông tin hỗ trợ của chúng tôi

Làm cách nào để sử dụng NumPy trong MATLAB?

Liên kết trực tiếp tới câu trả lời này .
Mở lời nhắc Anaconda [đi kèm với gói]. .
Thay đổi thư mục thành thư mục chứa tệp thực thi matlab. .
Chạy matlab bằng cách chỉ chạy lệnh "matlab" trong dấu nhắc
Xác minh bằng cách sử dụng một cái gì đó như "py

NumPy có dựa trên Matlab không?

Ngôn ngữ kịch bản của MATLAB được tạo cho đại số tuyến tính nên cú pháp cho một số thao tác mảng nhỏ gọn hơn của NumPy. Mặt khác, API để thêm GUI và tạo các ứng dụng chính thức ít nhiều là một suy nghĩ sau. NumPy dựa trên Python, một ngôn ngữ đa năng .

Python có nhanh hơn Matlab không?

Matlab nhanh hơn Python , nhưng Python chạy song song nhiều tác vụ tốt hơn.

Sự khác biệt giữa * và * trong Matlab là gì?

* là phép nhân ma trận trong khi. * là phép nhân theo phần tử . Để sử dụng toán tử đầu tiên, toán hạng phải tuân theo quy tắc nhân ma trận về kích thước.

Chủ Đề