MATLAB tạo đối tượng Python

To use it, subclass the

In [2]: import antigravity
98 abstract base class, and define your own constructor. In particular, the subclass must define the
In [2]: import antigravity
99 and
In [2]: import antigravity
00 properties.
In [2]: import antigravity
99 is a reference to the constructed Python object and
In [2]: import antigravity
00 is a string being the full class name as returned by
In [2]: import antigravity
03 in Python. For example, to wrap a class
In [2]: import antigravity
04 in module
In [2]: import antigravity
05 which is on the Python path, the Matlab constructor could specify
In [2]: import antigravity
06 and
In [2]: import antigravity
07. The constructor should then call the
In [2]: import antigravity
990 method to create dummy Matlab properties so that tab-completion will work

Show

An example is given by the

In [2]: import antigravity
991 class

The derived Matlab class can access all properties and call all methods of the wrapped Python class with the standard dot notation. Hidden Python properties (which starts with

In [2]: import antigravity
992) can be accessed using brace notation, e. g.
In [2]: import antigravity
993

The wrapper also performs some simple type conversions between Matlab and Python, but this is one area where many isses arise as Matlab and Python data types do not exactly match. Thus, you should carefully check the data transfered to Python and returned to Matlab are what you expect

In particular the wrapper assumes

In [2]: import antigravity
994 is installed and will convert Matlab numeric arrays to
In [2]: import antigravity
994 arrays, in order to take advantage of features which ensure that fewer data copies are made (at least for an "in-process" Python environment). However, the conversion from Matlab to
In [2]: import antigravity
994 array is done internally by matlab and can sometimes result in numpy arrays which are automatically "squeezed" (missing singleton dimensions) or transposed. If you find issues with the type conversion, please create an issue here

Finally, the wrapper provides a

In [2]: import antigravity
997 method so that
In [2]: import antigravity
998 will return the Python (
In [2]: import antigravity
999) help information for that object, method or property. There are also overloaded
In [2]: import antigravity
997 and
In [2]: import antigravity
001 functions in the
In [2]: import antigravity
002 folder which will work with the
In [2]: import antigravity
003 /
In [2]: import antigravity
004 syntax (e. g. without the brackets and without needing to construct an object), but these are not part of the
In [2]: import antigravity
005 class and so the
In [2]: import antigravity
002 folder needs to be added to the path separately

The

In [2]: import antigravity
007 and
In [2]: import antigravity
008 methods of the wrapper are also overloaded to serialise dependent Python objects using
In [2]: import antigravity
009, so they can be saved as to a Matlab
In [2]: import antigravity
990 file. Note that objects which cannot be pickled (which do not have a
In [2]: import antigravity
991 or
In [2]: import antigravity
992 methods) cannot be saved correctly. In these cases a warning will be given and a
In [2]: import antigravity
990 file will still be generated but it will not correctly reload

MATLAB® is widely known as a high-quality environment for any work that involves arrays, matrices, or linear algebra. Python is newer to this arena but is becoming increasingly popular for similar tasks. As you’ll see in this article, Python has all of the computational power of MATLAB for science tasks and makes it fast and easy to develop robust applications. However, there are some important differences when comparing MATLAB vs Python that you’ll need to learn about to effectively switch over

In this article, you’ll learn how to

  • Evaluate the differences of using MATLAB vs Python
  • Set up an environment for Python that duplicates the majority of MATLAB functions
  • Convert scripts from MATLAB to Python
  • Avoid common issues you might have when switching from MATLAB to Python
  • Write code that looks and feels like Python

Free Bonus. Click here to get access to a free NumPy Resources Guide that points you to the best tutorials, videos, and books for improving your NumPy skills

MATLAB vs Python. Comparing Features and Philosophy

Python is a high-level, general-purpose programming language designed for ease of use by human beings accomplishing all sorts of tasks. Python was created by Guido van Rossum and first released in the early 1990s. Python is a mature language developed by hundreds of collaborators around the world

Python is used by developers working on small, personal projects all the way up to some of the largest internet companies in the world. Not only does Python run Reddit and Dropbox, but the original Google algorithm was written in Python. Also, the Python-based Django Framework runs Instagram and many other websites. On the science and engineering side, the data to create the 2019 photo of a black hole was processed in Python, and major companies like Netflix use Python in their data analytics work

There is also an important philosophical difference in the MATLAB vs Python comparison. MATLAB is proprietary, closed-source software. For most people, a license to use MATLAB is quite expensive, which means that if you have code in MATLAB, then only people who can afford a license will be able to run it. Plus, users are charged for each additional toolbox they want to install to extend the basic functionality of MATLAB. Aside from the cost, the MATLAB language is developed exclusively by 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
  • Các kiểu dữ liệu cơ bản trong Python
  • 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. This means that Python code can be ported between all of the major operating system platforms and CPU architectures out there, with only small changes required for different platforms. There are distributions of Python for desktop and laptop CPUs and microcontrollers like Adafruit. Python can also talk to other microcontrollers like Arduino with a simple programming interface that is almost identical no matter the host operating system

For all of these reasons, and many more, Python is an excellent choice to replace MATLAB as your programming language of choice. Now that you’re convinced to try out Python, read on to find out how to get it on your computer and how to switch from MATLAB

Note. GNU Octave is a free and open-source clone of MATLAB. In this sense, GNU Octave has the same philosophical advantages that Python has around code reproducibility and access to the software

Octave’s syntax is mostly compatible with MATLAB syntax, so it provides a short learning curve for MATLAB developers who want to use open-source software. However, Octave can’t match Python’s community or the number of different kinds of applications that Python can serve, so we definitely recommend you switch whole hog over to Python

Besides, this website is called Real Python, not Real Octave 😀

Remove ads

Setting Up Your Environment for Python

In this section, you’ll learn

  • How to install Python on your computer for a seamless transition from MATLAB
  • How to install replacements for the MATLAB integrated development environment
  • How to use the replacements for MATLAB on your computer

Getting Python via Anaconda

Python can be downloaded from a number of different sources, called distributions. For instance, the Python that you can download from the official Python website is one distribution. Another very popular Python distribution, particularly for math, science, engineering, and data science applications, is the Anaconda distribution

There are two main reasons that Anaconda is so popular

  1. Anaconda distributes pre-built packages for Windows, macOS, and Linux, which means that the installation process is really easy and the same for all three major platforms

  2. Anaconda includes all of the most popular packages for engineering and data science type workloads in one single installer

For the purposes of creating an environment that is very similar to MATLAB, you should download and install Anaconda. As of this writing, there are two major versions of Python available. Python 2 and Python 3. You should definitely install the version of Anaconda for Python 3, since Python 2 will not be supported past January 1, 2020. Python 3. 7 is the most recent version at the time of this writing, but Python 3. 8 should be out a few months after this article is published. Either 3. 7 hoặc 3. 8 will work the same for you, so choose the most recent version you can

Once you have downloaded the Anaconda installer, you can follow the default set up procedures depending on your platform. You should install Anaconda in a directory that does not require administrator permission to modify, which is the default setting in the installer

With Anaconda installed, there are a few specific programs you should know about. The easiest way to launch applications is to use the Anaconda Navigator. On Windows, you can find this in the Start Menu and on macOS you can find it in Launchpad. Here’s a screenshot of the Anaconda Navigator on Windows

MATLAB tạo đối tượng Python

In the screenshot, you can see several installed applications, including JupyterLab, Jupyter Notebook, and Spyder, that you’ll learn more about later in this tutorial

On Windows, there is one other application that you should know about. This is called Anaconda Prompt, and it is a command prompt set up specifically to work with

In [2]: import antigravity
32 on Windows. If you want to type
In [2]: import antigravity
32 commands in a terminal, rather than using the Navigator GUI, then you should use Anaconda Prompt on Windows

On macOS, you can use any terminal application such as the default Terminal. app or iTerm2 to access

In [2]: import antigravity
32 from the command line. On Linux, you can use the terminal emulator of your choice and which specific emulator is installed will depend on your Linux distribution

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 is a distribution of Python that includes many of the necessary packages for scientific work of all kinds.
In [2]: import antigravity
32 là một phần mềm quản lý gói đa nền tảng được bao gồm trong 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 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ỉ khả dụng 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

MATLAB tạo đối tượng Python

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

MATLAB tạo đối tượng Python

Ở 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ổ. Hơn nữa, bất kỳ biến nào bạn tạo trong bảng điều khiển sẽ được hiển thị trong trình khám phá biến ở ngăn trên cùng bên phải

Lưu ý rằng bạn có thể điều chỉnh kích thước của bất kỳ ngăn nào bằng cách đưa chuột lên dải phân cách giữa các ngăn, bấm và kéo cạnh theo kích thước bạn muốn. Bạn có thể đóng bất kỳ ngăn nào bằng cách nhấp vào x ở đầu ngăn

Bạn cũng có thể ngắt bất kỳ ngăn nào ra khỏi cửa sổ chính bằng cách nhấp vào nút trông giống như hai cửa sổ ở đầu ngăn, ngay bên cạnh dấu x đóng ngăn đó. Khi một cửa sổ được chia ra khỏi cửa sổ chính, bạn có thể kéo nó xung quanh và sắp xếp lại nó theo cách bạn muốn. Nếu bạn muốn đặt ngăn trở lại cửa sổ chính, hãy kéo ngăn đó bằng chuột để nền màu xanh lam hoặc xám trong suốt xuất hiện và các ngăn bên cạnh thay đổi kích thước, sau đó thả tay và ngăn sẽ khớp vào vị trí

Khi bạn đã sắp xếp các ngăn chính xác theo cách mình muốn, bạn có thể yêu cầu Spyder lưu bố cục. Chuyển đến menu Xem và tìm lại cửa sổ thả xuống Bố cục cửa sổ. Sau đó nhấp vào Lưu bố cục hiện tại và đặt tên cho nó. Điều này cho phép bạn đặt lại về bố cục ưa thích của mình bất kỳ lúc nào nếu có điều gì đó vô tình bị thay đổi. You can also reset to one of the default configurations from this menu

Chạy câu lệnh trong Bảng điều khiển trong Spyder

Trong phần này, bạn sẽ viết một số lệnh Python đơn giản, nhưng đừng lo lắng nếu bạn chưa hiểu ý nghĩa của chúng. Bạn sẽ tìm hiểu thêm về cú pháp Python sau trong bài viết này. Những gì bạn muốn làm ngay bây giờ là hiểu giao diện của Spyder giống và khác với giao diện MATLAB như thế nào

Bạn sẽ làm việc rất nhiều với bảng điều khiển Spyder trong bài viết này, vì vậy bạn nên tìm hiểu về cách thức hoạt động của nó. Trong bảng điều khiển, bạn sẽ thấy một dòng bắt đầu bằng

In [2]: import antigravity
44, cho dòng đầu vào 1. Spyder (thực sự, bảng điều khiển IPython) đánh số tất cả các dòng đầu vào mà bạn nhập. Vì đây là đầu vào đầu tiên bạn nhập nên số dòng là 1. Trong phần còn lại của bài viết này, bạn sẽ thấy các tham chiếu đến “dòng đầu vào X”, trong đó X là số trong ngoặc vuông

Một trong những điều đầu tiên tôi muốn làm với những người mới làm quen với Python là cho họ thấy Zen of Python. Bài thơ ngắn này giúp bạn hiểu Python là gì và cách tiếp cận làm việc với Python

Để xem Zen của Python, hãy nhập

In [2]: import antigravity
45 trên dòng đầu vào 1 rồi chạy mã bằng cách nhấn Enter . Bạn sẽ thấy một đầu ra như bên dưới.

>>>

In [2]: import antigravity
4

Mã này có

In [2]: import antigravity
45 trên dòng đầu vào 1. Đầu ra từ việc chạy
In [2]: import antigravity
45 là in Zen của Python lên bàn điều khiển. Chúng ta sẽ trở lại một số khổ thơ trong bài thơ này ở phần sau của bài viết

Trong nhiều khối mã trong bài viết này, bạn sẽ thấy ba dấu lớn hơn (

In [2]: import antigravity
48) ở trên cùng bên phải của khối mã. Nếu bạn nhấp vào đó, nó sẽ xóa dấu nhắc đầu vào và mọi dòng đầu ra, vì vậy bạn có thể sao chép và dán mã ngay vào bảng điều khiển của mình

Nhiều Pythonistas duy trì khiếu hài hước lành mạnh. Điều này được hiển thị ở nhiều nơi trong ngôn ngữ, bao gồm cả Zen of Python. Đối với một mã khác, trong bảng điều khiển Spyder, hãy nhập mã sau đây, sau đó là Enter để chạy mã đó.

>>>

In [2]: import antigravity

Câu lệnh đó sẽ mở trình duyệt web của bạn đến webcomic có tên là XKCD, cụ thể là truyện tranh #353, nơi tác giả đã phát hiện ra rằng Python đã cho anh ta khả năng bay

Bây giờ bạn đã chạy thành công hai câu lệnh Python đầu tiên của mình. Chúc mừng 😃🎉

Nếu bạn xem Nhật ký lịch sử, bạn sẽ thấy hai lệnh đầu tiên bạn đã nhập trong bảng điều khiển (

In [2]: import antigravity
45 và
In [2]: import antigravity
50). Let’s define some variables and do some basic arithmetic now. Trong bảng điều khiển, nhập các câu lệnh sau, nhấn Enter sau mỗi câu lệnh.

>>>

In [2]: import antigravity
1

Trong mã này, bạn đã xác định 3 biến.

In [2]: import antigravity
51,
In [2]: import antigravity
52 và
In [2]: import antigravity
53. Bạn đã gán cho
In [2]: import antigravity
51 giá trị 10,
In [2]: import antigravity
52 giá trị 20 và
In [2]: import antigravity
53 tổng của
In [2]: import antigravity
51 và
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. Đầu ra từ câu lệnh đó được hiển thị trên dòng
In [2]: import antigravity
60 tiếp theo và số trên dòng
In [2]: import antigravity
60 khớp với dòng
In [2]: import antigravity
62 được liên kết

Có hai điều chính để bạn chú ý trong các lệnh này

  1. Nếu một tuyên bố không bao gồm một nhiệm vụ (với một

    In [2]: import antigravity
    
    63), nó được in trên một dòng
    In [2]: import antigravity
    
    60. Trong MATLAB, bạn sẽ cần bao gồm dấu chấm phẩy để chặn đầu ra ngay cả từ các câu lệnh gán, nhưng điều đó là không cần thiết trong Python

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

Sau khi bạn chạy ba lệnh này, Trình khám phá biến của bạn sẽ giống như hình bên dưới

MATLAB tạo đối tượng Python

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

  1. Tên hiển thị tên mà bạn đã đặt cho
    In [2]: import antigravity
    
    51,
    In [2]: import antigravity
    
    52 và
    In [2]: import antigravity
    
    53
  2. Loại hiển thị loại Python của biến, trong trường hợp này, tất cả
    In [2]: import antigravity
    
    68 cho số nguyên
  3. Kích thước hiển thị kích thước của biến được lưu trữ dữ liệu, hữu ích hơn cho danh sách và các cấu trúc dữ liệu khác
  4. Giá trị hiển thị giá trị hiện tại của biến

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

In [2]: import antigravity
2

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 docstring for short. You’ll learn more about docstrings in a later section

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

In [2]: import antigravity
6

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

MATLAB tạo đối tượng Python

This will automatically execute the following code in the console

>>>

In [2]: import antigravity
7

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

In [2]: import antigravity
3

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

Remove ads

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

MATLAB tạo đối tượng Python

There are two main sections of the interface

  1. On the left is a File explorer that lets you open files from your computer
  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. You can also learn about the Notebook interface in 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. Chẳng hạn, Python có các thư viện

In [2]: import antigravity
88 và
In [2]: import antigravity
89 tích hợp sẵn bao gồm các thao tác cơ bản

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. Tại cơ sở của ngăn xếp là các thư viện cung cấp các phép toán mảng và ma trận cơ bản (NumPy), tích hợp, tối ưu hóa, xử lý tín hiệu và các hàm đại số tuyến tính (SciPy) và vẽ đồ thị (Matplotlib). Các thư viện khác dựa trên những thư viện này để cung cấp chức năng nâng cao hơn bao gồm Pandas, scikit-learning, SymPy, v.v.

NumPy (Trăn số)

NumPy có lẽ là gói cơ bản nhất cho tính toán khoa học trong Python. Nó cung cấp một giao diện hiệu quả cao để tạo và tương tác với các mảng đa chiều. Gần như mọi gói khác trong ngăn xếp SciPy đều sử dụng hoặc tích hợp với NumPy theo một cách nào đó

Mảng NumPy tương đương với cấu trúc dữ liệu mảng cơ bản trong MATLAB. Với mảng NumPy, bạn có thể thực hiện những việc như tích bên trong và bên ngoài, chuyển vị và các phép toán theo phần tử. NumPy cũng chứa một số phương pháp hữu ích để đọc các tệp dữ liệu văn bản và nhị phân, khớp các hàm đa thức, nhiều hàm toán học (sin, cos, căn bậc hai, v.v.) và tạo các số ngẫu nhiên

Các phần nhạy cảm về hiệu suất của NumPy đều được viết bằng ngôn ngữ C, vì vậy chúng rất nhanh. NumPy cũng có thể tận dụng các thư viện đại số tuyến tính được tối ưu hóa như MKL của Intel hoặc OpenBLAS để tăng hiệu suất hơn nữa

Ghi chú

Real Python có một số bài viết đề cập đến cách bạn có thể sử dụng NumPy để tăng tốc mã Python của mình

  • Look Ma, No-Loops. Lập trình mảng với NumPy
  • NumPy arange(). Làm thế nào để sử dụng np. sắp xếp()
  • Vẽ biểu đồ Python. NumPy, Matplotlib, Pandas và Seaborn

Remove ads

SciPy (Trăn khoa học)

Gói SciPy (khác với ngăn xếp SciPy) là một thư viện cung cấp một số lượng lớn các chức năng hữu ích cho các ứng dụng khoa học. Nếu bạn cần làm công việc yêu cầu tối ưu hóa, đại số tuyến tính hoặc đại số tuyến tính thưa, biến đổi Fourier rời rạc, xử lý tín hiệu, hằng số vật lý, xử lý ảnh hoặc tích phân số, thì SciPy chính là thư viện dành cho bạn. Vì SciPy triển khai rất nhiều tính năng khác nhau nên gần giống như có quyền truy cập vào một loạt các hộp công cụ MATLAB trong một gói

SciPy relies heavily on NumPy arrays to do its work. Giống như NumPy, nhiều thuật toán trong SciPy được triển khai bằng C hoặc Fortran nên chúng cũng rất nhanh. 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

Ghi chú

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

With that out of the way, let’s get started. 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

In [2]: import antigravity
0

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

In [2]: import antigravity
1

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

In [2]: import antigravity
2

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 string literals. Don’t worry too much about the syntax of defining a function yet. You’ll see more about that in a later section

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 [2]: import antigravity
100 to store the value 10 and then checking whether the value of
In [2]: import antigravity
100 is equal to 10. If it is, you are displaying the phrase
In [2]: import antigravity
102 on the console from line 2. Otherwise, the
In [2]: import antigravity
103 clause will kick in and display
In [2]: import antigravity
104. Of course, if you run this code, you will see the
In [2]: import antigravity
102 output and then
In [2]: import antigravity
106

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 [2]: import antigravity
103 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 [2]: import antigravity
113 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 [2]: import antigravity
100 and setting its value to 10. On line 2, writing
In [2]: import antigravity
117 tests the value of
In [2]: import antigravity
100 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 [2]: import antigravity
119 to display some output to the console, in a similar way to
In [2]: import antigravity
120 in MATLAB. You’ll read more about
In [2]: import antigravity
119 versus
In [2]: import antigravity
120 in a later section

On line 4, you are starting the

In [2]: import antigravity
103 block. Notice that the
In [2]: import antigravity
124 in the
In [2]: import antigravity
103 keyword is vertically aligned with the
In [2]: import antigravity
126 in the
In [2]: import antigravity
96 keyword, and the line is ended by a colon. Because the
In [2]: import antigravity
103 is dedented relative to
In [2]: import antigravity
119 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 [2]: import antigravity
103 part is starting. Line 5 is indented by one level, so it forms the block of code to be executed when the
In [2]: import antigravity
103 statement is satisfied

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

In [2]: import antigravity
96/
In [2]: import antigravity
103 block. This statement will be printed regardless of the value of
In [2]: import antigravity
100. Notice that the
In [2]: import antigravity
137 in
In [2]: import antigravity
119 is vertically aligned with the
In [2]: import antigravity
126 in
In [2]: import antigravity
96 and the
In [2]: import antigravity
124 in
In [2]: import antigravity
103. This is how Python knows that the code in the
In [2]: import antigravity
96/
In [2]: import antigravity
103 block has ended. If you run the code above, Python will display
In [2]: import antigravity
102 followed by
In [2]: import antigravity
106

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 [2]: import antigravity
147

>>>

In [2]: import antigravity
3

In this code, you first set the value of

In [2]: import antigravity
100 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 PEP 8 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 [2]: import antigravity
151 if the indentation becomes mismatched.

Conditional Statements Use
In [2]: import antigravity
152 in Python

In MATLAB, you can construct conditional statements with

In [2]: import antigravity
96,
In [2]: import antigravity
154, and
In [2]: import antigravity
103. 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 [2]: import antigravity
100 bằng 10. Sau đó, bạn đang kiểm tra xem giá trị của
In [2]: import antigravity
100 có phải là 10 hay không và nếu có, hãy sử dụng
In [2]: import antigravity
120 để in đầu ra ra bàn điều khiển. Nếu
In [2]: import antigravity
100 là 20, bạn đang in một câu lệnh khác và nếu
In [2]: import antigravity
100 không phải là 10 cũng không phải 20, bạn đang in câu lệnh thứ ba

Trong Python, từ khóa

In [2]: import antigravity
154 được thay thế bằng
In [2]: import antigravity
152

In [2]: import antigravity
5

Khối mã này có chức năng tương đương với khối mã MATLAB trước đó. Có 2 sự khác biệt chính. Ở dòng 4,

In [2]: import antigravity
154 được thay thế bằng
In [2]: import antigravity
152 và không có câu lệnh
In [2]: import antigravity
99 nào để kết thúc khối. Instead, the
In [2]: import antigravity
96 block ends when the next dedented line of code is found after the
In [2]: import antigravity
103. Bạn có thể đọc thêm trong tài liệu Python về câu lệnh
In [2]: import antigravity
96

Các hàm gọi và chuỗi lập chỉ mục sử dụng các dấu ngoặc khác nhau trong Python

Trong MATLAB, khi bạn muốn gọi một hàm hoặc khi bạn muốn lập chỉ mục cho một mảng, bạn sử dụng dấu ngoặc tròn (

In [2]: import antigravity
169), đôi khi còn được gọi là dấu ngoặc đơn. Dấu ngoặc vuông (
In [2]: import antigravity
170) được sử dụng để tạo mảng

Bạn có thể kiểm tra sự khác biệt giữa MATLAB và Python bằng mã ví dụ bên dưới

>>>

In [2]: import antigravity
6

Trong mã này, trước tiên bạn tạo một mảng bằng cách sử dụng dấu ngoặc vuông ở bên phải của dấu bằng. Sau đó, bạn truy xuất giá trị của phần tử đầu tiên bằng

In [2]: import antigravity
171, sử dụng dấu ngoặc tròn làm toán tử lập chỉ mục. Ở dòng đầu vào thứ ba, bạn đang gọi
In [2]: import antigravity
172 và sử dụng dấu ngoặc tròn để chỉ ra các tham số sẽ được chuyển vào
In [2]: import antigravity
172, trong trường hợp này chỉ là
In [2]: import antigravity
174. MATLAB tính tổng các phần tử trong
In [2]: import antigravity
174 và trả về kết quả đó

Python sử dụng cú pháp riêng biệt để gọi hàm và lập chỉ mục chuỗi. Trong Python, sử dụng dấu ngoặc tròn có nghĩa là một hàm sẽ được thực thi và sử dụng dấu ngoặc vuông sẽ lập chỉ mục cho một chuỗi

>>>

In [2]: import antigravity
7

Trong mã này, bạn đang xác định danh sách Python trên dòng đầu vào 1. Python lists have some important distinctions from arrays in MATLAB and arrays from the NumPy package. Bạn có thể đọc thêm về danh sách Python trong Danh sách và Bộ dữ liệu trong Python và bạn sẽ tìm hiểu thêm về mảng NumPy trong phần sau

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. Trên dòng đầu vào 3, bạn đang gọi

In [2]: import antigravity
172 bằng cách sử dụng dấu ngoặc tròn và chuyển vào danh sách được lưu trữ trong
In [2]: import antigravity
174. Đ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. Lưu ý rằng Python sử dụng dấu ngoặc vuông để lập chỉ mục danh sách và dấu ngoặc tròn để gọi hàm

Chỉ mục đầu tiên trong chuỗi là 0 trong Python

Trong MATLAB, bạn có thể lấy giá trị đầu tiên từ một mảng bằng cách sử dụng

In [2]: import antigravity
178 làm chỉ mục. Phong cách này tuân theo quy ước đánh số tự nhiên và bắt đầu cách bạn đếm số mục trong chuỗi. You can try out the differences of MATLAB vs Python with this example

>>>

In [2]: import antigravity
8

Trong mã này, bạn đang tạo một mảng có ba số.

In [2]: import antigravity
179,
In [2]: import antigravity
180 và
In [2]: import antigravity
181. Sau đó, bạn đang hiển thị giá trị của phần tử đầu tiên có chỉ số
In [2]: import antigravity
178, là
In [2]: import antigravity
179. Việc cố gắng truy cập phần tử thứ 0 sẽ dẫn đến lỗi trong MATLAB, như được hiển thị trên hai dòng cuối cùng

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

>>>

In [2]: import antigravity
9

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

In [2]: import antigravity
174 là một danh sách Python có ba phần tử trên dòng đầu vào 1. 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, có chỉ số 0. Sau đó, bạn đang hiển thị phần tử thứ hai của danh sách có chỉ số 1

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

In [2]: import antigravity
185 with the contents
In [2]: import antigravity
186 and then getting the first and second elements of the string. Lưu ý rằng phần tử thứ hai (ký tự) của chuỗi là khoảng trắng. Điều này thể hiện một tính năng chung của Python, đó là nhiều loại biến hoạt động theo trình tự và có thể được lập chỉ mục, bao gồm danh sách, bộ dữ liệu, chuỗi và mảng

Phần tử cuối cùng của một chuỗi có chỉ số
In [2]: import antigravity
187 trong Python

Trong MATLAB, bạn có thể lấy giá trị cuối cùng từ một mảng bằng cách sử dụng

In [2]: import antigravity
99 làm chỉ mục. Điều này thực sự hữu ích khi bạn không biết một mảng dài bao nhiêu, vì vậy bạn không biết số nào để truy cập giá trị cuối cùng

Hãy thử sự khác biệt giữa MATLAB và Python với ví dụ này

>>>

In [2]: import antigravity
10

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

In [2]: import antigravity
179,
In [2]: import antigravity
180, and
In [2]: import antigravity
181. Then you are displaying the value of the last element with the index
In [2]: import antigravity
99, which is
In [2]: import antigravity
181

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

In [2]: import antigravity
187

>>>

In [2]: import antigravity
11

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 [2]: import antigravity
187 and the value 30

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

>>>

In [2]: import antigravity
12

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

In [2]: import antigravity
180 and
In [2]: import antigravity
179, respectively

Exponentiation Is Done With
In [2]: import antigravity
198 in Python

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

In [2]: import antigravity
199). The caret operator is a binary operator that takes two numbers. Other binary operators include addition (
In [2]: import antigravity
200), subtraction (
In [2]: import antigravity
201), multiplication (
In [2]: import antigravity
202), and division (
In [2]: import antigravity
203), 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 [2]: import antigravity
13

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 [2]: import antigravity
198) when you want to raise a number to a power

>>>

In [2]: import antigravity
14

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
In [2]: import antigravity
205 in Python

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

In [2]: import antigravity
206. 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 [2]: import antigravity
15

In this code, on the first input line you are finding the length of an array with 3 elements. As expected,

In [2]: import antigravity
206 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

In [2]: import antigravity
205

>>>

In [2]: import antigravity
16

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

In [2]: import antigravity
205 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
In [2]: import antigravity
205 counts the number of characters in the string. In this case,
In [2]: import antigravity
211 has 8 characters

Console Output Is Shown With
In [2]: import antigravity
119 in Python

In MATLAB, you can use

In [2]: import antigravity
120,
In [2]: import antigravity
214, and
In [2]: import antigravity
215 to print the value of variables and other output to the console. In Python,
In [2]: import antigravity
119 serves a similar function as
In [2]: import antigravity
120. Unlike
In [2]: import antigravity
120,
In [2]: import antigravity
119 can send its output to a file similar to
In [2]: import antigravity
214

Python’s

In [2]: import antigravity
119 will display any number of arguments passed to it, separating them by a space in the output. This is different from
In [2]: import antigravity
120 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 [2]: import antigravity
119 can take any number of arguments, and each argument is separated by a space in the output

>>>

In [2]: import antigravity
17

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

In [2]: import antigravity
224,
In [2]: import antigravity
225, and
In [2]: import antigravity
226, where
In [2]: import antigravity
224 and
In [2]: import antigravity
224 are integers, and
In [2]: import antigravity
226 is a string of text. On input line 4, you are printing the three variables using
In [2]: import antigravity
119. 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 [2]: import antigravity
119 by using the
In [2]: import antigravity
232 keyword argument

>>>

In [2]: import antigravity
18

In this code, you are printing the same three variables but setting the separator to be a semicolon followed by a space. Dấu tách này được in giữa đối số thứ nhất và thứ hai và thứ hai và thứ ba, nhưng không phải sau đối số thứ ba. To control the character printed after the last value, you can use the

In [2]: import antigravity
99 keyword argument to
In [2]: import antigravity
119

>>>

In [2]: import antigravity
19

In this code, you have added the

In [2]: import antigravity
99 keyword argument to
In [2]: import antigravity
119, setting it to print a semicolon after the last value. This is shown in the output on line below the input

Like

In [2]: import antigravity
120 from MATLAB,
In [2]: import antigravity
119 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
In [2]: import antigravity
239. In these strings, you can use very similar formatting style codes as
In [2]: import antigravity
214 in MATLAB to format numbers

>>>

In [2]: import antigravity
20

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

In [2]: import antigravity
241 to start the string. Điều này có nghĩa là Python sẽ thay thế giá trị của bất kỳ biến nào nó gặp giữa
In [2]: import antigravity
242 hoặc dấu ngoặc nhọn trong chuỗi. Bạn có thể thấy rằng ở đầu ra, Python đã thay thế
In [2]: import antigravity
243 bằng một số dấu phẩy động với 8 cột ở đầu ra và 3 chữ số chính xác

Dòng đầu vào 9 thể hiện một tính năng mới trong Python 3. 8. Nếu một tên biến ngay sau dấu bằng bên trong dấu ngoặc nhọn, tên của biến và giá trị sẽ được in tự động

Bạn có thể tìm hiểu sâu về

In [2]: import antigravity
119 của Python bằng cách xem Hướng dẫn cơ bản về Python Print

Remove ads

Bạn có thể sẽ thấy những điều này, nhưng bạn có thể học chúng khi cần

Trong phần này, bạn sẽ tìm thấy các ví dụ về mã mà bạn có thể sẽ thấy trong tự nhiên, nhưng bạn có thể đợi một lúc để hiểu chúng nếu muốn. These examples use some intermediate features in Python but are still in the core of how Python works. Giống như trong phần trước, bạn sẽ thấy các so sánh về sự khác biệt trong cú pháp MATLAB và Python

Định nghĩa hàm bắt đầu bằng các giá trị
In [2]: import antigravity
245 và
In [2]: import antigravity
246 trong Python

Trong MATLAB, bạn có thể định nghĩa một hàm bằng cách đặt từ khóa

In [2]: import antigravity
247 ở đầu dòng. Tiếp theo là tên của bất kỳ biến đầu ra nào, dấu bằng (
In [2]: import antigravity
63), sau đó là tên của hàm và bất kỳ đối số đầu vào nào trong ngoặc đơn. Trong hàm, bạn phải gán cho bất kỳ biến nào bạn đã chỉ định trong dòng định nghĩa làm đầu ra. Một hàm MATLAB ví dụ đơn giản được hiển thị bên dưới

In [2]: import antigravity
21

Trong mã này, bạn thấy định nghĩa

In [2]: import antigravity
247 trên dòng 1. Chỉ có một biến đầu ra, được gọi là
In [2]: import antigravity
250, cho chức năng này. Tên của hàm là
In [2]: import antigravity
251 và nó nhận hai đối số, sẽ được gán tên là
In [2]: import antigravity
252 và
In [2]: import antigravity
253 trong thân hàm. Dòng 2 là việc thực hiện chức năng. Giá trị của
In [2]: import antigravity
250 được đặt bằng tổng của
In [2]: import antigravity
252 và
In [2]: import antigravity
253. Dòng cuối cùng của hàm là từ khóa
In [2]: import antigravity
99 cho trình thông dịch MATLAB biết việc định nghĩa hàm đã kết thúc

Để sử dụng hàm này trong MATLAB, bạn nên lưu nó vào một tệp có tên là

In [2]: import antigravity
258, trùng với tên của hàm. Ngoài ra, nó có thể được đặt trong tệp với các lệnh khác với điều kiện là định nghĩa hàm là điều cuối cùng trong tệp và tệp không được đặt tên là
In [2]: import antigravity
258. Sau đó, bạn có thể chạy chức năng này bằng cách nhập đoạn mã sau vào bảng điều khiển MATLAB

>>>

In [2]: import antigravity
22

Trong mã này, bạn đã xác định hai biến có tên là

In [2]: import antigravity
51 và
In [2]: import antigravity
52 lần lượt giữ các giá trị 20 và 10. Sau đó, bạn đã tạo một biến thứ ba có tên là
In [2]: import antigravity
262 lưu trữ kết quả từ
In [2]: import antigravity
263. Check out the Variable explorer, and you’ll see that
In [2]: import antigravity
262 has the value 30, as expected. Lưu ý rằng tên
In [2]: import antigravity
262 không nhất thiết phải trùng tên với biến đầu ra được sử dụng trong định nghĩa hàm, đó là
In [2]: import antigravity
250

MATLAB không yêu cầu hàm cung cấp giá trị đầu ra. Trong trường hợp này, bạn sẽ loại bỏ biến đầu ra và dấu bằng khỏi định nghĩa hàm. Sửa đổi tệp

In [2]: import antigravity
258 của bạn để mã trông như thế này

In [2]: import antigravity
23

Thay đổi duy nhất trong mã này so với mã trước đó là bạn đã xóa

In [2]: import antigravity
268 khỏi dòng 1, các dòng khác hoàn toàn giống nhau. Now if you try to assign the result of calling this function to a variable, MATLAB will generate an error in the console

>>>

In [2]: import antigravity
24

Trong mã này, bạn đã xác định hai biến

In [2]: import antigravity
51 và
In [2]: import antigravity
52 giống như trước và gọi là
In [2]: import antigravity
263 theo cách tương tự như trước. Tuy nhiên, vì
In [2]: import antigravity
263 không còn chỉ định một biến đầu ra, MATLAB tạo ra một thông báo lỗi rằng có quá nhiều đối số đầu ra. Bấm vào chữ
In [2]: import antigravity
251 sẽ mở ra phần định nghĩa của hàm để bạn chỉnh sửa hoặc xem mã nguồn để khắc phục sự cố

Trong Python, từ khóa

In [2]: import antigravity
245 bắt đầu định nghĩa hàm. Từ khóa
In [2]: import antigravity
245 phải được theo sau bởi tên của hàm và mọi đối số của hàm bên trong dấu ngoặc đơn, tương tự như MATLAB. Dòng có
In [2]: import antigravity
245 phải được kết thúc bằng dấu hai chấm (
In [2]: import antigravity
277)

Bắt đầu từ dòng tiếp theo, mã sẽ được thực thi như một phần của hàm phải được thụt vào một cấp. 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

In [2]: import antigravity
245 trên dòng đầu tiên

Nếu hàm của bạn trả lại một số đầu ra cho người gọi, Python không yêu cầu bạn chỉ định tên cho biến đầu ra. Thay vào đó, bạn sử dụng câu lệnh

In [2]: import antigravity
246 để gửi giá trị đầu ra từ hàm

An equivalent function in Python to your first

In [2]: import antigravity
263 example with an output variable is shown below

In [2]: import antigravity
25

Trong mã này, bạn thấy từ khóa

In [2]: import antigravity
245 theo sau là tên hàm và hai đối số
In [2]: import antigravity
252 và
In [2]: import antigravity
253 trên dòng 1. Ở dòng 2, bạn có thể thấy việc tạo một biến mới
In [2]: import antigravity
250 để lưu tổng của
In [2]: import antigravity
252 và
In [2]: import antigravity
253, và ở dòng 3, giá trị của
In [2]: import antigravity
250 được trả về điểm mà hàm này được gọi. Lưu ý rằng dòng 2 và 3 được thụt vào bởi 4 dấu cách vì chúng tạo nên phần thân của hàm

Biến lưu trữ tổng của

In [2]: import antigravity
252 và
In [2]: import antigravity
253 có thể có bất kỳ tên nào, không nhất thiết phải gọi là
In [2]: import antigravity
250. Trên thực tế, bạn không cần phải tạo một biến ở đó. You can simplify your previous function definition by eliminating
In [2]: import antigravity
250 and simply returning the value of
In [2]: import antigravity
292

In [2]: import antigravity
26

Dòng 1 trong mã này giống như trước đây, bạn chỉ thay đổi dòng 2 và xóa dòng 3. Dòng 2 hiện tính giá trị của

In [2]: import antigravity
292 và trả lại giá trị đó cho người gọi hàm. 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

Để sử dụng chức năng này trong Python, bạn không cần lưu nó vào một tệp có tên đặc biệt. Bạn có thể đặt định nghĩa hàm trong bất kỳ tệp Python nào, tại bất kỳ điểm nào trong tệp. Không có hạn chế rằng định nghĩa chức năng phải là cuối cùng. Trên thực tế, bạn thậm chí có thể định nghĩa các hàm ngay từ bảng điều khiển, điều này không thể thực hiện được trong MATLAB

Mở Spyder và trong khung Console gõ

>>>

In [2]: import antigravity
27

On this line of code you are creating the function definition. Trong bảng điều khiển Spyder/IPython, sau khi bạn bắt đầu định nghĩa hàm và nhấn Enter , phần đầu của dòng sẽ trở thành ba dấu chấm và con trỏ sẽ tự động thụt vào. Bây giờ bạn có thể nhập phần còn lại của định nghĩa hàm. Bạn sẽ phải nhấn Enter hai lần để hoàn thành định nghĩa.

>>>

In [2]: import antigravity
28

Trong mã này, bạn có định nghĩa của hàm trên dòng đầu tiên và phần thân của hàm trên dòng thứ hai. Bảng điều khiển tự động thêm

In [2]: import antigravity
294 vào đầu các dòng để cho biết đây là các dòng tiếp theo á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

>>>

In [2]: import antigravity
29

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. Sau đó, trên dòng đầu vào 4, bạn gán
In [2]: import antigravity
262 cho kết quả được trả về từ
In [2]: import antigravity
263. Trên dòng đầu vào 5, bạn đang xuất giá trị của
In [2]: import antigravity
262 ra màn hình bảng điều khiển. Điều này hiển thị 30, tổng của 10 và 20

Trong Python, nếu bạn không đặt câu lệnh

In [2]: import antigravity
246 một cách rõ ràng, hàm của bạn sẽ ngầm trả về giá trị đặc biệt
In [2]: import antigravity
601. Bạn nên thay đổi định nghĩa Python của bạn về
In [2]: import antigravity
263 để xem nó hoạt động như thế nào. Trong bảng điều khiển Spyder/IPython, gõ như sau

>>>

In [2]: import antigravity
60

Trong mã này, bạn có cùng một dòng

In [2]: import antigravity
245 trên dòng đầu vào 6. Bạn đã thay đổi dòng tiếp theo đầu tiên để gán kết quả của phép cộng thành
In [2]: import antigravity
250 thay vì trả về. Bây giờ bạn sẽ thấy điều gì xảy ra khi chúng ta thực hiện chức năng sửa đổi này

>>>

In [2]: import antigravity
61

Trong mã này, trên dòng đầu vào 7, bạn đang chỉ định

In [2]: import antigravity
262 là giá trị được trả về từ
In [2]: import antigravity
263. Sau đó, trên dòng đầu vào 8, bạn đang hiển thị giá trị của
In [2]: import antigravity
262 trên màn hình bảng điều khiển, giống như trước đây. Lần này mặc dù, không có đầu ra. Theo mặc định, Python không in gì khi nó xuất ra một biến có giá trị là
In [2]: import antigravity
601. Bạn có thể kiểm tra lại giá trị của biến
In [2]: import antigravity
262 bằng cách xem Trình khám phá biến. Trong cột Loại, nó sẽ liệt kê
In [2]: import antigravity
610, cho bạn biết rằng
In [2]: import antigravity
262 là giá trị đặc biệt của
In [2]: import antigravity
601

Hàm chấp nhận đối số vị trí và từ khóa trong Python

Trong MATLAB, các hàm có đối số đầu vào được chỉ định trên dòng đầu tiên, trong định nghĩa

In [2]: import antigravity
247. Khi bạn gọi một hàm trong MATLAB, bạn có thể chuyển từ số 0 lên đến số đối số được chỉ định. Trong phần thân của hàm, bạn có thể kiểm tra số lượng đối số đầu vào mà người gọi thực sự đã chuyển để thực thi các mã khác nhau. Điều này hữu ích khi bạn muốn các đối số khác nhau có ý nghĩa khác nhau, như trong ví dụ bên dưới

In [2]: import antigravity
62

Trong mã này, bạn đang xác định một hàm với ba đối số đầu vào có thể. Ở dòng 7, bạn đang bắt đầu một khối

In [2]: import antigravity
614/
In [2]: import antigravity
615 xác định có bao nhiêu đối số đầu vào được truyền cho hàm bằng cách sử dụng biến đặc biệt
In [2]: import antigravity
616. Biến này lưu trữ số lượng đối số thực tế mà người gọi đã truyền vào hàm

Trong mã của bạn ở trên, bạn đang xác định ba trường hợp

  1. Nếu số lượng đối số đầu vào là 2, bạn đang cộng
    In [2]: import antigravity
    
    252 và
    In [2]: import antigravity
    
    253 lại với nhau
  2. Nếu số lượng đối số đầu vào là 3, bạn đang trừ
    In [2]: import antigravity
    
    253 từ
    In [2]: import antigravity
    
    252
  3. Nếu ít hơn 2 đối số được truyền vào, đầu ra sẽ là
    In [2]: import antigravity
    
    621

Nếu truyền nhiều hơn 3 đối số, MATLAB sẽ báo lỗi

Bây giờ bạn nên thử nghiệm với chức năng này. Save the code above into a file called

In [2]: import antigravity
622 and then on the MATLAB console, try the version with two input arguments

>>>

In [2]: import antigravity
63

Trong mã này, bạn đang gọi

In [2]: import antigravity
623 với hai đối số, do đó, các đối số được cộng lại với nhau, dẫn đến câu trả lời là
In [2]: import antigravity
181. Tiếp theo, hãy thử gọi
In [2]: import antigravity
623 với ba đối số

>>>

In [2]: import antigravity
64

Trong mã này, bạn đã sử dụng ba đối số đầu vào và nhận thấy rằng đối số thứ hai đã bị trừ khỏi đối số thứ nhất, dẫn đến kết quả là

In [2]: import antigravity
626. Thứ ba, hãy thử gọi
In [2]: import antigravity
623 với một đối số

>>>

In [2]: import antigravity
65

Trong mã này, bạn đã sử dụng một đối số đầu vào và thấy câu trả lời là 0, vì MATLAB chỉ tìm thấy một đối số cho hàm và sử dụng trường hợp

In [2]: import antigravity
628. Cuối cùng, hãy thử gọi
In [2]: import antigravity
623 với bốn đối số

>>>

In [2]: import antigravity
66

Trong đoạn mã này, bạn thấy rằng MATLAB phát sinh lỗi vì có nhiều đối số đầu vào được truyền hơn so với định nghĩa trong dòng

In [2]: import antigravity
247

Có bốn điểm chính rút ra từ ví dụ này với MATLAB

  1. Chỉ có một loại đối số trong định nghĩa hàm
  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. Số lượng đối số tối đa có thể được truyền cho một hàm được xác định bởi số lượng đối số được chỉ định trong định nghĩa hàm
  4. Người gọi có thể chuyển bất kỳ số lượng đối số nào cho đến mức tối đa

Trong Python, có hai loại đối số bạn có thể chỉ định khi xác định một hàm. Đây là những đối số bắt buộc và tùy chọn. Sự khác biệt chính giữa những điều này là các đối số bắt buộc phải được truyền khi một hàm được gọi, trong khi tùy chọn được cung cấp một giá trị mặc định trong định nghĩa hàm

Bạn có thể thấy sự khác biệt giữa hai phong cách này trong ví dụ tiếp theo

In [2]: import antigravity
67

Trong mã này, bạn đang định nghĩa một hàm có tên là

In [2]: import antigravity
631 có ba đối số.
In [2]: import antigravity
252,
In [2]: import antigravity
253 và
In [2]: import antigravity
634. Trong định nghĩa hàm, bạn có thể thấy hai loại đối số. Hai đối số đầu tiên,
In [2]: import antigravity
252 và
In [2]: import antigravity
253, là đối số bắt buộc

Đối số thứ ba,

In [2]: import antigravity
634, có giá trị mặc định được gán cho nó bằng cách chỉ định giá trị sau dấu bằng trong định nghĩa hàm. Điều này có nghĩa là khi hàm được gọi, việc truyền giá trị cho
In [2]: import antigravity
634 là tùy chọn. Nếu không có giá trị nào được truyền, giá trị mặc định như được xác định trong dòng định nghĩa hàm sẽ được sử dụng. Trong trường hợp này, giá trị mặc định là
In [2]: import antigravity
639

Trong phần thân của hàm, bạn đang kiểm tra giá trị của

In [2]: import antigravity
634 bằng câu lệnh
In [2]: import antigravity
96 để xác định xem có nên thực hiện phép cộng hay phép trừ hay không. Nếu
In [2]: import antigravity
634 là
In [2]: import antigravity
643, thì
In [2]: import antigravity
253 sẽ bị trừ khỏi
In [2]: import antigravity
252. Ngược lại, nếu
In [2]: import antigravity
634 là
In [2]: import antigravity
639, thì
In [2]: import antigravity
252 sẽ được thêm vào
In [2]: import antigravity
253. Trong cả hai trường hợp, kết quả của phép toán số học sẽ được trả về cho người gọi

Ngoài hai loại đối số bạn có thể sử dụng khi xác định một hàm, có hai loại đối số bạn có thể chỉ định khi gọi một hàm. Chúng được gọi là đối số vị trí và từ khóa. Bạn có thể thấy sự khác biệt giữa những điều này trong ví dụ sau. Đầu tiên, hãy thử chỉ truyền hai đối số cho hàm

>>>

In [2]: import antigravity
68

Trong mã này, bạn chỉ truyền hai đối số cho

In [2]: import antigravity
631,
In [2]: import antigravity
179 và
In [2]: import antigravity
180. Trong trường hợp này, bạn đã chuyển các giá trị này dưới dạng đối số vị trí và ý nghĩa của đối số được xác định theo vị trí của chúng trong lệnh gọi hàm

Vì chỉ có hai đối số bắt buộc được chuyển, nên

In [2]: import antigravity
634 sẽ nhận giá trị mặc định là
In [2]: import antigravity
639. 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. Tiếp theo, hãy thử chuyển một giá trị cho
In [2]: import antigravity
634

>>>

In [2]: import antigravity
69

Trong mã này, bạn đã chuyển ba đối số cho

In [2]: import antigravity
631, với hai giá trị khác nhau cho đối số
In [2]: import antigravity
634. Đầu tiên, bạn đã vượt qua
In [2]: import antigravity
639 trên dòng đầu vào 2. Kết quả là phép cộng của 10 và 20. Sau đó, bạn đã chuyển
In [2]: import antigravity
643 trên dòng đầu vào 3, dẫn đến chênh lệch giữa 10 và 20 hoặc -10

Trong các ví dụ này, bạn đã thấy rằng trong Python có thể xác định các giá trị mặc định cho các đối số của một hàm. Điều này có nghĩa là khi bạn gọi hàm, mọi đối số có giá trị mặc định là tùy chọn và không cần phải chuyển. Nếu không có giá trị nào được chuyển cho bất kỳ đối số mặc định nào, thì giá trị mặc định sẽ được sử dụng. Tuy nhiên, bạn phải chuyển một giá trị cho mọi đối số không có giá trị mặc định. Otherwise, Python will raise an error

>>>

In [2]: import antigravity
70

Trong đoạn mã này, bạn chỉ truyền một trong hai đối số bắt buộc cho

In [2]: import antigravity
631, vì vậy Python sẽ tăng một giá trị
In [2]: import antigravity
661. Thông báo lỗi cho bạn biết rằng bạn đã không chuyển giá trị cho
In [2]: import antigravity
253 vì nó không có giá trị mặc định

Trong ba ví dụ cuối cùng này, bạn đã sử dụng các đối số vị trí, vì vậy tham số nào được gán cho các biến trong hàm phụ thuộc vào thứ tự chúng được truyền. Có một phương pháp khác để truyền đối số cho các hàm trong Python, được gọi là đối số từ khóa. Để sử dụng đối số từ khóa, bạn chỉ định tên của đối số trong lời gọi hàm

>>>

In [2]: import antigravity
71

Trong mã này, bạn đã sử dụng các đối số từ khóa cho cả ba đối số của

In [2]: import antigravity
631. Các đối số từ khóa được chỉ định bằng cách nêu tên đối số, sau đó là dấu bằng, sau đó là giá trị mà đối số đó phải có. Một trong những lợi thế lớn của đối số từ khóa là chúng làm cho mã của bạn rõ ràng hơn. (Như Zen of Python đã nói, tường minh tốt hơn ẩn ý. ) Tuy nhiên, chúng làm cho mã dài hơn một chút, do đó tùy thuộc vào quyết định của bạn khi sử dụng đối số từ khóa hay không

Một lợi ích khác của đối số từ khóa là chúng có thể được chỉ định theo thứ tự bất kỳ

>>>

In [2]: import antigravity
72

Trong mã này, bạn đã chỉ định ba đối số cho

In [2]: import antigravity
631 làm đối số từ khóa, nhưng thứ tự khác với trong định nghĩa hàm. Tuy nhiên, Python kết nối các biến phù hợp với nhau vì chúng được chỉ định làm từ khóa thay vì đối số vị trí

Bạn cũng có thể kết hợp các đối số vị trí và từ khóa với nhau trong cùng một lệnh gọi hàm. Nếu các đối số vị trí và từ khóa được trộn lẫn với nhau, các đối số vị trí phải được chỉ định trước, trước bất kỳ đối số từ khóa nào

>>>

In [2]: import antigravity
73

Trong mã này, bạn đã chỉ định các giá trị cho

In [2]: import antigravity
252 và
In [2]: import antigravity
253 bằng cách sử dụng đối số vị trí và giá trị cho
In [2]: import antigravity
634 bằng cách sử dụng đối số từ khóa. Đây có lẽ là trường hợp phổ biến nhất của việc sử dụng các đối số từ khóa, bởi vì nó mang lại sự cân bằng tốt giữa rõ ràng và súc tích

Cuối cùng, có một lợi ích cuối cùng của việc sử dụng đối số từ khóa và giá trị mặc định. Spyder và các IDE khác cung cấp nội quan của các định nghĩa chức năng. Điều này sẽ cho bạn biết tên của tất cả các đối số hàm đã xác định, đối số nào có đối số mặc định và giá trị của đối số mặc định. Điều này có thể giúp bạn tiết kiệm thời gian và làm cho mã của bạn dễ đọc hơn và nhanh hơn

Không có khối
In [2]: import antigravity
614/
In [2]: import antigravity
615 trong Python

Trong MATLAB, bạn có thể sử dụng các khối

In [2]: import antigravity
614/
In [2]: import antigravity
615 để thực thi mã bằng cách kiểm tra giá trị của một biến xem có bằng nhau với một số hằng số không. Loại cú pháp này khá hữu ích khi bạn biết bạn muốn xử lý một vài trường hợp riêng biệt. Hãy thử một khối
In [2]: import antigravity
614/______4615 với ví dụ này

In [2]: import antigravity
74

Trong mã này, bạn bắt đầu bằng cách xác định

In [2]: import antigravity
100 và đặt nó bằng 10 và trên các dòng sau, bạn kiểm tra giá trị của
In [2]: import antigravity
100. Mã này sẽ dẫn đến kết quả đầu ra
In [2]: import antigravity
676 được hiển thị trên bảng điều khiển, vì
In [2]: import antigravity
100 bằng 10

Cú pháp này là một so sánh thú vị giữa MATLAB và Python vì Python không có cú pháp tương tự. Thay vào đó, bạn nên sử dụng khối

In [2]: import antigravity
96/
In [2]: import antigravity
152/
In [2]: import antigravity
103

In [2]: import antigravity
75

Trong mã này, bạn bắt đầu bằng cách xác định

In [2]: import antigravity
100 và đặt nó bằng
In [2]: import antigravity
179. Ở một số dòng tiếp theo, bạn đang viết một khối
In [2]: import antigravity
96/
In [2]: import antigravity
152/
In [2]: import antigravity
103 để kiểm tra các giá trị khác nhau mà bạn quan tâm

Không gian tên là một ý tưởng tuyệt vời trong Python

Trong MATLAB, tất cả các chức năng được tìm thấy trong một phạm vi duy nhất. MATLAB có thứ tự tìm kiếm xác định để tìm các hàm trong phạm vi hiện tại. Nếu bạn xác định chức năng của riêng mình cho thứ gì đó mà MATLAB đã bao gồm, bạn có thể gặp hành vi không mong muốn

Như bạn đã thấy trong Zen of Python, không gian tên là một ý tưởng tuyệt vời. Không gian tên là một cách để cung cấp các phạm vi khác nhau cho tên hàm, lớp và biến. Điều này có nghĩa là bạn phải cho Python biết thư viện nào có chức năng mà bạn muốn sử dụng. Đâ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. Không có không gian tên, sẽ khó khăn hơn để cho Python biết bạn muốn sử dụng hàm căn bậc hai nào

Để cho Python biết vị trí của một hàm, trước tiên bạn phải

In [2]: import antigravity
687 thư viện, thư viện này tạo không gian tên cho mã của thư viện đó. Sau đó, khi bạn muốn sử dụng một hàm từ thư viện, bạn cho Python biết không gian tên nào cần tìm trong đó

>>>

In [2]: import antigravity
76

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

In [2]: import antigravity
88 được tích hợp sẵn vào Python. Sau đó, dòng đầu vào 2 tính căn bậc hai của 4 bằng cách sử dụng hàm căn bậc hai từ bên trong thư viện
In [2]: import antigravity
88. Dòng
In [2]: import antigravity
690 nên được đọc là “từ trong
In [2]: import antigravity
88, tìm
In [2]: import antigravity
692. ”

Từ khóa

In [2]: import antigravity
687 tìm kiếm thư viện được đặt tên và liên kết không gian tên với cùng tên với thư viện theo mặc định. Bạn có thể đọc thêm về cách Python tìm kiếm các thư viện trong Python Modules and Packages – An Introduction

You can also tell Python what name it should use for a library. Chẳng hạn, rất phổ biến khi thấy

In [2]: import antigravity
694 được rút ngắn thành
In [2]: import antigravity
695 với đoạn mã sau

>>>

In [2]: import antigravity
77

Trong mã này, dòng đầu vào 3 nhập NumPy và yêu cầu Python đặt thư viện vào không gian tên

In [2]: import antigravity
695. Sau đó, bất cứ khi nào bạn muốn sử dụng một chức năng từ NumPy, bạn sử dụng chữ viết tắt
In [2]: import antigravity
695 để tìm chức năng đó. Trên dòng đầu vào 4, bạn đang tính căn bậc hai của 4 một lần nữa, nhưng lần này, sử dụng
In [2]: import antigravity
698.
In [2]: import antigravity
698 nên được đọc là “từ bên trong NumPy, tìm
In [2]: import antigravity
692. ”

Có hai lưu ý chính khi sử dụng không gian tên mà bạn nên cẩn thận

  1. Bạn không nên đặt tên biến trùng tên với một trong các hàm được tích hợp trong Python. Bạn có thể tìm thấy danh sách đầy đủ các chức năng này trong tài liệu Python. Các tên biến phổ biến nhất cũng là các hàm dựng sẵn và không nên được sử dụng là

    In [2]: import antigravity
    
    701,
    In [2]: import antigravity
    
    702,
    In [2]: import antigravity
    
    703,
    In [2]: import antigravity
    
    704,
    In [2]: import antigravity
    
    705,
    In [2]: import antigravity
    
    706,
    In [2]: import antigravity
    
    707,
    In [2]: import antigravity
    
    91,
    In [2]: import antigravity
    
    709 và
    In [2]: import antigravity
    
    710

  2. Bạn không nên đặt tên tệp Python (tệp có phần mở rộng là

    In [2]: import antigravity
    
    711) trùng tên với thư viện mà bạn đã cài đặt. Nói cách khác, bạn không nên tạo tệp Python có tên là
    In [2]: import antigravity
    
    712. Điều này là do Python tìm kiếm thư mục làm việc hiện tại trước tiên khi nó cố gắng nhập thư viện. Nếu bạn có một tệp có tên là
    In [2]: import antigravity
    
    712, thì tệp đó sẽ được tìm thấy trước thư viện
    In [2]: import antigravity
    
    88 được tích hợp sẵn và bạn có thể sẽ thấy một tệp
    In [2]: import antigravity
    
    715

Kết quả chưa được chỉ định gần đây nhất có sẵn là
In [2]: import antigravity
716 trong Python

Bảng điều khiển MATLAB sử dụng

In [2]: import antigravity
717 để lưu trữ kết quả của phép tính gần đây nhất nếu kết quả đó không được gán cho một biến. Điều này thực sự hữu ích khi bạn quên gán kết quả tính toán cho một biến hoặc khi bạn chỉ muốn xâu chuỗi một vài phép tính đơn giản lại với nhau. Để thấy sự khác biệt giữa MATLAB và Python, hãy thử ví dụ này

>>>

In [2]: import antigravity
78

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

In [2]: import antigravity
172 để tính tổng của mảng. Vì không có dấu bằng với tên biến ở bên trái, MATLAB gán đầu ra từ
In [2]: import antigravity
172 thành
In [2]: import antigravity
717. Sau đó, bạn có thể sử dụng biến đó trong các tính toán tiếp theo, như bạn làm ở đây bằng cách thêm 10 vào kết quả cuối cùng. Lưu ý rằng điều này sẽ chỉ hoạt động trong bảng điều khiển MATLAB, không hoạt động trong tệp tập lệnh

Trong bảng điều khiển Python (bao gồm cả bảng điều khiển IPython/Spyder), đầu ra từ phép tính gần đây nhất được lưu trữ trong

In [2]: import antigravity
716 (ký tự gạch dưới). Hãy thử đoạn mã sau

>>>

In [2]: import antigravity
79

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

In [2]: import antigravity
172 để tính tổng của danh sách. Vì không có dấu bằng với tên biến ở bên trái, Python gán đầu ra từ
In [2]: import antigravity
172 cho dấu gạch dưới (
In [2]: import antigravity
716), ngoài việc in nó trên dòng đầu ra. Sau đó, bạn có thể sử dụng biến đó trong các tính toán tiếp theo, như bạn làm ở đây bằng cách thêm 10 vào kết quả cuối cùng. Lưu ý rằng điều này sẽ chỉ hoạt động trong bảng điều khiển Python, không hoạt động trong tệp tập lệnh

Trong bảng điều khiển IPython, có một tính năng bổ sung được bật. Bạn có thể thêm một số sau dấu gạch dưới để truy xuất kết quả của bất kỳ dòng nào trước đó. Hãy thử đoạn mã sau

>>>

In [2]: import antigravity
30

Trong mã này trên dòng đầu vào 3, bạn đang sử dụng

In [2]: import antigravity
725 để chỉ giá trị của dòng đầu ra 1, dòng
In [2]: import antigravity
172. Với kết quả đó (60), bạn đang thêm 20, tạo ra kết quả là 80. Trên dòng đầu vào 4, bạn đang thêm 20 vào giá trị của dòng đầu ra 2, được truy cập bằng
In [2]: import antigravity
727, vì vậy kết quả là 90

Lưu ý rằng Trình khám phá biến Spyder không hiển thị biến này theo mặc định, trong khi đó,

In [2]: import antigravity
717 được hiển thị trong Trình khám phá biến MATLAB. Trong một vài phần, bạn sẽ thấy lý do tại sao dấu gạch dưới không được hiển thị theo mặc định và cách bạn có thể thấy dấu gạch dưới

Các hàm ẩn danh được tạo bằng từ khóa
In [2]: import antigravity
729 trong Python

MATLAB sử dụng ký hiệu at (

In [2]: import antigravity
730) để chỉ ra rằng những gì tiếp theo là định nghĩa của một hàm ẩn danh. Các hàm ẩn danh là các hàm không được định nghĩa trong tệp chương trình và không sử dụng từ khóa
In [2]: import antigravity
247. Tệp chương trình là tệp MATLAB có tên tệp kết thúc bằng
In [2]: import antigravity
732. Các hàm ẩn danh được giới hạn trong một câu lệnh duy nhất để chúng được dùng cho các tính toán đơn giản

Bạn có thể thử sự khác biệt của các hàm ẩn danh trong MATLAB so với Python bằng ví dụ này

>>>

In [2]: import antigravity
31

Trong mã này, dòng đầu vào đầu tiên xác định hàm ẩn danh với một tham số đầu vào,

In [2]: import antigravity
733. Phần thân của hàm theo sau, sử dụng
In [2]: import antigravity
214 để định dạng đầu vào thành một chuỗi. Chức năng này được gán cho
In [2]: import antigravity
735. Trên dòng đầu vào thứ hai,
In [2]: import antigravity
736 được thực thi và truyền giá trị
In [2]: import antigravity
737. Kết quả chuỗi
In [2]: import antigravity
738 được in trên bàn điều khiển

Các hàm ẩn danh thường được sử dụng nhất khi bạn cần chuyển một hàm này sang một hàm khác. Trong những trường hợp này, thường không cần thiết phải gán định nghĩa hàm cho một biến

>>>

In [2]: import antigravity
32

Trong mã này, dòng đầu vào đầu tiên thực thi

In [2]: import antigravity
739, một hàm tính tích phân xác định của một hàm đã cho. Đối số đầu tiên của
In [2]: import antigravity
739 phải là một hàm, vì vậy đây là một nơi hoàn hảo để sử dụng một hàm ẩn danh. Ở đây, hàm ẩn danh của bạn bình phương bất kể giá trị đầu vào là gì. Hai đối số khác của
In [2]: import antigravity
739 là giới hạn của tích phân, sao cho kết quả của tích phân
In [2]: import antigravity
742 từ 0 đến 9 là 243

Python sử dụng từ khóa

In [2]: import antigravity
729 để xác định các hàm ẩn danh. Ngoài sự khác biệt về cú pháp này, các hàm ẩn danh trong Python hoạt động giống như trong MATLAB

>>>

In [2]: import antigravity
33

Trong mã này, dòng đầu vào 1 xác định hàm

In [2]: import antigravity
729 với một tham số,
In [2]: import antigravity
733. Bạn sử dụng
In [2]: import antigravity
119 trong định nghĩa hàm để hiển thị chuỗi f có giá trị của tham số đầu vào. Chức năng này sau đó được lưu trữ trong
In [2]: import antigravity
747. Dòng đầu vào 2 đánh giá
In [2]: import antigravity
747 với chuỗi đầu vào
In [2]: import antigravity
737 và tạo ra đầu ra
In [2]: import antigravity
738

Trong Python, hướng dẫn phong cách chính thức được gọi là PEP 8 đặc biệt không khuyến nghị gán biểu thức

In [2]: import antigravity
729 cho tên biến, như bạn đã thấy trong ví dụ trước. Nếu bạn muốn đặt tên cho một hàm để tham chiếu đến nó nhiều lần, bạn nên sử dụng cú pháp
In [2]: import antigravity
245 và xác định một hàm đầy đủ, ngay cả đối với các hàm một dòng

Tuy nhiên, các hàm

In [2]: import antigravity
729 vẫn hữu ích khi chúng được truyền dưới dạng đối số vào một hàm khác

>>>

In [2]: import antigravity
34

Trong mã này, dòng đầu vào 3 nhập thư viện

In [2]: import antigravity
754 và lưu trữ nó trong không gian tên
In [2]: import antigravity
755. Trên dòng đầu vào 4, bạn đang sử dụng
In [2]: import antigravity
756 từ
In [2]: import antigravity
754 để tính tích phân bằng phương pháp bậc hai, rất giống với
In [2]: import antigravity
739 trong MATLAB. Đối số đầu tiên của
In [2]: import antigravity
756 là chức năng được tích hợp và bạn sử dụng hàm
In [2]: import antigravity
729 để chỉ định rằng
In [2]: import antigravity
761 phải được tích hợp. Đối số thứ hai và thứ ba của
In [2]: import antigravity
756 xác định rằng tích phân nên được tiến hành từ 0 đến 9

Bạn có thể thấy kết quả ở dòng 4 có 2 giá trị là

In [2]: import antigravity
763 và
In [2]: import antigravity
764. Giá trị đầu tiên là kết quả của phép tích hợp và bằng với kết quả từ MATLAB. Giá trị thứ hai là ước tính sai số tuyệt đối trong kết quả. Một lỗi nhỏ này xấp xỉ độ chính xác của các số được sử dụng để lưu trữ kết quả, vì vậy câu trả lời gần như chính xác nhất có thể

Bạn có thể đọc thêm về

In [2]: import antigravity
729 trong Cách sử dụng Hàm lambda Python hoặc xem video trong khóa học Cách sử dụng Hàm Lambda Python

Remove ads

Bạn sẽ chỉ cần những thứ này trong các tình huống chuyên biệt

Trong phần này, các ví dụ là các khái niệm nâng cao hơn mà bạn sẽ cần khi bạn trở nên nâng cao hơn trong quá trình phát triển Python. Một số ví dụ ở đây liên quan đến việc phát triển ứng dụng hoặc mã cấp cao hơn các phần khác. Khi bạn thấy những khái niệm này trong mã khác, bạn có thể tìm hiểu chúng khi bạn cảm thấy thoải mái

Định nghĩa lớp bắt đầu bằng
In [2]: import antigravity
766 trong Python

MATLAB có hai cách để định nghĩa một lớp. Với cách thứ nhất, bạn có thể đặt tất cả định nghĩa lớp trong một tệp duy nhất với tên của lớp là tên tệp. Sau đó, trong tệp, bạn có thể sử dụng từ khóa

In [2]: import antigravity
767 để xác định các thuộc tính và phương thức thuộc về lớp

Với cách 2, bạn có thể tạo thư mục bắt đầu bằng

In [2]: import antigravity
730 và trùng tên với class. Trong thư mục đó, bạn có thể tạo một tệp có cùng tên với lớp. Định nghĩa hàm trong tệp đó sẽ được sử dụng làm trình khởi tạo lớp và nó sẽ gọi
In [2]: import antigravity
769 để khởi tạo lớp. Các phương thức của lớp có thể được định nghĩa trong các tệp khác trong cùng một thư mục, trong đó tên của mỗi tệp phải giống với tên của phương thức

Python chỉ có một cách để định nghĩa một lớp, sử dụng từ khóa

In [2]: import antigravity
766. Vì Python sử dụng thụt đầu dòng để tìm phần cuối của định nghĩa lớp nên toàn bộ định nghĩa phải được chứa trong một tệp duy nhất

In [2]: import antigravity
35

Trong mã này, dòng đầu tiên xác định tên của lớp. Nó bắt đầu bằng từ khóa

In [2]: import antigravity
766, theo sau là tên của lớp và dấu hai chấm. Bên dưới dòng này, tất cả mã là một phần của định nghĩa lớp (phương thức và thuộc tính) phải được thụt vào. Khi một dòng mã bắt đầu trong cùng một cột với
In [2]: import antigravity
772 trong
In [2]: import antigravity
766, định nghĩa lớp sẽ kết thúc

Dòng thứ hai trong mã này là một nhận xét cần lưu ý rằng phần còn lại của định nghĩa lớp sẽ tuân theo dòng

In [2]: import antigravity
766

Như trong tất cả các mã hướng đối tượng, các lớp Python có thể kế thừa từ các lớp cha. Lớp cha của một lớp nhất định có thể được cung cấp dưới dạng tham số trong định nghĩa lớp, như được hiển thị bên dưới

In [2]: import antigravity
36

Trong mã này, thay đổi duy nhất là tên của lớp cha được liệt kê bên trong dấu ngoặc tròn trước dấu hai chấm.

Không có thuộc tính hoặc phương thức riêng tư nào trong Python

MATLAB cho phép đặt các thuộc tính và phương thức của lớp thành một trong bốn tùy chọn

In [2]: import antigravity
775

  • In [2]: import antigravity
    
    776. Quyền truy cập vào thuộc tính hoặc phương thức không bị hạn chế
  • In [2]: import antigravity
    
    777. Chỉ được phép truy cập vào thuộc tính hoặc phương thức trong lớp này hoặc các lớp con
  • In [2]: import antigravity
    
    778. Chỉ được phép truy cập vào thuộc tính hoặc phương thức trong lớp này
  • In [2]: import antigravity
    
    779 hoặc
    In [2]: import antigravity
    
    780. Chỉ được phép truy cập vào thuộc tính hoặc phương thức trong lớp hoặc các lớp được liệt kê

Điều này cho phép bạn kiểm soát cụ thể các cách mà một thuộc tính hoặc phương thức lớp có thể được truy cập

Trong Python, không có cách nào để đặt thuộc tính hoặc phương thức của lớp hoặc cá thể là được bảo vệ hoặc riêng tư. Tất cả các lớp và thể hiện của lớp có thể thay đổi các thuộc tính và phương thức của chúng trong thời gian chạy. Quy ước của Python là các thuộc tính và phương thức bắt đầu bằng dấu gạch dưới (

In [2]: import antigravity
716) được dự định là riêng tư hoặc ít nhất là không công khai. Tuy nhiên, quy ước này không được thực thi bởi bất kỳ kiểm tra nào trong ngôn ngữ và tất cả các thuộc tính và phương thức có thể được sửa đổi bởi người dùng khi chạy

Như bạn đã thấy trong phần về cách sử dụng dấu gạch dưới để truy xuất các giá trị trong bảng điều khiển, dấu gạch dưới không hiển thị theo mặc định trong trình khám phá Biến Spyder. Điều này là do Spyder và các công cụ khác tôn trọng quy ước rằng dấu gạch dưới cho biết nội dung nào đó không được công khai. Tuy nhiên, dấu gạch dưới có thể được hiển thị trong trình khám phá Biến Spyder nếu bạn nhấp vào biểu tượng bánh răng ở trên cùng bên phải của ngăn đó và bỏ chọn mục Loại trừ biến riêng tư. Điều này cũng sẽ hiển thị các biến không công khai khác

Python sử dụng một số phương thức đặc biệt bắt đầu bằng dấu gạch dưới kép (

In [2]: import antigravity
782), được gọi là phương thức dunder, để triển khai hành vi cụ thể cho các lớp. Phương thức dunder được sử dụng phổ biến nhất là
In [2]: import antigravity
783, là trình khởi tạo lớp hoặc hàm tạo. Bạn có thể đọc nhiều hơn về các phương thức dunder trong Làm phong phú các lớp Python của bạn với các phương thức Dunder (Magic, Special)

Nếu bạn muốn biết thêm thông tin về các lớp của Python, bạn có thể đọc Lập trình hướng đối tượng trong Python vs Java. Mặc dù bài viết đó là về Java, nhưng Java tương tự như mô hình MATLAB OOP về bản chất của các thuộc tính và phương thức

Một lớp gọi chính nó là
In [2]: import antigravity
784 trong Python

MATLAB sử dụng tên

In [2]: import antigravity
785 khi một lớp muốn tham chiếu đến thể hiện hiện tại của chính nó.
In [2]: import antigravity
785 phải là đối số đầu tiên được truyền cho một phương thức thông thường. MATLAB cũng định nghĩa các phương thức tĩnh không có tham chiếu đến thể hiện của lớp

Python sử dụng tên

In [2]: import antigravity
784 khi một lớp muốn tham chiếu đến thể hiện hiện tại của chính nó, nhưng đây thực sự chỉ là một quy ước. Bạn có thể gọi đối số đầu tiên cho một phương thức thể hiện với bất kỳ tên nào bạn muốn, nhưng
In [2]: import antigravity
784 là quy ước phổ biến nhất. Python cũng định nghĩa các phương thức tĩnh không nhận đối số của đối tượng lớp và các phương thức lớp nhận đối số của đối tượng lớp thay vì đối tượng. Bạn có thể đọc thêm về các phương thức thể hiện, tĩnh và lớp trong Python's Instance, Class và 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 [2]: import antigravity
789) hoặc trong mảng ký tự nếu bạn sử dụng dấu nháy đơn (
In [2]: import antigravity
790). Nếu bạn sử dụng cả dấu ngoặc đơn và dấu ngoặc kép trong phép gán mảng, thì mảng đó sẽ được thăng cấp thành mảng chuỗi

Trong mảng ký tự, mỗi ký tự trong chuỗi chiếm một cột trong mảng. Đối với mảng ký tự nhiều chiều, mỗi hàng của mảng phải có cùng số ký tự, nghĩa là cùng số cột. Điều này được thể hiện trong ví dụ dưới đây

>>>

In [2]: import antigravity
37

Trong ví dụ này, dòng 1 hiển thị nỗ lực xác định mảng ký tự 2 hàng bằng cách sử dụng dấu nháy đơn. Tuy nhiên, số lượng ký tự trong

In [2]: import antigravity
791 không giống như trong
In [2]: import antigravity
87, vì vậy MATLAB hiển thị thông báo lỗi rằng kích thước không nhất quán

Ở dòng 4, bạn đã tạo thành công một mảng ký tự và ở dòng nhập thứ ba, bạn đang kiểm tra kích thước của mảng. Đầu ra cho thấy có 2 hàng, như mong đợi và 6 cột, vì độ dài của cả

In [2]: import antigravity
86 và
In [2]: import antigravity
87 đều là 6 ký tự

Đây không phải là trường hợp của mảng chuỗi. Trong mảng chuỗi, mỗi chuỗi chiếm một cột trong mảng và mỗi hàng trong mảng nhiều chiều phải có cùng số lượng chuỗi, mặc dù mỗi chuỗi có thể có độ dài khác nhau. Điều này được thể hiện trong ví dụ dưới đây

>>>

In [2]: import antigravity
38

Trong mã này, dòng 1 hiển thị nỗ lực xác định mảng chuỗi 2 hàng bằng cách sử dụng dấu ngoặc kép. Tuy nhiên, số chuỗi ở hàng đầu tiên (2) không khớp với số chuỗi ở hàng thứ hai (1), vì vậy MATLAB phát sinh lỗi

Ở dòng 5, bạn đã tạo thành công một mảng chuỗi. Lưu ý rằng mặc dù số lượng ký tự khác nhau giữa

In [2]: import antigravity
791 và
In [2]: import antigravity
87, MATLAB vẫn có thể tạo mảng chuỗi. Trên dòng 6, bạn đang kiểm tra kích thước của mảng chuỗi, cho thấy có 2 hàng và 1 cột, như mong đợi

Trong Python, chỉ có một kiểu chuỗi ký tự, được gọi là

In [2]: import antigravity
91. Bạn có thể tạo một chuỗi ký tự bằng cách sử dụng dấu ngoặc đơn (______4790) hoặc dấu ngoặc kép (
In [2]: import antigravity
789), không có sự khác biệt giữa hai định nghĩa. Tuy nhiên, có một số đối số tốt để ưu tiên sử dụng dấu ngoặc kép khi xác định chuỗi ký tự bằng Python, điều này được thể hiện rõ trong thư viện định dạng mã Đen

Có một cách bổ sung để xác định chuỗi trong Python, sử dụng dấu nháy đơn ba lần (

In [2]: import antigravity
300) hoặc dấu nháy ba lần kép (
In [2]: import antigravity
95). Phương pháp tạo chuỗi này cho phép các chuỗi được xác định trên nhiều dòng với các ký tự dòng mới được giữ lại. Bạn có thể xem một ví dụ về điều này trong phần về nhận xét và chuỗi tài liệu

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

Bạn có thể tạo cấu trúc dữ liệu tương tự cho mảng chuỗi và mảng ký tự trong MATLAB bằng cách sử dụng NumPy trong Python. NumPy có một số kiểu dữ liệu hoặc dtypes có liên quan đến chuỗi. Trong Python 3, chuỗi dtype mặc định cho mảng là chuỗi Unicode có độ rộng cố định

>>>

In [2]: import antigravity
39

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

In [2]: import antigravity
695. Trên dòng đầu vào 2, bạn đang tạo NumPy
In [2]: import antigravity
303 với 2 phần tử chuỗi,
In [2]: import antigravity
791 và
In [2]: import antigravity
87, đồng thời gán mảng cho
In [2]: import antigravity
174

Trên dòng đầu vào 3, bạn đang hiển thị giá trị của

In [2]: import antigravity
174. Đầu ra từ dòng thứ ba cho thấy rằng
In [2]: import antigravity
174 đang lưu trữ một
In [2]: import antigravity
303 có 2 phần tử,
In [2]: import antigravity
310 và
In [2]: import antigravity
311, như mong đợi. Lưu ý rằng mặc dù bạn đã xác định mảng bằng chuỗi trích dẫn kép, nhưng Python đang hiển thị chúng bằng chuỗi trích dẫn đơn. Hãy nhớ rằng không có sự khác biệt giữa dấu ngoặc đơn và dấu ngoặc kép trong Python

Dòng 3 cũng hiển thị dtype của dữ liệu trong mảng. Đối với mảng này, dtype là

In [2]: import antigravity
312. Ba ký tự ở đây đại diện cho các khía cạnh về cách sắp xếp các chuỗi trong bộ nhớ.
In [2]: import antigravity
313 có nghĩa là thứ tự byte của mảng là endian nhỏ.
In [2]: import antigravity
314 có nghĩa là chuỗi thuộc loại Unicode. Cuối cùng,
In [2]: import antigravity
315 có nghĩa là độ dài tối đa của một phần tử là 6 ký tự. Điều này đã được chọn làm độ dài của chuỗi dài nhất trong đầu vào

Lưu ý rằng chuỗi

In [2]: import antigravity
791 chỉ có 4 ký tự. Trong mảng dtype chuỗi NumPy, các phần tử có thể có ít hơn số ký tự tối đa mà không gặp sự cố, nhưng việc gán cho các phần tử có chuỗi dài hơn độ dài tối đa sẽ cắt bớt đầu vào

>>>

In [2]: import antigravity
00

Trong mã này, bạn đang cố gán lại phần tử đầu tiên của mảng bằng chuỗi

In [2]: import antigravity
317. Rõ ràng, chuỗi này dài hơn 6 ký tự, do đó, nó bị cắt ngắn chỉ còn 6 ký tự khi được gán,
In [2]: import antigravity
318. (Khoảng trắng được tính là 1 ký tự. )

Nếu bạn muốn tạo một mảng có thể chứa các chuỗi có độ dài bất kỳ, bạn nên chuyển loại dtype

In [2]: import antigravity
319 khi bạn tạo mảng

>>>

In [2]: import antigravity
01

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

In [2]: import antigravity
320, với hai phần tử, nhưng lần này bạn đã chỉ định dtype là
In [2]: import antigravity
319, bạn đã xác nhận điều này bằng cách hiển thị đầu ra trên bảng điều khiển. Bây giờ bạn sẽ thấy kiểu dtype của
In [2]: import antigravity
319 ảnh hưởng đến việc gán các chuỗi dài cho một phần tử như thế nào

>>>

In [2]: import antigravity
02

Trong mã này, bạn lại gán phần tử đầu tiên của mảng có giá trị

In [2]: import antigravity
317. Bạn có thể thấy từ dòng đầu ra rằng chuỗi đó được lưu trữ dưới dạng phần tử đầu tiên của mảng mà không bị cắt bớt, vì dtype là
In [2]: import antigravity
319. Nhược điểm của việc sử dụng dtype
In [2]: import antigravity
319 là nó thường chậm hơn nhiều so với dtype cụ thể hơn là
In [2]: import antigravity
314, bởi vì nó phải tạo toàn bộ đối tượng Python cho từng phần tử thay vì chỉ một đối tượng Unicode được tối ưu hóa cho NumPy

Một điểm khác biệt nữa mà bạn sẽ nhận thấy từ MATLAB là hình dạng hoặc kích thước của mảng được xác định như thế nào.

>>>

In [2]: import antigravity
03

Trong mã này, chúng tôi đang in hình dạng của

In [2]: import antigravity
174 và
In [2]: import antigravity
320. Để ý rằng chúng đều có hình dạng giống nhau, hai phần tử trong mảng một chiều. Điều này tương tự với mảng chuỗi trong MATLAB, trong đó mỗi chuỗi được tính là một phần tử trong mảng. Tuy nhiên, thực tế là mảng NumPy với kiểu dtype
In [2]: import antigravity
314 có kích thước tối đa cố định hoạt động giống mảng ký tự từ MATLAB hơn. Bạn sẽ thấy nhiều hơn về sự khác biệt trong cách MATLAB và NumPy tính toán hình dạng của mảng trong phần sau

Thư viện không được tải lại tự động trong Python

Khi thực thi một chức năng hoặc tập lệnh, MATLAB sẽ luôn sử dụng bản sao mới nhất của tệp trên đĩa. Do đó, khi bạn đang phát triển tập lệnh, bạn có thể chạy tập lệnh đó trong bảng điều khiển nhiều lần và những thay đổi mới mà bạn thực hiện sẽ tự động được chọn

Python hoạt động hơi khác. Hãy nhớ rằng khi bạn muốn truy cập mã từ một tệp, bạn phải

In [2]: import antigravity
687 nó vào một không gian tên. Khi Python nhập một tệp hoặc mô-đun, nó chỉ đọc mã trong lần nhập đầu tiên. Điều này tiết kiệm khá nhiều thời gian nếu bạn nhập cùng một tệp nhiều lần. Tuy nhiên, nếu bạn đang kiểm tra mã của mình trong lời nhắc của bảng điều khiển tương tác khi bạn làm việc với mã đó, Python sẽ không nhận bất kỳ thay đổi nào nếu bạn
In [2]: import antigravity
687 lại mã đó

Khi bạn đang phát triển một mô-đun, bạn có một số tùy chọn để Python tải lại mã của bạn khi mã được nhập. Nếu bạn đang sử dụng Spyder IDE thì đây hoàn toàn không phải là vấn đề, vì Spyder có tính năng Tải lại mô-đun người dùng tự động được bật theo mặc định

Mặt khác, nếu bạn đang sử dụng bảng điều khiển IPython bên ngoài Spyder hoặc Jupyter Notebook, bạn có thể sử dụng một lệnh ma thuật được xác định trong các trình thông dịch đó có tên là

In [2]: import antigravity
332

>>>

In [2]: import antigravity
04

Trong mã này, bạn đang sử dụng lệnh ma thuật

In [2]: import antigravity
333 để tải tiện ích mở rộng
In [2]: import antigravity
332. Trong IPython và Jupyter Notebooks, các lệnh có tiền tố là dấu phần trăm
In [2]: import antigravity
72 là các lệnh ma thuật. Tiện ích mở rộng
In [2]: import antigravity
332 xác định chức năng ma thuật
In [2]: import antigravity
332 mà bạn sử dụng trên dòng đầu vào 2. Bạn đang chuyển tham số
In [2]: import antigravity
338 cho hàm ma thuật
In [2]: import antigravity
332, có nghĩa là tất cả các mô-đun sẽ được tải lại mỗi khi một dòng mã được thực thi

Remove ads

Tổng quan về hoạt động mảng cơ bản

Như bạn đã thấy, Python không bao gồm thư viện tốc độ cao dành cho mảng trong thư viện chuẩn của nó. Tuy nhiên, thư viện NumPy tuyệt vời có sẵn dễ dàng nếu bạn cài đặt Anaconda. NumPy có chức năng như thư viện ma trận và mảng thực tế cho Python

NumPy có hai loại giống như mảng

  1. In [2]: import antigravity
    
    340, còn được gọi là
    In [2]: import antigravity
    
    341
  2. In [2]: import antigravity
    
    342

Sự khác biệt chính giữa hai loại này là

In [2]: import antigravity
343 có thể là bất kỳ số lượng kích thước nào, trong khi
In [2]: import antigravity
344 bị giới hạn ở chính xác hai kích thước. Đối với
In [2]: import antigravity
343, tất cả các phép toán như cộng, trừ, nhân, lũy thừa và chia đều hoạt động theo nguyên tố. Tuy nhiên, đối với loại
In [2]: import antigravity
344, các phép toán như nhân và lũy thừa là các phép toán ma trận

Khi bạn đang chuyển đổi từ MATLAB, loại

In [2]: import antigravity
344 có vẻ quen thuộc hơn. Nó cung cấp hành vi tương tự mà bạn có thể đã quen với MATLAB về mặt cú pháp hoạt động. Tuy nhiên, NumPy thực sự khuyên bạn nên sử dụng loại
In [2]: import antigravity
343 vì loại này linh hoạt hơn và vì
In [2]: import antigravity
344 cuối cùng sẽ bị xóa

Trong phần còn lại của phần này, bạn sẽ biết những khác biệt chính giữa các mảng MATLAB và NumPy. Bạn có thể tìm hiểu sâu về cách sử dụng mảng NumPy bằng cách đọc Look Ma, No For-Loops. Lập trình mảng với NumPy

Các toán tử toán học cơ bản hoạt động thông minh trong NumPy

MATLAB, với di sản là ngôn ngữ kịch bản ma trận, giả định rằng tất cả các toán tử số học sẽ hoạt động trên mảng. Do đó, MATLAB coi phép nhân ma trận hoặc vectơ là phép nhân ma trận. Hãy xem xét ví dụ này

>>>

In [2]: import antigravity
05

Trong mã này, bạn đang tạo hai ma trận 1x3,

In [2]: import antigravity
350 và
In [2]: import antigravity
320. Sau đó, bạn đang cố gắng nhân chúng lại với nhau. Đối với các mảng 1xN này, điều này tương đương với việc lấy tích vô hướng hoặc vô hướng. Tuy nhiên, tích vô hướng chỉ hoạt động khi toán hạng bên trái là 1xN và bên phải là Nx1, vì vậy MATLAB tạo ra một thông báo lỗi và gợi ý toán tử dấu sao (
In [2]: import antigravity
352) là cú pháp thích hợp cho phép nhân phần tử

>>>

In [2]: import antigravity
06

Trong đoạn mã này, bạn đang thực hiện phép nhân từng phần tử của

In [2]: import antigravity
350 và
In [2]: import antigravity
320. Điều này nhân phần tử đầu tiên của
In [2]: import antigravity
350 với phần tử đầu tiên của
In [2]: import antigravity
320 (
In [2]: import antigravity
357), thứ hai với thứ hai (
In [2]: import antigravity
358) và thứ ba với thứ ba (
In [2]: import antigravity
359)

Để thực hiện tích vô hướng, bạn có thể thực hiện chuyển vị của

In [2]: import antigravity
320 để chuyển nó thành mảng 3x1

>>>

In [2]: import antigravity
07

Trong mã này, bạn đang thực hiện phép nhân ma trận với

In [2]: import antigravity
350 và chuyển vị của
In [2]: import antigravity
320. Lưu ý rằng bạn có thể sử dụng
In [2]: import antigravity
363 hoặc toán tử báo giá (
In [2]: import antigravity
790) để chuyển vị của
In [2]: import antigravity
320. Vì
In [2]: import antigravity
350 là 1x3 và
In [2]: import antigravity
367 là 3x1, điều này dẫn đến tích vô hướng hoặc dấu chấm

Với mảng NumPy, các phép toán như phép nhân với dấu hoa thị (

In [2]: import antigravity
202) hoạt động theo nguyên tố theo mặc định

>>>

In [2]: import antigravity
08

Trong đoạn mã này, trước tiên bạn nhập gói NumPy và gán nó với tên

In [2]: import antigravity
695. Sau đó, bạn đang tạo hai mảng một chiều. Lưu ý cú pháp tạo mảng trong NumPy. Nó bắt đầu bằng
In [2]: import antigravity
370, nên đọc là “từ trong
In [2]: import antigravity
695, tìm
In [2]: import antigravity
372. ” Sau đó, bạn phải chuyển một danh sách Python hoặc bộ dữ liệu tới hàm tạo mảng chứa các phần tử của mảng. Trong trường hợp này, bạn đang chuyển một danh sách Python, được biểu thị bằng dấu ngoặc vuông

Cuối cùng, trên dòng đầu vào 4, bạn đang nhân

In [2]: import antigravity
350 và
In [2]: import antigravity
320. Lưu ý rằng kết quả trên dòng đầu ra 4 là một mảng khác với các phần tử 4, 10 và 18, kết quả tương tự như phép nhân theo phần tử trong MATLAB

Nếu bạn muốn thực hiện tích vô hướng hoặc vô hướng cho hai mảng trong NumPy, bạn có hai tùy chọn. Tùy chọn ưu tiên là sử dụng toán tử nhân ma trận (______4730) được thêm vào trong Python 3. 5. Bạn có thể thấy một số mã cũ hơn cũng sử dụng

In [2]: import antigravity
376 từ thư viện NumPy và chuyển hai mảng

>>>

In [2]: import antigravity
09

Trong mã này, dòng đầu vào 5 sử dụng toán tử nhân ma trận để tìm tích vô hướng của

In [2]: import antigravity
350 và
In [2]: import antigravity
320. Đúng như dự đoán, kết quả là 32. Dòng đầu vào 5 sử dụng
In [2]: import antigravity
376 và phải được đọc là “từ trong
In [2]: import antigravity
695, tìm
In [2]: import antigravity
376 và vượt qua
In [2]: import antigravity
350 và
In [2]: import antigravity
320. ” Bạn có thể thấy rằng kết quả là giống hệt nhau

Lưu ý rằng NumPy không yêu cầu bạn chuyển đổi

In [2]: import antigravity
320 trước khi thực hiện tích vô hướng. Bạn sẽ tìm hiểu thêm về tính năng này trong phần tiếp theo

Remove ads

Mảng một chiều là các vectơ trong NumPy

Như bạn đã thấy trong phần trước, MATLAB nhấn mạnh rằng kích thước của mảng thẳng hàng khi thực hiện phép nhân ma trận, trong khi NumPy linh hoạt hơn một chút. Điều này là do cách mảng một chiều được xử lý trong MATLAB so với trong NumPy

Trong MATLAB, mọi mảng luôn có ít nhất hai chiều, ngay cả khi chỉ ngầm định. Bạn có thể thấy điều này bằng cách kiểm tra

In [2]: import antigravity
385 của một số

>>>

In [2]: import antigravity
10

Ở đây, bạn đang tìm kích thước của số nguyên 1. Bạn có thể thấy rằng kết quả là một mảng có 1 hàng và 1 cột

Bạn có thể tạo các vectơ hàng hoặc vectơ cột trong MATLAB và chuyển đổi giữa chúng bằng toán tử chuyển vị (

In [2]: import antigravity
790) hoặc
In [2]: import antigravity
363

>>>

In [2]: import antigravity
11

Trong mã này, bạn đang tạo hai vectơ.

In [2]: import antigravity
350 và
In [2]: import antigravity
320. Mảng chỉ có các giá trị trong một chiều được gọi là vectơ.
In [2]: import antigravity
350 là một vectơ hàng vì các phần tử được sắp xếp thành một hàng và ba cột, trong khi đó,
In [2]: import antigravity
320 là một vectơ cột vì các phần tử được sắp xếp thành ba hàng và một cột. Trong MATLAB, các phần tử được đặt vào các cột khác nhau bằng cách phân tách chúng bằng dấu phẩy trong phép gán và các phần tử được đặt vào các hàng khác nhau bằng cách phân tách chúng bằng dấu chấm phẩy

Sau đó, bạn đang kiểm tra sự bằng nhau của phép chuyển vị của

In [2]: import antigravity
350 với
In [2]: import antigravity
320 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ơ cột có giá trị logic. Finally, you are checking the equality of the transpose of
In [2]: import antigravity
320 with
In [2]: import antigravity
350, and you find that all of the elements are equal and the result is a row vector of logical values

Bạn có thể thấy rằng trong MATLAB, ngay cả các vectơ cũng có hai chiều được liên kết với chúng. hàng và cột. Khi hoán vị được thực hiện, các hàng được hoán đổi với các cột và hình dạng của mảng bị thay đổi. Điều này có nghĩa là có hai loại vectơ trong MATLAB. vectơ hàng và vectơ cột

Trong NumPy, có ba loại mảng hoặc vectơ một chiều. Mặc định là một vectơ N phần tử chỉ có một chiều. Điều này khác với mặc định trong MATLAB, nơi mỗi mảng có ít nhất 2 chiều. Vectơ một chiều này trong NumPy không có ý nghĩa về hàng và cột, vì đối với cấu trúc một chiều, nói chung các phần tử được lưu trữ theo hàng hay cột không quan trọng, chỉ có bao nhiêu phần tử mà thôi

Bạn có thể xem ví dụ tạo kiểu mảng này ở ví dụ sau. Trong một vài ví dụ tiếp theo, có thêm khoảng trắng được thêm vào trước và sau dấu ngoặc đơn để làm rõ cú pháp. Những không gian này thường không được coi là phong cách Python tốt, nhưng chúng có trong ví dụ để giúp bạn thấy điều gì đang xảy ra

>>>

In [2]: import antigravity
12

Trong mã này, bạn đang tạo một vectơ 3 phần tử mặc định trong NumPy. Trên dòng đầu vào 1, bạn nhập NumPy và cung cấp nó theo

In [2]: import antigravity
695. Trên dòng đầu vào 2, bạn đang tạo mảng và lưu trữ nó trong
In [2]: import antigravity
397. Bạn đang chuyển danh sách
In [2]: import antigravity
398 đến
In [2]: import antigravity
372, trong đó danh sách có 3 phần tử và không có phần tử nào chính là danh sách. Điều này tạo ra mảng 3 phần tử chỉ có một chiều

Bạn có thể xác minh rằng đây là trường hợp bằng cách hiển thị hình dạng của mảng, như được hiển thị trên dòng đầu vào 3. Dòng đó nên được đọc là “từ bên trong

In [2]: import antigravity
397 (một mảng), tìm
In [2]: import antigravity
001. ”
In [2]: import antigravity
001 của mảng tương đương với
In [2]: import antigravity
385 trong MATLAB. Trong trường hợp này, hình dạng là
In [2]: import antigravity
004, cho biết có ba phần tử và chỉ có một chiều, vì không có số thứ hai sau dấu phẩy

Bạn cũng có thể tạo vectơ hàng và vectơ cột trong NumPy, tương tự như vectơ hàng và vectơ cột trong MATLAB. NumPy's

In [2]: import antigravity
372 lấy danh sách phẳng hoặc danh sách lồng nhau làm đầu vào. Sử dụng danh sách phẳng giúp bạn có một vectơ phần tử N một chiều. 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

In [2]: import antigravity
13

Trong mã này, bạn thấy một danh sách bên ngoài có 2 phần tử. Mỗi trong số 2 phần tử này của danh sách bên ngoài là một danh sách khác, được lồng vào nhau, có ba phần tử, các số nguyên 1-3 và 4-6. Về mảng, bạn có thể coi số phần tử của mỗi danh sách bên trong là số cột và số danh sách lồng nhau là số hàng. Điều này dễ thấy hơn nếu bạn thay đổi định dạng

In [2]: import antigravity
14

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. Trong trường hợp này, chúng ta sẽ có một mảng có 2 hàng và 3 cột. 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

>>>

In [2]: import antigravity
15

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

In [2]: import antigravity
006 đến
In [2]: import antigravity
372. 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

In [2]: import antigravity
16

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. Như mong đợi, hình dạng là

In [2]: import antigravity
008 hoặc một hàng có ba cột

Finally, you can create a column array by including three nested lists in the input

>>>

In [2]: import antigravity
17

In this code, input line 6 is passing

In [2]: import antigravity
009 to the array constructor. You can break out the formatting of this nested list to see how it looks

In [2]: import antigravity
18

As you can see, there are three rows in this nested list with one column each. On input line 7, you are displaying the shape of this array. As expected, the shape is

In [2]: import antigravity
010, or three rows with one column

Since the general N-element vector has no sense of rows and columns, NumPy is able to shape the vector in whatever way makes sense for the operation being performed. You saw this in the last section, where the NumPy array did not need to be transposed to perform the scalar product, whereas the MATLAB array did need to be transposed

Trying to take the transpose of the N-element vector does not change the shape of the array. You can take the transpose using either

In [2]: import antigravity
011 or the
In [2]: import antigravity
012 attribute of the array

>>>

In [2]: import antigravity
19

In this code, you are taking the transpose of the N-element vector

In [2]: import antigravity
397 and printing its shape. Notice that the shape is the same as the shape of the original
In [2]: import antigravity
397

However, if you are using row-vectors and column-vectors, you will need to ensure that the dimensions are appropriate for the particular operation. For instance, trying to take the scalar product of the row vector with itself will result in an error

>>>

In [2]: import antigravity
20

In this code, trying to find the scalar product of the row vector with itself results in a

In [2]: import antigravity
015 informing you that the dimensions of the arrays are not aligned. Using
In [2]: import antigravity
376 gives the same error but a slightly different message

>>>

In [2]: import antigravity
21

In this code, you are using

In [2]: import antigravity
376 from the
In [2]: import antigravity
695 namespace to attempt to find the scalar product of two 1x3 row-vectors. Since this operation is not permitted, NumPy raises a
In [2]: import antigravity
015, similar to the matrix multiplication operator

Instead, you need to take the transpose of one of the arguments

>>>

In [2]: import antigravity
22

On input line 12, you are taking the transpose of the row vector to turn it into a column vector using the transpose attribute (

In [2]: import antigravity
012). This is shown in corresponding output line, where the elements are arranged to form a column for printing purposes. Then, you are taking the scalar product of the vector with its transpose, producing an array with a single value, 14. Notice that this is a 1x1 array, so to access just the value, you need to access the first element in each dimension

>>>

In [2]: import antigravity
23

In this code, you are verifying that the shape is 1x1, and then accessing the first element in each dimension located at the 0th index. Remember that Python uses 0 as the first index, not 1

You can use the nested lists to create arrays of any shape that you want. To create a three-by-three array (two-dimensional), simply include three elements in each of your three nested lists

>>>

In [2]: import antigravity
24

In this code, you have nested three lists with three elements each into the constructor. As shown by the shape, this produces a 3x3 array with the elements 1 through 9

Remove ads

Creating Arrays Is Very Flexible in NumPy

MATLAB and NumPy both allow you to explicitly specify the specific elements in an array, as you have seen in the previous section. In addition to this direct creation of arrays, both MATLAB and NumPy support a number of other methods to create arrays without explicitly specifying each element. Dự án NumPy duy trì một danh sách chi tiết các chức năng tương đương giữa MATLAB và NumPy

Many functions operate identically between MATLAB and NumPy. This includes commonly used functions like

In [2]: import antigravity
021 and
In [2]: import antigravity
022 to generate evenly spaced data and
In [2]: import antigravity
023 and
In [2]: import antigravity
024 to generate arrays of a given shape filled with ones and zeros, respectively. The full list of ways to create arrays in NumPy is listed in the official documentation

The one big difference between MATLAB and NumPy in terms of array creation routines is that MATLAB supports simply using the colon to create an array, while NumPy does not. Instead, NumPy uses

In [2]: import antigravity
025 to create an array between specified values

In MATLAB, you can use a colon to create an array specification range. In general, you can use up to 2 colons in a specification. The syntax is as follows

In [2]: import antigravity
25

In this syntax, the, first method only uses one colon and specifies the start and stop values. The second method includes a second colon, where the value before the first colon is the start, the middle value is the step, and the last value is the stop

Try out these examples to experiment with this syntax

>>>

In [2]: import antigravity
26

In this example, you are using the single colon with the start and stop to generate an array with the values from 1 to 6. You can see that when the step is omitted, it defaults to a value of 1. Notice that MATLAB includes both the start and the stop values in the array, and that the size of the array is 6 elements long. Next, change the value of the step size to create a new array

>>>

In [2]: import antigravity
27

In this example, you are using the two colons syntax with the start, step, and stop. The start value is 1, the step is 2, and the stop value is 6, so MATLAB starts with 1, increments to 3, and then to 5. The next step would exceed the stop value, so MATLAB does not include the stop value in the array. Next, change the starting value to create another new array

>>>

In [2]: import antigravity
28

In this example, you are again using the two colon method, but you are specifying the start value as 2 instead of 1. In this case, MATLAB starts at 2, increments to 4, increments to 6, and then has reached the stop value so does not go further. Notice that in this case, the the stop value of 6 is included in the array

With NumPy, you can use

In [2]: import antigravity
025 to create an array with specific start, stop, and step values. However,
In [2]: import antigravity
025 has one big difference from MATLAB, which is that the stop value is not included in the resulting array. The reason for this is so that the size of the array is equal to
In [2]: import antigravity
028 for the default case of a step size of 1. Notice in MATLAB that the size of the array of the integers from 1 to 6 is 6, but 6 - 1 = 5

There are three ways to use

In [2]: import antigravity
025

In [2]: import antigravity
29

If you only pass one argument to

In [2]: import antigravity
025, it will be interpreted as the stop value. The start value defaults to 0 and the step defaults to 1. If you pass two arguments to
In [2]: import antigravity
025, they are interpreted as the start and stop values. Finally, you can pass all three of start, stop, and step to
In [2]: import antigravity
025

Notice that the order of the arguments is different from MATLAB, going

In [2]: import antigravity
033,
In [2]: import antigravity
034,
In [2]: import antigravity
035 in Python. If you’re having trouble remembering the order that these arguments go, remember that you can use keyword arguments in Python to be explicit about what each argument means

You can try out

In [2]: import antigravity
025 with the following examples

>>>

In [2]: import antigravity
00

In this example, you are creating an array that contains the values from 1 to 6. As in MATLAB, if the step is omitted, it defaults to 1. Notice that you had to pass the stop value 7 so that the array stopped at 6. However, the size of the resulting array is 7 - 1 = 6 elements long. Next, you should see how to change the step size

>>>

In [2]: import antigravity
01

In this code, you are creating an array that contains the values from 1 to 6, incrementing by two between each element. The step is two, so NumPy starts with 1, increments to 3, and then to 5. The next step would equal the stop value, but NumPy does not include the stop value in the array. Notice that the formula to compute the size of the array is a little bit different, since the step size is not 1

With step sizes other than 1, the size of the array can be computed by

In [2]: import antigravity
037 if this results in an integer value. In this case, the size of the array is (7 - 1)/2 = 3 elements, as expected. If
In [2]: import antigravity
037 results in a floating point number, the size of the array is equal to the next largest integer as demonstrated in the next example

>>>

In [2]: import antigravity
02

In this example, you are creating an array that contains the values from 2 to 6, incrementing by two between each element. The step is two, so NumPy starts with 2, increments to 4, and then to 6. Bước tiếp theo sẽ vượt quá giá trị dừng, vì vậy NumPy dừng ở 6. Notice that the size of the array is (7 - 2)/2 = 2. 5, so the next highest integer is 3 elements, as expected

Finally, you should usually use integer arguments to

In [2]: import antigravity
025 in NumPy and the colon operator in 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. If you want to use floating point numbers,
In [2]: import antigravity
021 is a better choice in general

Remove ads

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

In MATLAB, the colon operator is used to perform a number of useful tasks. As you saw, it can be used to create arrays, and it can also be used to index or slice arrays. 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 chiều đó, như bạn đã thấy trước đó

>>>

In [2]: import antigravity
03

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

In [2]: import antigravity
350 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

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

In [2]: import antigravity
320 với các số từ 1 đến 6, bao gồm. Sau đó, bạn đang chỉ định phần tử thứ hai làm giá trị bắt đầu và phần tử thứ tư làm giá trị dừng trong lát cắt. MATLAB cũng hỗ trợ cú pháp tăng hai dấu hai chấm khi lập chỉ mục

>>>

In [2]: import antigravity
05

In this code, you are indexing the array, starting at the second element, skipping every other element, until the end of the array. 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

In [2]: import antigravity
320 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

In [2]: import antigravity
046, whereas in MATLAB, it is
In [2]: import antigravity
047, 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
In [2]: import antigravity
034 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

In [2]: import antigravity
025 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

In [2]: import antigravity
025 does not include the stop value, so that the length of the resulting array is equal to
In [2]: import antigravity
028. 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. This results in an array with the values 2, 4, and 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

Remove ads

Array Slices Are Views of Arrays in NumPy

In MATLAB, when you access a slice of an array and assign it to a variable, MATLAB will make a copy of that portion of the array into your new variable. This means that when you assign values to the slice, the original array is not affected. Try out this example to help explain the differences of MATLAB vs Python

>>>

In [2]: import antigravity
13

In this code, you have created a 3x3 array

In [2]: import antigravity
350 storing the values from 1 through 9. Then, you create a 2x2 slice of the original array storing from the second value to the end in both dimensions,
In [2]: import antigravity
320. On the third input line, you assign the value 10 to the upper left element in
In [2]: import antigravity
320. Finally, you print
In [2]: import antigravity
350 again to verify that none of the values in
In [2]: import antigravity
350 have changed

Technical detail. MATLAB employs a copy-on-write memory management system, where an array may only be copied to a new memory location when it is modified. You can read more about MATLAB memory management in Memory Management for Functions and Variables on the Mathworks blog and in Internal Matlab memory optimizations

In NumPy, slices of arrays are views to the original array. This behavior saves memory and time, since the values in the array don’t have to be copied to a new location. However, it means that changes that you make to a slice from an array will change the original array. You should try the following code to see how this works

>>>

In [2]: import antigravity
14

In this code, you are creating a 3x3 array

In [2]: import antigravity
350 storing the values from 1 through 9. Then, you create a 2x2 slice of the original array storing from the second value to the end in both dimensions,
In [2]: import antigravity
320. Notice that the Python indexing is 0-based, so the second element has the index 1. Finally, you are printing
In [2]: import antigravity
320 to verify that it is a 2x2 array

Now you should see what happens when you change a value in

In [2]: import antigravity
320. Like in the MATLAB example, you should change the upper left element of
In [2]: import antigravity
320

>>>

In [2]: import antigravity
15

In this code, you first assign the upper left element in

In [2]: import antigravity
320, at index (0, 0) to have a value of 10. Then you print
In [2]: import antigravity
320 to verify that the appropriate value has changed. Finally, you print
In [2]: import antigravity
350 and see that the value in the middle of the array has changed from 5 to 10

This is what is meant by

In [2]: import antigravity
320 being a view of
In [2]: import antigravity
350. Since it is a view,
In [2]: import antigravity
320 points to the same memory location as
In [2]: import antigravity
350, so updating
In [2]: import antigravity
320 also updates
In [2]: import antigravity
350 because the value stored in the memory location accessed by both
In [2]: import antigravity
320 and
In [2]: import antigravity
350 has been updated. This also goes the other direction, where changing values in
In [2]: import antigravity
350 will update the value in
In [2]: import antigravity
320

>>>

In [2]: import antigravity
16

In this code, you are assigning the bottom right element of

In [2]: import antigravity
350 to have the value 42. Remember that in Python, an index of
In [2]: import antigravity
187 means the last value on that dimension. Then you are printing
In [2]: import antigravity
350 to verify that the lower right value has changed from 9 to 42. Finally, you are printing
In [2]: import antigravity
320, and you see for
In [2]: import antigravity
320 as well, the bottom right value has changed from 9 to 42

If you want to generate a copy of an array, you can use

In [2]: import antigravity
081. Copying an array creates a new place in memory for the copy to be stored, so changes to the copied array do not affect the original

>>>

In [2]: import antigravity
17

In this code, you are creating

In [2]: import antigravity
082 as a copy of
In [2]: import antigravity
320. Then, you are changing the element in the second row, first column to have the value of 37. Then, you are printing
In [2]: import antigravity
082 to verify that the specified change has been made. Finally, you are printing
In [2]: import antigravity
320 to verify that no changes have occurred in
In [2]: import antigravity
320, as expected

Tips and Tricks to Make Your Code Pythonic

Like any other programming language, Python code written by experienced Python developers often has a particular look and feel to it. This is because they are able to take advantage of specific idioms in Python to work with Python rather than against Python. Developers coming from other languages often miss out on what makes code Pythonic in their first projects

In this section, you’ll learn some tips and tricks to make your code Pythonic and level up your Python skills. There are many more tips and tricks than you can learn here, so feel free to check out Write More Pythonic Code

You Should Not Use Semicolons to End Lines in Python

In MATLAB, ending a line of code with a semicolon

In [2]: import antigravity
087 suppresses the output from that line. For instance, assigning a variable will print the value of the variable after the assignment if the semicolon is omitted

In Python, you should not end lines of code with semicolons. It is unnecessary, since Python does not change its behavior whether the line is ended with a semicolon or not. So you can save yourself a key stroke and not bother including the semicolon in your scripts and libraries

There is one case in Python where the semicolon is useful. When you want to execute several statements, but you cannot include a newline character in the input, you can separate the statements with semicolons. This is mostly useful to execute very short scripts from the command prompt or terminal. For instance, to find the particular Python executable that is running, you can type the following

In [2]: import antigravity
18

In this code, you are executing the Python interpreter in the

In [2]: import antigravity
088 executable and passing the
In [2]: import antigravity
089 switch. This switch takes the next argument and executes it within the interpreter. Since the shell environment would execute if you pressed Enter to insert a new line, you can type the whole script on one line.

In this case, you have two logical statements that need to be separated by the semicolon. First you are importing the built-in

In [2]: import antigravity
090 library and then you are printing the value of
In [2]: import antigravity
091. In this example, the Python interpreter that the shell is running comes from the
In [2]: import antigravity
092 file

You Should Not Import In [2]: import antigravity 202 From a Module in Python

In a previous section, you read about how namespaces are one honking great idea in Python. In MATLAB, all functions are part of the global namespace by default, so every function and class name has to be unique. Python solves this problem by using namespaces and requiring you to specify which module a function should come from

You will find tutorials around the Web that suggest you write the following

In [2]: import antigravity
19

In this code, you are using the

In [2]: import antigravity
202 to indicate that Python should import everything that is contained in
In [2]: import antigravity
095 and put it in the current scope without a prefix. This is slightly more convenient, because you no longer have to prefix functions and classes from
In [2]: import antigravity
095 with anything, you can just use them directly. However, it is not a good practice because you don’t know what names are defined in
In [2]: import antigravity
095 and whether or not they will override any existing names in your current scope

Lưu ý kỹ thuật. When you

In [2]: import antigravity
098, Python imports all of the names listed in a special variable called
In [2]: import antigravity
099 in
In [2]: import antigravity
095. 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
In [2]: import antigravity
095

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

MATLAB, với di sản là một ngôn ngữ tập trung vào mảng và đại số tuyến tính, xử lý hầu hết các kiểu dữ liệu dưới dạng một số mảng. Đ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ư

In [2]: import antigravity
102,
In [2]: import antigravity
103, 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. The major ones that you’ll learn about in this section are lists and dictionaries

Lists

Python lists are mutable sequences of values. Lists can contain heterogeneous data, which means that each element of the list can be of a different type. Because lists are mutable, you can change the value of any element in the list, or add or remove values from the list, without creating a new list object

Since lists are sequences, you can create loops that iterate over them. In Python, you do not need to access each element of a list with an index in a

In [2]: import antigravity
97 loop, as you would do in MATLAB

>>>

In [2]: import antigravity
20

In this code, you are creating an array

In [2]: import antigravity
350 with the integers from 1 to 6, taking every other number. Then you are creating a
In [2]: import antigravity
97 loop where the loop variable goes from 1 to the length of
In [2]: import antigravity
350. Finally, you are displaying the value of the element of
In [2]: import antigravity
350 at the loop variable on each step by using the loop variable
In [2]: import antigravity
126 to index
In [2]: import antigravity
350

In Python, you should not use an index for the list when you loop over it. Instead, you should loop directly over the items in a list

>>>

In [2]: import antigravity
21

In this code, on input line 1 you are first creating a Python list with three elements

  1. The integer
    In [2]: import antigravity
    
    178
  2. The string
    In [2]: import antigravity
    
    112
  3. The float
    In [2]: import antigravity
    
    113

This list is assigned to

In [2]: import antigravity
114. Then you are using a
In [2]: import antigravity
97 loop to access each item in the list in turn. On each iteration, the next value in the list is put into the variable
In [2]: import antigravity
116 that you specified on the
In [2]: import antigravity
97 line. Then, you are printing the value of
In [2]: import antigravity
116 on each iteration

Notice in the previous example that you could loop over the value of each element in the list without using an index. Nonetheless, sometimes you want to access the index of each item in the list as you’re looping over it. For those cases, Python provides

In [2]: import antigravity
119 that returns the index and the value of the item

>>>

In [2]: import antigravity
22

In this code, you are looping over

In [2]: import antigravity
114 again, but this time, you are using
In [2]: import antigravity
119 to get both the index and the item. Then you are printing the value of the index and item on each loop iteration. As you can see from the result, the index values start at 0 as expected, but you do not need to use the index to access the item from the list

In summary, you should not write Python code like this

In [2]: import antigravity
23

In this code, you are creating a range of integers from 0 to the length of

In [2]: import antigravity
114 and then you are accessing each element in the list by its index. This can lead to off-by-one and fencepost errors. Instead, you should write code that loops over the list directly

In [2]: import antigravity
24

You can read a lot more about lists in Lists and Tuples in Python and about

In [2]: import antigravity
97 loops and iteration in Python “for” Loops (Definite Iteration). There is also a more advanced concept called list comprehensions that you can learn about in Using List Comprehensions Effectively

Dictionaries

In MATLAB, you can create a map data type with

In [2]: import antigravity
124. This kind of data structure is useful when you have two pieces of data that are always related to each other and you want to connect them together. For instance, you can map cities to their population with a
In [2]: import antigravity
124

>>>

In [2]: import antigravity
25

In this code, you are creating a

In [2]: import antigravity
124 on the first line. The first argument is a cell array of character arrays with the city names. These are called the keys of the map. The second argument is an array of populations. These are called the values of the map. Then, you are accessing the value of the population in Cleveland by indexing the map with a character array

You can assign new values into the map by assigning to an undefined key value

>>>

In [2]: import antigravity
26

If you try to access a key that does not exist, you will receive an error message

>>>

In [2]: import antigravity
27

Python has an equivalent data structure called a dictionary. 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. Notice that the key and value are specified together, separated by a colon. The values are specified with

In [2]: import antigravity
716 in the numbers, a feature available since Python 3. 6. This does not change the value of the number, it only makes it easier to read very large numbers. Then, you are accessing the value at the
In [2]: import antigravity
128 key using square brackets, similar to the indexing syntax for lists and arrays

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

>>>

In [2]: import antigravity
29

In this code, you assigned a new key

In [2]: import antigravity
129 to the dictionary with a value of 180,393. If you try to access a key that is not in the dictionary, you will get a
In [2]: import antigravity
130

>>>

In [2]: import antigravity
30

In this code, you are trying to access the dictionary using the

In [2]: import antigravity
131 key. However, this key does not exist in the dictionary so Python raises a
In [2]: import antigravity
130 letting you know that
In [2]: import antigravity
131 is not an option

You can read a lot more about Python dictionaries in Dictionaries in Python and

In [2]: import antigravity
130 exceptions in Python KeyError Exceptions and How to Handle Them. You can also iterate through dictionaries and use dictionary comprehensions, similar to list comprehensions. You can read about these topics in How to Iterate Through a Dictionary in Python

Exceptions Help You Control Program Flow in Python

MATLAB and Python both use errors and exceptions to let you know when something has gone wrong in the code. In this section, you will learn about common exceptions in Python and how you can handle them appropriately

If you want an introduction to Python exceptions overall, you can read Python Exceptions. An Introduction. When a Python exception is raised, it produces a traceback. You can read about how to interpret the traceback in Understanding Python Tracebacks. Understanding tracebacks is very helpful to interpret and correct Python exceptions in general. There are a few specific cases that usually have the same resolution. You’ll see those described in the rest of this section

NameError

Python

In [2]: import antigravity
135 exceptions are usually the result of a variable being undefined. When you see a
In [2]: import antigravity
135, check your code for typos and misspelled variable names. You can use the debugging features and the variable explorer in Spyder to find out which variables are defined

SyntaxError

Python

In [2]: import antigravity
137 exceptions mean that you have input some improper syntax. This is usually caused by mismatched brackets, when you have only the opening bracket or closing bracket but not the matching one. These exceptions usually point to the line after the place where the problem is located

Another common

In [2]: import antigravity
137 is using only one equals sign in an
In [2]: import antigravity
96 statement. In this case, you either meant not-equals (
In [2]: import antigravity
140) or equals (
In [2]: import antigravity
141), so you can correct the line. For more on
In [2]: import antigravity
137 exceptions, check out Invalid Syntax in Python. Common Reasons for SyntaxError

KeyError

Python

In [2]: import antigravity
130 exceptions occur when you try to access a key in a dictionary that does not exist. You can use
In [2]: import antigravity
144 to retrieve a key from a dictionary if it exists, or return a default value if the key does not exist. You can read more about
In [2]: import antigravity
130 exceptions in Python KeyError Exceptions and How to Handle Them

IndexError

Python

In [2]: import antigravity
146 exceptions occur when you are trying to access the index of an array or list that does not exist. This usually means the array or list you are trying to access has fewer elements than the index you are trying to access. You can use the debugging features and the variable explorer in Spyder to see the size of lists and arrays and make sure you’re only accessing indices that exist

ImportError/ModuleNotFoundError

Python

In [2]: import antigravity
147 and
In [2]: import antigravity
148 exceptions occur when you try to import a module that Python cannot find. This might be because it is installed in a different
In [2]: import antigravity
32 environment or
In [2]: import antigravity
150, or it might be because you forgot to install the package

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

In [2]: import antigravity
151 hoặc
In [2]: import antigravity
152 và đảm bảo kích hoạt đúng môi trường. If you’re not using the
In [2]: import antigravity
153 environment in
In [2]: import antigravity
32, you also need to make sure to install Spyder or Jupyter into your environment

TypeError/ValueError

Python

In [2]: import antigravity
661 exceptions happen when an argument is of the wrong type. This happens most commonly when you pass an argument of the wrong type into a function. For instance, a function that works with numbers would raise a
In [2]: import antigravity
661 if a string were passed in

A related exception is the

In [2]: import antigravity
015. This exception happens when an argument is of the correct type, but has an incorrect value. For instance, a function that works only with positive numbers would raise a
In [2]: import antigravity
015 if a negative number were passed in

AttributeError

Python

In [2]: import antigravity
715 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 đó. You will often see this error associated with the message
In [2]: import antigravity
160. Thông báo này rất có thể có nghĩa là một hàm đã trả về
In [2]: import antigravity
601 thay vì đối tượng 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
In [2]: import antigravity
601

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

MATLAB cho phép bạn

In [2]: import antigravity
163 một câu lệnh mã và
In [2]: import antigravity
164 bất kỳ lỗi nào do mã đưa ra. Once you have caught an error, you can do further processing of the error and assign variables based on the type of error. The MATLAB documentation has several good examples of how this would look in MATLAB

In Python, one big difference from MATLAB is that you can choose to catch only certain types of exceptions and handle them. This allows all other exceptions to continue to be displayed to the user. If you want to learn more about how to do this in Python, you can read The

In [2]: import antigravity
163 and
In [2]: import antigravity
166 Block. Handling Exceptions

To see how this works, you can try the following example

>>>

In [2]: import antigravity
31

In this code, on input line 1 you are importing the built-in

In [2]: import antigravity
88 library. Then, starting on input line 2, you are defining a function called
In [2]: import antigravity
168 that will take one argument, called
In [2]: import antigravity
169. Inside the function definition, you first print the argument that the user passed

Next, you enter the

In [2]: import antigravity
163/
In [2]: import antigravity
166 block. First, you try to take the square root of the input argument and return the result. If taking the square root of the argument results in an error, Python will catch that error and check which type of error was raised

You have defined code that handles two specific exceptions.

In [2]: import antigravity
015 and
In [2]: import antigravity
661. If
In [2]: import antigravity
690 raises a
In [2]: import antigravity
015, your code will print a message that the number cannot be operated on. If
In [2]: import antigravity
690 raises a
In [2]: import antigravity
661, your code will print a message that the argument was not a number. If any other type of exception is raised by
In [2]: import antigravity
690, that error will be passed through without any processing, since there is no handler for any other error types

More specifically, Python checks for any error that is raised by the code in the

In [2]: import antigravity
163 block. In your case, you only defined one line of code in the
In [2]: import antigravity
163 block, but this is not required, and you can have as many lines as you want there. However, it is usually a good practice to minimize the number of lines of code in the
In [2]: import antigravity
163 block so you can be very specific about which code is raising any errors

On input line 3, you are testing out

In [2]: import antigravity
168. First, you pass the value 4. 0 to the function. The function prints the argument, and
In [2]: import antigravity
690 has no problems taking the square root of 4, resulting in 2. 0 on the output line

On input line 4, you are passing -1. 0 as the argument to

In [2]: import antigravity
168. As you may recall, taking the square root of negative numbers results in a complex number, which the
In [2]: import antigravity
690 function is not equipped to handle. Taking the square root of a negative number using
In [2]: import antigravity
690 raises a
In [2]: import antigravity
015. You exception handler catches this
In [2]: import antigravity
015 and prints the message that the number cannot be operated on

On input line 5, you are passing

In [2]: import antigravity
189 as the argument to
In [2]: import antigravity
168. In this case,
In [2]: import antigravity
690 does not know how to take the square root of a string, even though that string appears to represent a number. You can see that you have passed a string by the quotes in the statement giving the value of the argument.
In [2]: import antigravity
192. Since
In [2]: import antigravity
690 cannot take the square root of a string, it raises a
In [2]: import antigravity
661, and your function prints the message that the argument was not a number

There Is an Official Guide to Writing Good Code in Python

The Python community has developed a set of recommendations for how to style your Python code. These are codified in a document called PEP 8, which stands for Python Enhancement Proposal #8. PEP 8 can be found in full on the Python website. You can also learn more about good Python style in How to Write Beautiful Python Code With PEP 8 and Idiomatic Python 101

Perhaps the most important principle in PEP 8 is the saying that “a foolish consistency is the hobgoblin of little minds. ” This means that you should follow the recommendations in PEP 8 for almost all of your code, but there may be some limited cases where it is a good idea not to follow the PEP 8 recommendations. For instance, if you are working with an existing codebase that has its own style, you should follow that style where it diverges from PEP 8. You can see an excellent discussion of this principle from Raymond Hettinger, one of the core Python developers, in a talk from PyCon 2015

Aside from reading PEP 8, you can use a few Python packages to automatically make sure that your code fits the style guidelines. Flake8 is a code linter that reads your code and makes suggestions for how you can improve it. This is similar to the feature in the MATLAB code editor that makes improvement suggestions. In addition, packages such as Black, yapf, and autopep8 will automatically format your code to be compliant with PEP 8 or your own style rules. Using these packages can help your code feel more Pythonic and help you learn good Python style

Python Has a Fantastic and Supportive Community

Python is known for having a very supportive, open, and welcoming community. Whether you are a brand new developer or an experienced one, whether you’re brand new to Python or have been to a dozen conferences, the community is there to support you and what you want to do

The community starts with the Python Package Index (called PyPI or the CheeseShop, a reference to the Monty Python sketch), which houses hundreds of thousands of different Python packages that you can download for free. These packages can be installed using

In [2]: import antigravity
40, a package manager that comes bundled with Python. This means that adding the functionality you need to Python can be as simple as
In [2]: import antigravity
196 or if you’re using Anaconda,
In [2]: import antigravity
197

Since Python is used in so many different areas of software development, data science, science, and engineering, there are always people around who want to talk about Python. Most large cities around the world have Python meetup groups. You can go to these groups to learn about Python by hearing people speak about their work or work on some open-source code

A few times a year, these groups coalesce into different PyCons which happen on every continent around the globe. PyCon North America is the largest of these, with several thousand attendees every year. You can read all about what it’s like to attend in How to Get the Most Out of PyCon

Python also has a very strong online community. If you have a question about programming in Python, you can ask on StackOverflow and some of the world-leading Python experts will be able to help you out. Make sure to follow the instructions for how to ask a question on StackOverflow. Remember that the more effort you put into your question, the more likely you are to either find the answer yourself (hooray. ) or get a good answer from someone else

If you want to follow along with Python’s development, you can sign up for one of the mailing lists covering different aspects of Python’s community. The general mailing list for asking questions about writing programs in Python is called comp. lang. python. If you are interested in the development of Python itself, you can follow the python-dev mailing list

If you’re interested in learning much, much more about Python development, you can check out the Real Python Learning Paths

Areas Where You Should Still Use MATLAB®

In spite of the awesome community and terrific packages, there are still one or two areas where MATLAB works better than Python. The main place where Python can’t compete with MATLAB is the Simulink Toolbox. This toolbox offers advanced capabilities for signal processing and modeling in a convenient graphical interface

Python does not have an equivalent graphical interface to these kinds of functions. However, to the extent that Simulink is a convenient interface to ordinary differential equation solvers, Python has equivalent solvers as in MATLAB and the underlying functionality of Simulink can certainly be replicated in Python

Otherwise, you can do anything in Python that you can do in MATLAB. If you can think of work that you can do with MATLAB, but you’re not sure how to do it in Python, let us know in the comments and we’ll be able to help with suggestions

Conclusion

Congratulations, you now have the knowledge you need to switch your MATLAB code to Python. In this article, you learned a little bit about what Python is, how to set up your computer to use Python, and how to convert your code from MATLAB to Python

Python is a really huge language and community, with lots to learn and lots of people to learn from. Remember, you weren’t a MATLAB expert the first time you opened the MATLAB development environment, and the same is true about the first time you write some Python code. Come back to this article as often as you need to improve your skills and learn more about becoming a Python wizard

Further Reading

There are tons of resources on the Web covering the differences in MATLAB vs Python. Here are a few of the resources that I found helpful when I transitioned from MATLAB to Python

  • Webinar. Python for MATLAB Users, What You Need to Know (Video)
  • MATLAB To Python Whitepaper
  • Matlab vs. Julia vs. Python
  • Eight Advantages of Python Over MATLAB
  • 10 Reasons Python Rocks for Research (And a Few Reasons it Doesn’t)

Mark as Completed

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team

MATLAB tạo đối tượng Python

Send Me Python Tricks »

About Bryan Weber

MATLAB tạo đối tượng Python
MATLAB tạo đối tượng Python

Bryan is a core developer of Cantera, the open-source platform for thermodynamics, chemical kinetics, and transport. 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

» More about Bryan


Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are

MATLAB tạo đối tượng Python

Aldren

MATLAB tạo đối tượng Python

Geir Arne

MATLAB tạo đối tượng Python

Joanna

Master Real-World Python Skills With Unlimited Access to Real Python

MATLAB tạo đối tượng Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas

Level Up Your Python Skills »

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

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas

Level Up Your Python Skills »

What Do You Think?

Rate this article

Tweet Share Share Email

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know

Commenting Tips. The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal

Can MATLAB generate Python code?

You can add MATLAB files to the project to generate sample Python driver files . Although Python driver files are not necessary to create a package, you can use them to implement a Python application, as shown in Install and Run MATLAB Generated Python Application.

How does MATLAB integrate with Python?

To integrate a MATLAB® Compiler SDK™ Python® Package. .
In consultation with the MATLAB programmer, collect the MATLAB function signatures that comprise the services in the application
Install and import the compiled Python package. .
Write the Python code to initialize MATLAB Runtime and load the MATLAB code

Does MATLAB have dictionary?

Use dictionaries to store key-value pairs of different data types . Modify custom classes for expected behavior in dictionaries.