Mã matlab có hoạt động trong python không?

MATLAB® được biết đến rộng rãi như một môi trường chất lượng cao cho mọi công việc liên quan đến mảng, ma trận hoặc đại số tuyến tính. Python mới hơn trong lĩnh vực này nhưng ngày càng trở nên phổ biến cho các nhiệm vụ tương tự. Như bạn sẽ thấy trong bài viết này, Python có tất cả sức mạnh tính toán của MATLAB cho các nhiệm vụ khoa học và giúp phát triển các ứng dụng mạnh mẽ một cách nhanh chóng và dễ dàng. 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
  • Tránh các vấn đề phổ biến mà bạn có thể gặp phải khi chuyển từ MATLAB sang Python
  • 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

Ngoài ra còn có một sự khác biệt triết học quan trọng trong so sánh MATLAB với Python. MATLAB 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. If Mathworks were ever to go out of business, then MATLAB would no longer be able to be developed and might eventually stop functioning

On the other hand, Python is free and open-source software. Not only can you download Python at no cost, but you can also download, look at, and modify the source code as well. This is a big advantage for Python because it means that anyone can pick up the development of the language if the current developers were unable to continue for some reason

If you’re a researcher or scientist, then using open-source software has some pretty big benefits. Paul Romer, the 2018 Nobel Laureate in Economics, is a recent convert to Python. By his estimation, switching to open-source software in general, and Python in particular, brought greater integrity and accountability to his research. This was because all of the code could be shared and run by any interested reader. Prof. Romer wrote an excellent article, Jupyter, Mathematica, and the Future of the Research Paper, about his experience with open-source software

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. As you’ll see a little later on in the article, Python has an awesome community that can help you get started with the language and advance your knowledge. 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

  • Introduction to Python 3
  • Basic Data Types in Python
  • Lộ trình học Python 3 cơ bản

Plus, with so many developers in the community, there are hundreds of thousands of free packages to accomplish many of the tasks that you’ll want to do with Python. You’ll learn more about how to get these packages later on in this article

Like MATLAB, Python is an interpreted language. 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 cũng có thể nói chuyện với các bộ vi điều khiển khác như Arduino với giao diện lập trình đơn giản gần như giống hệt nhau bất kể hệ điều hành máy chủ là gì

For all of these reasons, and many more, Python is an excellent choice to replace MATLAB as your programming language of choice. Bây giờ bạn đã bị thuyết phục để dùng thử Python, hãy đọc tiếp để tìm hiểu cách tải nó trên máy tính của bạn và cách chuyển đổi từ MATLAB

Note. GNU Octave is a free and open-source clone of MATLAB. Theo nghĩa này, GNU Octave có cùng những lợi thế triết học mà Python có xung quanh khả năng tái tạo mã và quyền truy cập vào phần mềm

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

Thiết lập môi trường của bạn cho 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. Trăn 2 và Trăn 3. Bạn chắc chắn nên cài đặt phiên bản Anaconda cho Python 3, vì Python 2 sẽ không được hỗ trợ sau ngày 1 tháng 1 năm 2020. Trăn 3. 7 là phiên bản mới nhất tại thời điểm viết bài này, nhưng Python 3. 8 sẽ ra mắt vài tháng sau khi bài viết này được xuất bản. Either 3. 7 or 3. 8 will work the same for you, so choose the most recent version you can

Khi bạn đã tải xuống trình cài đặt Anaconda, bạn có thể làm theo các quy trình thiết lập mặc định tùy thuộc vào nền tảng của bạn. 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

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. Đây được gọi là Dấu nhắc Anaconda và nó là dấu nhắc lệnh được thiết lập riêng để hoạt động với

In [2]: import antigravity
32 trên 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 hoặc iTerm2 để truy cập

In [2]: import antigravity
32 từ dòng lệnh. 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ữ. You may be a little bit confused about

In [2]: import antigravity
32 versus Anaconda. The distinction is subtle but important. Anaconda is a distribution of Python that includes many of the necessary packages for scientific work of all kinds.
In [2]: import antigravity
32 is a cross-platform package management software that is included with the Anaconda distribution of Python.
In [2]: import antigravity
32 is the software that you use to build, install, and remove packages within the Anaconda distribution

You can read all about how to use

In [2]: import antigravity
32 in Setting Up Python for Machine Learning on Windows. Although that tutorial focuses on Windows, the
In [2]: import antigravity
32 commands are the same on Windows, macOS, and Linux

Python also includes another way to install packages, called

In [2]: import antigravity
40. If you’re using Anaconda, you should always prefer to install packages using
In [2]: import antigravity
32 whenever possible. Sometimes, though, a package is only available with
In [2]: import antigravity
40, and for those cases, you can read What Is Pip? A Guide for New Pythonistas

Getting an Integrated Development Environment

One of the big advantages of MATLAB is that it includes a development environment with the software. Đây là cửa sổ mà bạn thường làm việc nhất. There is a console in the center where you can type commands, a variable explorer on the right, and a directory listing on the left

Unlike MATLAB, Python itself does not have a default development environment. It is up to each user to find one that fits their needs. Fortunately, Anaconda comes with two different integrated development environments [IDEs] that are similar to the MATLAB IDE to make your switch seamless. These are called Spyder and JupyterLab. In the next two sections, you’ll see a detailed introduction to Spyder and a brief overview of JupyterLab

Spyder

Spyder is an IDE for Python that is developed specifically for scientific Python work. One of the really nice things about Spyder is that it has a mode specifically designed for people like you who are converting from MATLAB to Python. You’ll see that a little later on

First, you should open Spyder. If you followed the instructions in the previous section, you can open Spyder using the Anaconda Navigator. Just find the Spyder icon and click the Launch button. You can also launch Spyder from the Start Menu if you’re using Windows or from Launchpad if you’re using macOS

Changing the Default Window Layout in Spyder

The default window in Spyder looks like the image below. This is for version 3. 3. 4 of Spyder running on Windows 10. It should look quite similar on macOS or Linux

Before you take a tour of the user interface, you can make the interface look a little more like MATLAB. In the View → Window layouts menu choose MATLAB layout. That will change the window automatically so it has the same areas that you’re used to from MATLAB, annotated on the figure below

Ở trên cùng bên trái của cửa sổ là File Explorer hoặc danh sách thư mục. In this pane, you can find files that you want to edit or create new files and folders to work with

In the top center is a file editor. In this editor, you can work on Python scripts that you want to save to re-run later on. By default, the editor opens a file called

In [2]: import antigravity
43 located in Spyder’s configuration directory. 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ể tách 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. Bạn cũng có thể đặt lại về một trong các cấu hình mặc định từ menu này

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]. Hãy xác định một số biến và thực hiện một số phép tính cơ bản ngay bây giờ. 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. Sau đó, bạn đã hiển thị giá trị của biến
In [2]: import antigravity
53 bằng cách viết nó như một thứ duy nhất trên dòng đầu vào. Đầ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. Trên các dòng đầu vào 3, 4 và 5, Trình khám phá biến ở ngăn trên cùng bên phải được cập nhật

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

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

Chạy mã trong tệp trong Spyder

Điểm dừng cuối cùng trong chuyến tham quan ngắn của chúng tôi về giao diện Spyder là khung Trình chỉnh sửa tệp. Trong ngăn này, bạn có thể tạo và chỉnh sửa tập lệnh Python và chạy chúng bằng bảng điều khiển. Theo mặc định, Spyder tạo một tệp tạm thời có tên là

In [2]: import antigravity
43 nhằm mục đích để bạn lưu trữ tạm thời các lệnh khi bạn đang làm việc trước khi di chuyển hoặc lưu chúng vào một tệp khác

Hãy viết một số mã vào tệp

In [2]: import antigravity
43 và xem cách chạy nó. Tệp bắt đầu bằng đoạn mã sau, bạn có thể để nguyên đoạn mã này

In [2]: import antigravity
2

Trong mã này, bạn có thể thấy hai cấu trúc cú pháp Python

  • Dòng 1 có chú thích. Trong Python, ký tự nhận xét là dấu thăng hoặc dấu thăng [

    In [2]: import antigravity
    
    71]. MATLAB sử dụng ký hiệu phần trăm [
    In [2]: import antigravity
    
    72] làm ký tự nhận xét. Bất cứ điều gì theo sau hàm băm trên dòng là một nhận xét và thường bị trình thông dịch Python bỏ qua

  • Bắt đầu từ dòng 2 là một chuỗi cung cấp một số ngữ cảnh cho nội dung của tệp. Điều này thường được gọi là chuỗi tài liệu hoặc chuỗi tài liệu cho ngắn. Bạn sẽ tìm hiểu thêm về docstrings trong phần sau

Bây giờ bạn có thể bắt đầu thêm mã vào tệp này. Bắt đầu từ dòng 8 trong

In [2]: import antigravity
43, hãy nhập mã sau giống với mã bạn đã nhập trong bảng điều khiển

In [2]: import antigravity
6

Sau đó, có ba cách để chạy mã

  1. Bạn có thể sử dụng phím tắt F5 để chạy tệp giống như trong MATLAB.
  2. Bạn có thể nhấp vào hình tam giác hướng bên phải màu xanh lá cây trong thanh menu ngay phía trên khung Trình chỉnh sửa và Trình khám phá tệp
  3. Bạn có thể sử dụng tùy chọn menu Run → Run

Lần đầu tiên bạn chạy một tệp, Spyder sẽ mở một cửa sổ hộp thoại yêu cầu bạn xác nhận các tùy chọn bạn muốn sử dụng. Đối với thử nghiệm này, các tùy chọn mặc định đều ổn và bạn có thể nhấp vào Chạy ở cuối hộp thoại

Điều này sẽ tự động thực thi đoạn mã sau trong bảng điều khiển

>>>

In [2]: import antigravity
7

Mã này sẽ chạy tệp mà bạn đang làm việc. Lưu ý rằng việc chạy tệp đã thêm ba biến vào Trình khám phá biến.

In [2]: import antigravity
74,
In [2]: import antigravity
75 và
In [2]: import antigravity
76. Đây là ba biến mà bạn đã xác định trong tệp. Bạn cũng sẽ thấy
In [2]: import antigravity
77 được thêm vào nhật ký Lịch sử

Trong Spyder, bạn cũng có thể tạo các ô mã có thể chạy riêng lẻ. Để tạo một ô mã, hãy thêm một dòng bắt đầu bằng

In [2]: import antigravity
78 vào tệp đang mở trong trình chỉnh sửa

In [2]: import antigravity
3

Trong mã này, bạn đã tạo ô mã đầu tiên của mình trên dòng 11 với mã

In [2]: import antigravity
78. Phần tiếp theo là một dòng nhận xét và bị Python bỏ qua. Ở dòng 12, bạn đang gán
In [2]: import antigravity
80 có giá trị 42 và sau đó dòng 13 gán
In [2]: import antigravity
81 là
In [2]: import antigravity
80 nhân hai. Dòng 15 bắt đầu một ô mã khác có thể được thực thi tách biệt với ô đầu tiên

Để thực thi các ô mã, nhấp vào Chạy ô hiện tại hoặc Chạy ô hiện tại và chuyển đến các nút Tiếp theo bên cạnh nút Chạy chung trên thanh công cụ. Bạn cũng có thể sử dụng phím tắt Ctrl + Enter để chạy hiện tại . Shift+Enter to run the current cell and select the next cell.

Spyder cũng cung cấp các tính năng sửa lỗi dễ sử dụng, giống như trong MATLAB. Bạn có thể nhấp đúp vào bất kỳ số dòng nào trong Trình chỉnh sửa để đặt điểm dừng trong mã của mình. Bạn có thể chạy mã ở chế độ gỡ lỗi bằng cách sử dụng tam giác hướng về bên phải màu xanh với hai đường kẻ dọc từ thanh công cụ hoặc 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.

Tóm tắt kinh nghiệm của bạn trong Spyder

Bây giờ bạn đã có các công cụ cơ bản để sử dụng Spyder thay thế cho môi trường phát triển tích hợp MATLAB. Bạn biết cách chạy code trong console hay gõ code vào file và chạy file. Bạn cũng biết nơi cần tìm để xem các thư mục và tệp của mình, các biến bạn đã xác định và lịch sử của các lệnh bạn đã nhập

Khi bạn đã sẵn sàng bắt đầu tổ chức mã của mình thành các mô-đun và gói, bạn có thể xem các tài nguyên sau

  • Các mô-đun và gói Python – Giới thiệu
  • Cách xuất bản Gói Python mã nguồn mở lên PyPI
  • Cách xuất bản gói Python của riêng bạn lên PyPI

Spyder là một phần mềm thực sự lớn và bạn chỉ mới làm xước bề mặt. Bạn có thể tìm hiểu thêm về Spyder bằng cách đọc tài liệu chính thức, hướng dẫn khắc phục sự cố và câu hỏi thường gặp cũng như Spyder wiki

Remove ads

JupyterLab

JupyterLab là một IDE được phát triển bởi Project Jupyter. Bạn có thể đã nghe nói về Jupyter Notebooks, đặc biệt nếu bạn là nhà khoa học dữ liệu. Chà, JupyterLab là phiên bản tiếp theo của Jupyter Notebook. Mặc dù tại thời điểm viết bài này, JupyterLab vẫn đang trong giai đoạn thử nghiệm, Project Jupyter hy vọng rằng JupyterLab cuối cùng sẽ thay thế giao diện máy chủ Notebook hiện tại. Tuy nhiên, JupyterLab hoàn toàn tương thích với Notebook hiện có nên quá trình chuyển đổi sẽ khá liền mạch

JupyterLab được cài đặt sẵn Anaconda, vì vậy bạn có thể khởi chạy nó từ Anaconda Navigator. Tìm hộp JupyterLab và nhấp vào Khởi chạy. Điều này sẽ mở trình duyệt web của bạn đến địa chỉ

In [2]: import antigravity
85

Cửa sổ JupyterLab chính được hiển thị trong hình bên dưới

Có hai phần chính của giao diện

  1. Ở bên trái là Trình khám phá tệp cho phép bạn mở tệp từ máy tính của mình
  2. Ở phía bên phải của cửa sổ là cách bạn có thể mở, tạo tệp Notebook mới, làm việc trong bảng điều khiển IPython hoặc thiết bị đầu cuối hệ thống hoặc tạo tệp văn bản mới

Nếu bạn muốn tìm hiểu thêm về JupyterLab, bạn có thể đọc thêm về sự phát triển tiếp theo của Notebook trong bài đăng trên blog thông báo về bản phát hành beta hoặc trong tài liệu về JupyterLab. Bạn cũng có thể tìm hiểu về giao diện Notebook trong Jupyter Notebook. Giới thiệu và khóa học Sử dụng Notebook Jupyter. Một điều thú vị về tài liệu kiểu Jupyter Notebook là các ô mã bạn đã tạo trong Spyder rất giống với các ô mã trong Jupyter Notebook

Tìm hiểu về thư viện toán học của Python

Bây giờ bạn đã có Python trên máy tính của mình và bạn đã có một IDE mà bạn cảm thấy như ở nhà. 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. With NumPy arrays, you can do things like inner and outer products, transposition, and element-wise operations. 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

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

Note

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

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

Remove ads

SciPy [Scientific Python]

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

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

Matplotlib [MATLAB-like Plotting Library]

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

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

Note

Here are some more resources on Matplotlib

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

Other Important Python Libraries

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

  • Pandas cung cấp DataFrame, một mảng có khả năng đặt tên cho các hàng và cột để dễ dàng truy cập
  • 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 cung cấp một thư viện đơn vị để tiến hành chuyển đổi tự động giữa các hệ thống đơn vị vật lý
  • 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

Sự khác biệt kỹ thuật lớn nhất giữa MATLAB và Python là trong MATLAB, mọi thứ được coi là một mảng, trong khi trong Python, mọi thứ là một đối tượng tổng quát hơn. For instance, in MATLAB, strings are arrays of characters or arrays of strings, while in Python, strings have their own type of object called

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

Với cách đó, chúng ta hãy bắt đầu. Để giúp bạn, các phần bên dưới được sắp xếp thành các nhóm dựa trên khả năng bạn gặp phải cú pháp đó như thế nào

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]. Điều này cho phép chuỗi tài liệu chạy trên nhiều dòng với khoảng trắng và dòng mới được giữ nguyên. Ba ký tự trích dẫn là trường hợp đặc biệt của chuỗi ký tự. Đừng quá lo lắng về cú pháp định nghĩa hàm. Bạn sẽ thấy nhiều hơn về điều đó trong phần sau

Khoảng trắng ở đầu dòng có ý nghĩa quan trọng trong Python

Khi bạn viết mã trong MATLAB, các khối như câu lệnh

In [2]: import antigravity
96, vòng lặp
In [2]: import antigravity
97 và
In [2]: import antigravity
98 và định nghĩa hàm được kết thúc bằng từ khóa
In [2]: import antigravity
99. Nó thường được coi là một cách thực hành tốt trong MATLAB để thụt lề mã trong các khối để mã được nhóm lại với nhau một cách trực quan, nhưng nó không cần thiết về mặt cú pháp

Ví dụ: hai khối mã sau đây có chức năng tương đương trong MATLAB

In [2]: import antigravity
0

Trong mã này, trước tiên bạn tạo

In [2]: import antigravity
100 để lưu trữ giá trị 10 và sau đó kiểm tra xem giá trị của
In [2]: import antigravity
100 có bằng 10 không. Nếu đúng như vậy, bạn đang hiển thị cụm từ
In [2]: import antigravity
102 trên bảng điều khiển từ dòng 2. Nếu không, mệnh đề
In [2]: import antigravity
103 sẽ khởi động và hiển thị
In [2]: import antigravity
104. Tất nhiên, nếu bạn chạy mã này, bạn sẽ thấy đầu ra
In [2]: import antigravity
102 và sau đó là
In [2]: import antigravity
106

Bây giờ bạn nên sửa đổi mã của mình để nó trông giống như mẫu bên dưới

In [2]: import antigravity
1

Trong đoạn mã này, bạn chỉ thay đổi dòng 3 và 5 bằng cách thêm một số dấu cách hoặc thụt vào đầu dòng. Mã này sẽ hoạt động giống hệt với mã ví dụ trước, nhưng với việc thụt đầu dòng, sẽ dễ dàng hơn nhiều để biết mã nào nằm trong phần

In [2]: import antigravity
96 của câu lệnh và mã nào nằm trong phần
In [2]: import antigravity
103 của câu lệnh

Trong Python, thụt đầu dòng ở đầu dòng được sử dụng để phân định phần đầu và phần cuối của lớp và định nghĩa hàm, câu lệnh

In [2]: import antigravity
96 và vòng lặp
In [2]: import antigravity
97 và
In [2]: import antigravity
98. Không có từ khóa
In [2]: import antigravity
99 trong Python. Điều này có nghĩa là thụt đầu dòng rất quan trọng trong Python

Ngoài ra, trong Python, dòng định nghĩa của câu lệnh

In [2]: import antigravity
113, vòng lặp
In [2]: import antigravity
97 hoặc
In [2]: import antigravity
98, hàm hoặc lớp được kết thúc bằng dấu hai chấm. Trong MATLAB, dấu hai chấm không được dùng để kết thúc dòng

Xem xét ví dụ mã này

In [2]: import antigravity
2

Ở dòng đầu tiên, bạn đang xác định

In [2]: import antigravity
100 và đặt giá trị của nó là 10. Ở dòng 2, viết
In [2]: import antigravity
117 kiểm tra giá trị của
In [2]: import antigravity
100 so với 10. Chú ý dấu hai chấm ở cuối dòng

Tiếp theo, dòng 3 phải được thụt vào theo cú pháp của Python. Trên dòng đó, bạn đang sử dụng

In [2]: import antigravity
119 để hiển thị một số đầu ra cho bảng điều khiển, theo cách tương tự như
In [2]: import antigravity
120 trong MATLAB. Bạn sẽ đọc thêm về
In [2]: import antigravity
119 so với
In [2]: import antigravity
120 trong phần sau

Ở dòng 4, bạn đang bắt đầu khối

In [2]: import antigravity
103. Lưu ý rằng
In [2]: import antigravity
124 trong từ khóa
In [2]: import antigravity
103 được căn chỉnh theo chiều dọc với
In [2]: import antigravity
126 trong từ khóa
In [2]: import antigravity
96 và dòng được kết thúc bằng dấu hai chấm. Vì
In [2]: import antigravity
103 bị làm lệch so với
In [2]: import antigravity
119 trên dòng 3 và vì nó được căn chỉnh với từ khóa
In [2]: import antigravity
96, nên Python biết rằng mã trong phần
In [2]: import antigravity
96 của khối đã kết thúc và phần
In [2]: import antigravity
103 đang bắt đầu. Dòng 5 được thụt vào một cấp, do đó, nó tạo thành khối mã được thực thi khi câu lệnh
In [2]: import antigravity
103 được thỏa mãn

Cuối cùng, ở dòng 6, bạn đang in một câu lệnh từ bên ngoài khối

In [2]: import antigravity
96/
In [2]: import antigravity
103. Tuyên bố này sẽ được in bất kể giá trị của
In [2]: import antigravity
100. Lưu ý rằng
In [2]: import antigravity
137 trong
In [2]: import antigravity
119 được căn chỉnh theo chiều dọc với
In [2]: import antigravity
126 trong
In [2]: import antigravity
96 và
In [2]: import antigravity
124 trong
In [2]: import antigravity
103. Đây là cách Python biết rằng mã trong khối
In [2]: import antigravity
96/
In [2]: import antigravity
103 đã kết thúc. Nếu bạn chạy đoạn mã trên, Python sẽ hiển thị
In [2]: import antigravity
102 theo sau là
In [2]: import antigravity
106

Bây giờ bạn nên sửa đổi mã ở trên để xóa thụt đầu dòng và xem điều gì sẽ xảy ra. Nếu bạn cố nhập mã mà không thụt đầu dòng vào bảng điều khiển Spyder/IPython, bạn sẽ nhận được thông báo

In [2]: import antigravity
147

>>>

In [2]: import antigravity
3

Trong mã này, trước tiên bạn đặt giá trị của

In [2]: import antigravity
100 thành 10, sau đó thử viết câu lệnh
In [2]: import antigravity
96 mà không cần thụt đầu dòng. Trên thực tế, bảng điều khiển IPython rất thông minh và tự động thụt lề dòng sau câu lệnh
In [2]: import antigravity
96 cho bạn, vì vậy bạn sẽ phải xóa phần thụt lề để tạo ra lỗi này

Khi bạn thụt lề mã của mình, hướng dẫn phong cách chính thức của Python có tên là PEP 8 khuyên bạn nên sử dụng 4 ký tự khoảng trắng để biểu thị một cấp độ thụt lề. Hầu hết các trình soạn thảo văn bản được thiết lập để hoạt động với tệp Python sẽ tự động chèn 4 dấu cách nếu bạn nhấn phím Tab trên bàn phím. Bạn có thể chọn sử dụng ký tự tab cho mã của mình nếu muốn, nhưng bạn không nên trộn lẫn các tab và dấu cách, nếu không bạn có thể sẽ nhận được một ________ 2151 nếu thụt lề không khớp.

Câu lệnh có điều kiện Sử dụng
In [2]: import antigravity
152 trong Python

Trong MATLAB, bạn có thể xây dựng câu lệnh điều kiện với

In [2]: import antigravity
96,
In [2]: import antigravity
154 và
In [2]: import antigravity
103. Các loại câu lệnh này cho phép bạn kiểm soát luồng chương trình của mình để đáp ứng các điều kiện khác nhau

Bạn nên thử ý tưởng này với mã bên dưới, sau đó so sánh ví dụ về MATLAB với Python để biết các câu lệnh có điều kiện

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. Thay vào đó, khối
In [2]: import antigravity
96 kết thúc khi tìm thấy dòng mã được xác định tiếp theo sau
In [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

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

In [2]: import antigravity
171, using the round brackets as the indexing operator. On the third input line, you are calling
In [2]: import antigravity
172 and using the round brackets to indicate the parameters that should be passed into
In [2]: import antigravity
172, in this case just
In [2]: import antigravity
174. MATLAB computes the sum of the elements in
In [2]: import antigravity
174 and returns that result

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

>>>

In [2]: import antigravity
7

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

On the input line 2, you are displaying the value of the first element of the list with the indexing operation using square brackets. On input line 3, you are calling

In [2]: import antigravity
172 using round brackets and passing in the list stored in
In [2]: import antigravity
174. This results in the sum of the list elements being displayed on the last line. 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

The First Index in a Sequence Is 0 in Python

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

In [2]: import antigravity
178 as the index. This style follows the natural numbering convention and starts how you would count the number of items in the sequence. You can try out the differences of MATLAB vs Python with this example

>>>

In [2]: import antigravity
8

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

In [2]: import antigravity
179,
In [2]: import antigravity
180, and
In [2]: import antigravity
181. Then you are displaying the value of the first element with the index
In [2]: import antigravity
178, which is
In [2]: import antigravity
179. Trying to access the zeroth element results in an error in MATLAB, as shown on the last two lines

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

>>>

In [2]: import antigravity
9

In this code, you are defining

In [2]: import antigravity
174 as a Python list with three elements on input line 1. On input line 2, you are displaying the value of the first element of the list, which has the index 0. Then you are displaying the second element of the list, which has the index 1

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

In [2]: import antigravity
185 with the contents
In [2]: import antigravity
186 and then getting the first and second elements of the string. Notice that the second element [character] of the string is a space. This demonstrates a general Python feature, that many variable types operate as sequences and can be indexed, including lists, tuples, strings, and arrays

The Last Element of a Sequence Has Index
In [2]: import antigravity
187 in Python

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

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

Try out the differences in MATLAB vs Python with this example

>>>

In [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

Trong mã này, bạn đang truy xuất các phần tử từ thứ hai đến cuối cùng và từ thứ ba đến cuối cùng từ danh sách, có giá trị lần lượt là

In [2]: import antigravity
180 và
In [2]: import antigravity
179

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

Trong Python, bạn sử dụng hai dấu hoa thị [

In [2]: import antigravity
198] khi bạn muốn nâng một số lên lũy thừa

>>>

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. Lưu ý rằng không có tác dụng bao gồm khoảng trắng ở hai bên của dấu hoa thị. 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

Trong MATLAB, bạn có thể lấy độ dài của một mảng bằng

In [2]: import antigravity
206. Hàm này lấy một mảng làm đối số và trả về kích thước của thứ nguyên lớn nhất trong mảng. Bạn có thể thấy những điều cơ bản của chức năng này với ví dụ này

>>>

In [2]: import antigravity
15

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

In [2]: import antigravity
206 trả về câu trả lời là 3. Trên dòng đầu vào thứ hai, bạn đang tìm độ dài của mảng chuỗi chứa một phần tử. Lưu ý rằng MATLAB ngầm tạo một mảng chuỗi, mặc dù bạn không sử dụng dấu ngoặc vuông để chỉ ra đó là một mảng

Trong Python, bạn có thể lấy độ dài của một chuỗi bằng

In [2]: import antigravity
205

>>>

In [2]: import antigravity
16

Trong mã này, trên dòng đầu vào 1, bạn đang tìm độ dài của danh sách có 3 phần tử. Như mong đợi,

In [2]: import antigravity
205 trả về độ dài 3. Trên dòng đầu vào 2, bạn đang tìm độ dài của chuỗi làm đầu vào. Trong Python, các chuỗi là các chuỗi và
In [2]: import antigravity
205 đếm số ký tự trong chuỗi. Trong trường hợp này,
In [2]: import antigravity
211 có 8 ký tự

Đầu ra của bàn điều khiển được hiển thị với
In [2]: import antigravity
119 trong Python

Trong MATLAB, bạn có thể sử dụng

In [2]: import antigravity
120,
In [2]: import antigravity
214 và
In [2]: import antigravity
215 để in giá trị của các biến và đầu ra khác ra bàn điều khiển. Trong Python,
In [2]: import antigravity
119 có chức năng tương tự như
In [2]: import antigravity
120. Không giống như
In [2]: import antigravity
120,
In [2]: import antigravity
119 có thể gửi đầu ra của nó tới một tệp tương tự như
In [2]: import antigravity
214

In [2]: import antigravity
119 của Python sẽ hiển thị bất kỳ số lượng đối số nào được truyền cho nó, phân tách chúng bằng khoảng trắng ở đầu ra. Điều này khác với
In [2]: import antigravity
120 trong MATLAB, chỉ nhận một đối số, mặc dù đối số đó có thể là một mảng có nhiều giá trị. Ví dụ sau đây cho thấy cách
In [2]: import antigravity
119 của Python có thể nhận bất kỳ số lượng đối số nào và mỗi đối số được phân tách bằng khoảng trắng ở đầu ra

>>>

In [2]: import antigravity
17

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

In [2]: import antigravity
224,
In [2]: import antigravity
225 và
In [2]: import antigravity
226, trong đó
In [2]: import antigravity
224 và
In [2]: import antigravity
224 là số nguyên và
In [2]: import antigravity
226 là chuỗi văn bản. Trên dòng đầu vào 4, bạn đang in ba biến bằng cách sử dụng
In [2]: import antigravity
119. Đầu ra bên dưới dòng này, giá trị của ba biến được hiển thị trong đầu ra của bàn điều khiển, được phân tách bằng dấu cách

Bạn có thể kiểm soát dấu tách được sử dụng trong đầu ra giữa các đối số thành

In [2]: import antigravity
119 bằng cách sử dụng đối số từ khóa
In [2]: import antigravity
232

>>>

In [2]: import antigravity
18

Trong mã này, bạn đang in ba biến giống nhau nhưng đặt dấu phân cách thành dấu chấm phẩy theo sau là khoảng trắng. 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. Để kiểm soát ký tự được in sau giá trị cuối cùng, bạn có thể sử dụng đối số từ khóa

In [2]: import antigravity
99 thành
In [2]: import antigravity
119

>>>

In [2]: import antigravity
19

Trong đoạn mã này, bạn đã thêm đối số từ khóa

In [2]: import antigravity
99 vào
In [2]: import antigravity
119, đặt nó để in dấu chấm phẩy sau giá trị cuối cùng. Điều này được thể hiện trong đầu ra trên dòng bên dưới đầu vào

Giống như

In [2]: import antigravity
120 từ MATLAB,
In [2]: import antigravity
119 không thể trực tiếp kiểm soát định dạng đầu ra của các biến và dựa vào bạn để thực hiện định dạng. Nếu bạn muốn kiểm soát nhiều hơn định dạng của đầu ra, bạn nên sử dụng f-strings hoặc
In [2]: import antigravity
239. Trong các chuỗi này, bạn có thể sử dụng các mã kiểu định dạng rất giống như
In [2]: import antigravity
214 trong MATLAB để định dạng số

>>>

In [2]: import antigravity
20

Trong mã này, dòng đầu vào 7 bao gồm một chuỗi f, được chỉ định bởi

In [2]: import antigravity
241 để bắt đầu chuỗi. Đ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. Những ví dụ này sử dụng một số tính năng trung gian trong Python nhưng vẫn là cốt lõi về cách thức hoạt động của Python. 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 bằng 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. Kiểm tra Trình khám phá biến và bạn sẽ thấy rằng
In [2]: import antigravity
262 có giá trị 30, như mong đợi. Lưu ý rằng tên
In [2]: import antigravity
262 không nhất thiết phải cù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. Bây giờ nếu bạn cố gán kết quả của việc gọi hàm này cho một biến, MATLAB sẽ báo lỗi trong bảng điều khiển

>>>

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

Một hàm tương đương trong Python với ví dụ

In [2]: import antigravity
263 đầu tiên của bạn với một biến đầu ra được hiển thị bên dưới

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 ở đó. Bạn có thể đơn giản hóa định nghĩa hàm trước đây của mình bằng cách loại bỏ
In [2]: import antigravity
250 và chỉ cần trả về giá trị của
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

Trên dòng mã này, bạn đang tạo định nghĩa hàm. 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. Bạn nên gõ mã này

>>>

In [2]: import antigravity
29

Trong mã này, trước tiên bạn tạo hai biến

In [2]: import antigravity
51 và
In [2]: import antigravity
52 lưu trữ các giá trị bạn muốn cộng lại với nhau. 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. Lưu mã trên vào một tệp có tên là

In [2]: import antigravity
622 và sau đó trên bảng điều khiển MATLAB, hãy thử phiên bản có hai đối số đầu vào

>>>

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. Nếu không, Python sẽ báo lỗi

>>>

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

In MATLAB, you can use

In [2]: import antigravity
614/
In [2]: import antigravity
615 blocks to execute code by checking the value of a variable for equality with some constants. This type of syntax is quite useful when you know you want to handle a few discrete cases. Try out a
In [2]: import antigravity
614/
In [2]: import antigravity
615 block with this example

In [2]: import antigravity
74

In this code, you start by defining

In [2]: import antigravity
100 and setting it equal to 10 and on the following lines you test the value of
In [2]: import antigravity
100. This code will result in the output
In [2]: import antigravity
676 being displayed on the console, since
In [2]: import antigravity
100 is equal to 10

This syntax is an interesting comparison of MATLAB vs Python because Python does not have a similar syntax. Instead, you should use an

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

In [2]: import antigravity
75

In this code, you start by defining

In [2]: import antigravity
100 and setting it equal to
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

Bạn cũng có thể cho Python biết nên sử dụng tên nào cho thư viện. 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. Since there is no equal sign with a variable name on the left, Python assigns the output from
In [2]: import antigravity
172 to the underscore [
In [2]: import antigravity
716], in addition to printing it on the output line. 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. This function is assigned to
In [2]: import antigravity
735. On the second input line,
In [2]: import antigravity
736 is executed and passed
In [2]: import antigravity
737 as the value. The result the string
In [2]: import antigravity
738 printed on the console

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. In these cases, it is often not necessary to assign the function definition to a variable

>>>

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. The first argument to
In [2]: import antigravity
739 must be a function, so this is a perfect place to use an anonymous function. Here, your anonymous function squares whatever the input value is. 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 uses the

In [2]: import antigravity
729 keyword to define anonymous functions. Other than this syntax difference, anonymous functions work the same way in Python as in MATLAB

>>>

In [2]: import antigravity
33

In this code, input line 1 defines the

In [2]: import antigravity
729 function with one parameter,
In [2]: import antigravity
733. You use
In [2]: import antigravity
119 within the function definition to show an f-string with the value of the input parameter. The function is then stored in
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

However,

In [2]: import antigravity
729 functions are still useful when they are passed as arguments into another function

>>>

In [2]: import antigravity
34

In this code, input line 3 imports the

In [2]: import antigravity
754 library and stores it in the
In [2]: import antigravity
755 namespace. On input line 4, you are using
In [2]: import antigravity
756 from
In [2]: import antigravity
754 to compute the integral using quadrature, very similar to
In [2]: import antigravity
739 in MATLAB. The first argument to
In [2]: import antigravity
756 is the function to be integrated, and you use a
In [2]: import antigravity
729 function to specify that
In [2]: import antigravity
761 should be integrated. The second and third arguments to
In [2]: import antigravity
756 specify that the integral should be conducted from 0 to 9

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

In [2]: import antigravity
763 and
In [2]: import antigravity
764. The first value is the result of the integration, and is equal to the result from MATLAB. The second value is an estimate of the absolute error in the result. An error this small is approximately the precision of the numbers used to store the result, so the answer is about as accurate as it can be

You can read more about

In [2]: import antigravity
729 in How to Use Python lambda Functions or watch the videos in the How to Use Python Lambda Functions course

Remove ads

You Will Only Need These in Specialized Situations

In this section, the examples are more advanced concepts that you will need as you become more advanced in Python development. 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. When you see these concepts in other code, you can dig in to them when you feel comfortable

Class Definitions Start With
In [2]: import antigravity
766 in Python

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

In [2]: import antigravity
767 keyword to define the properties and methods that belong to the class

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

In [2]: import antigravity
730 and has the same name as the class. In that folder, you can create a single file that has the same name as the class. The function definition in that file will be used as the class initializer, and it should call
In [2]: import antigravity
769 to instantiate the class. Methods of the class can be defined in other files in the same folder, where the name of each file must be the same as the name of the method

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

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

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

In [2]: import antigravity
766 keyword, followed by the name of the class and a colon. Underneath this line, all of the code that is part of the class definition [methods and attributes] must be indented. Once a line of code starts in the same column as the
In [2]: import antigravity
772 in
In [2]: import antigravity
766, the class definition will be ended

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

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

In [2]: import antigravity
36

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

There Are No Private Properties or Methods in Python

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

In [2]: import antigravity
775 options

  • In [2]: import antigravity
    
    776. Access to the property or method is unrestricted
  • In [2]: import antigravity
    
    777. Access to the property or method is only allowed in this class or subclasses
  • In [2]: import antigravity
    
    778. Access to the property or method is only allowed in this class
  • In [2]: import antigravity
    
    779 hoặc
    In [2]: import antigravity
    
    780. Access to the property or method is only allowed in the listed class or classes

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

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ư. All classes and class instances can have their attributes and methods changed at runtime. 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. However, this convention is not enforced by any checks in the language and all attributes and methods can be modified by the user at runtime

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. This is because Spyder and other tools respect the convention that underscore indicates something should be non-public. 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ư. This will also show other non-public variables as well

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. The most commonly used dunder method is
In [2]: import antigravity
783, which is the class initializer or constructor. You can read a lot more about dunder methods in Enriching Your Python Classes With Dunder [Magic, Special] Methods

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

A Class Refers to Itself as
In [2]: import antigravity
784 in Python

MATLAB uses the name

In [2]: import antigravity
785 when a class wants to refer to the current instance of itself. The
In [2]: import antigravity
785 should be the first argument passed to an ordinary method. MATLAB also defines static methods that have no reference to the class instance

Python uses the name

In [2]: import antigravity
784 when a class wants to refer to the current instance of itself, but this is actually only a convention. You can call the first argument to an instance method any name you want, but
In [2]: import antigravity
784 is the most common convention. 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. You can read more about instance, static, and class methods in Python’s Instance, Class, and Static Methods Demystified

There Is One String Type in Python

In MATLAB, strings of characters are stored in string arrays when you use double quotes [

In [2]: import antigravity
789] or in character arrays if you use single quotes [
In [2]: import antigravity
790]. If you use both single and double quotes in an array assignment, the array will be promoted to a string array

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

>>>

In [2]: import antigravity
37

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

In [2]: import antigravity
791 is not the same as in
In [2]: import antigravity
87, so MATLAB shows an error message that the dimensions are not consistent

On line 4, you successfully create a character array, and on the third input line you are checking the size of the array. Đầ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. In string arrays, each string occupies one column in the array and each row in a multidimensional array must have the same number of strings, although each string can have different length. This is shown in the example below

>>>

In [2]: import antigravity
38

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

On line 5, you successfully create a string array. Notice that even though the number of characters is different between

In [2]: import antigravity
791 and
In [2]: import antigravity
87, MATLAB is able to create the string array. On line 6 you are checking the size of the string array, which shows that there are 2 rows and 1 column, as expected

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

In [2]: import antigravity
91. You can create a string literal using single quotes [
In [2]: import antigravity
790] or double quotes [
In [2]: import antigravity
789], there is no difference between the two definitions. However, there are some good arguments to prefer double quotes when defining string literals in Python, which are well expressed by the Black code formatting library

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

In [2]: import antigravity
300] or triple-double-quotes [
In [2]: import antigravity
95]. This method of creating strings allows the strings to be defined across multiple lines with the newline characters retained. You can see an example of this in the section about comments and docstrings

You can read a lot more about defining strings in Basic Data Types in Python and Strings and Character Data in Python

You can generate similar data structures to the string arrays and character arrays in MATLAB using NumPy in 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

In this code, you are importing the NumPy library on input line 1 and assigning it to the

In [2]: import antigravity
695 abbreviation. On input line 2, you are creating a NumPy
In [2]: import antigravity
303 with 2 string elements,
In [2]: import antigravity
791 and
In [2]: import antigravity
87, and assigning the array to
In [2]: import antigravity
174

On input line 3, you are showing the value of

In [2]: import antigravity
174. The output from the third line shows that
In [2]: import antigravity
174 is storing an
In [2]: import antigravity
303 that has 2 elements,
In [2]: import antigravity
310 and
In [2]: import antigravity
311, as expected. Notice that although you defined the array with double-quote strings, Python is displaying them with single-quote strings. Remember that there is no difference between single and double quotes in Python

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

In [2]: import antigravity
312. The three characters here represent the aspects of how the strings are arranged in memory. The
In [2]: import antigravity
313 means that the byte order of the array is little endian. The
In [2]: import antigravity
314 means the string is of the Unicode type. Finally, the
In [2]: import antigravity
315 means the maximum length of an element is 6 characters. This was chosen as the length of the longest string in the input

Notice that the string

In [2]: import antigravity
791 only has 4 characters. In NumPy string dtype arrays, elements can have fewer than the maximum number of characters without problems, but assigning to elements with strings that are longer than the maximum length will truncate the input

>>>

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. Clearly, this string is longer than 6 characters, so it is truncated to only 6 when it is assigned,
In [2]: import antigravity
318. [The space counts as 1 character. ]

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

In [2]: import antigravity
319 dtype when you create the array

>>>

In [2]: import antigravity
01

In this code, you are creating a new array,

In [2]: import antigravity
320, with two elements again, but this time you specified the dtype to be
In [2]: import antigravity
319, which you confirmed by showing the output on the console. Now you should see how the
In [2]: import antigravity
319 dtype affects assigning long strings to an element

>>>

In [2]: import antigravity
02

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

In [2]: import antigravity
317. You can see from the output line that that string is stored as the first element of the array without truncation, because the dtype is
In [2]: import antigravity
319. The disadvantage of using the
In [2]: import antigravity
319 dtype is that it is usually much slower than the more specific
In [2]: import antigravity
314 dtype, because it has to create a a whole Python object for each element rather than just a NumPy-optimized Unicode object

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

>>>

In [2]: import antigravity
03

In this code, we are printing the shape of

In [2]: import antigravity
174 and
In [2]: import antigravity
320. Notice that they both have the same shape, two elements in a one-dimensional array. This is similar to the string array from MATLAB, where each string counts as one element in the array. 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. You’ll see more about differences in how MATLAB and NumPy compute the shape of arrays in a later section

Libraries Are Not Automatically Reloaded in Python

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

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

In [2]: import antigravity
687 it into a namespace. When Python imports a file or module, it only reads the code the first time it is imported. This saves quite a bit of time if you’re importing the same file several times. However, if you’re testing your code in the interactive console prompt as you work on it, Python will not pick up any changes if you
In [2]: import antigravity
687 it again

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

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

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. In IPython and Jupyter Notebooks, commands prefixed with the percent sign
In [2]: import antigravity
72 are magic commands. The
In [2]: import antigravity
332 extension defines the
In [2]: import antigravity
332 magic function, which you use on input line 2. You are passing the parameter
In [2]: import antigravity
338 to the
In [2]: import antigravity
332 magic function, which means that all modules should be reloaded every time a line of code is executed

Remove ads

An Overview of Basic Array Operations

As you have seen, Python does not include a high-speed library for arrays in its standard library. 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 functions as the de facto array and matrix library for Python

NumPy has two array-like types

  1. In [2]: import antigravity
    
    340, also known as
    In [2]: import antigravity
    
    341
  2. In [2]: import antigravity
    
    342

The main difference between these two types is that the

In [2]: import antigravity
343 can be any number of dimensions, while the
In [2]: import antigravity
344 is limited to exactly two dimensions. For
In [2]: import antigravity
343, all operations such as addition, subtraction, multiplication, exponentiation, and division operate element-wise. 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

When you’re converting from MATLAB, the

In [2]: import antigravity
344 type may seem more familiar. It offers similar behavior that you may be used to from MATLAB in terms of operation syntax. However, NumPy strongly recommends that you use the
In [2]: import antigravity
343 type because it is more flexible and because
In [2]: import antigravity
344 will eventually be removed

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

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

MATLAB, with its heritage as a matrix scripting language, assumes that all arithmetic operators will be operating on arrays. Therefore, MATLAB treats the multiplication of matrices or vectors as matrix multiplication. Hãy xem xét ví dụ này

>>>

In [2]: import antigravity
05

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

In [2]: import antigravity
350, and
In [2]: import antigravity
320. Then, you are attempting to multiply them together. For these 1xN arrays, this is equivalent to taking the dot or scalar product. However, the scalar product only works when the left operand is 1xN and the right is Nx1, so MATLAB produces an error message and suggests the dot-star operator [
In [2]: import antigravity
352] as the proper syntax for element-wise multiplication

>>>

In [2]: import antigravity
06

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

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

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

In [2]: import antigravity
320 to convert it to a 3x1 array

>>>

In [2]: import antigravity
07

In this code, you are performing matrix multiplication with

In [2]: import antigravity
350 and the transpose of
In [2]: import antigravity
320. Note that you can use either
In [2]: import antigravity
363 or the quote operator [
In [2]: import antigravity
790] to take the transpose of
In [2]: import antigravity
320. Since
In [2]: import antigravity
350 is 1x3 and
In [2]: import antigravity
367 is 3x1, this results in the scalar, or dot, product

With NumPy arrays, operations like multiplication with the asterisk [

In [2]: import antigravity
202] operate element-wise by default

>>>

In [2]: import antigravity
08

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

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. It starts with
In [2]: import antigravity
370, which should be read as “from within
In [2]: import antigravity
695, find
In [2]: import antigravity
372. ” Then, you have to pass a Python list or tuple to the array constructor that contains the elements of the array. In this case, you are passing a Python list, denoted by the square brackets

Finally, on input line 4, you are multiplying

In [2]: import antigravity
350 and
In [2]: import antigravity
320. Notice that the result on output line 4 is another array with the elements 4, 10, and 18, the same result as the element-wise multiplication in MATLAB

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

In [2]: import antigravity
730] added in Python 3. 5. You may see some older code also use
In [2]: import antigravity
376 from the NumPy library and pass the two arrays

>>>

In [2]: import antigravity
09

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

In [2]: import antigravity
350 and
In [2]: import antigravity
320. As expected, the result is 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. ” You can see that the result is identical

Notice that NumPy did not require you to transpose

In [2]: import antigravity
320 before performing the scalar product. You’ll learn more about this feature in the next section

Remove ads

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

As you saw in the last section, MATLAB insists that the dimensions of arrays align when performing matrix multiplication, while NumPy is a little bit more flexible. Điều này là do cách mảng một chiều được xử lý trong MATLAB so với trong NumPy

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

In [2]: import antigravity
385 of a single number

>>>

In [2]: import antigravity
10

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

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

In [2]: import antigravity
790] or
In [2]: import antigravity
363

>>>

In [2]: import antigravity
11

In this code, you are creating two vectors.

In [2]: import antigravity
350 and
In [2]: import antigravity
320. Arrays with values in one dimension only are called vectors.
In [2]: import antigravity
350 is a row vector because the elements are arranged in one row and three columns, whereas
In [2]: import antigravity
320 is a column vector because the elements are arranged in three rows and one column. 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

Then, you are checking the equality of the transpose of

In [2]: import antigravity
350 with
In [2]: import antigravity
320, and you find that all of the elements are equal and the result is a column vector of logical values. Cuối cùng, bạn đang kiểm tra sự bằng nhau của phép chuyển vị của
In [2]: import antigravity
320 với
In [2]: import antigravity
350 và bạn thấy rằng tất cả các phần tử đều bằng nhau và kết quả là một vectơ hàng của các giá trị logic

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

In NumPy, there are three types of one-dimensional arrays or vectors. Mặc định là một vectơ N phần tử chỉ có một chiều. This is different from the default in MATLAB, where every array has at least 2 dimensions. This one-dimensional vector in NumPy does not have a sense of rows and columns, since for a one-dimensional structure, it does not matter in general whether the elements are stored in rows or in columns, only how many elements there are

You can see an example of creating this kind of array in the following example. In the next few examples, there are extra spaces added before and after parentheses to clarify the syntax. 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

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

In [2]: import antigravity
695. On input line 2 you are creating the array and storing it in
In [2]: import antigravity
397. You are passing the list
In [2]: import antigravity
398 to
In [2]: import antigravity
372, where the list has 3 elements and none of the elements are themselves lists. This creates the 3-element array with only one dimension

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

In [2]: import antigravity
397 [an array], find the
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

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

In [2]: import antigravity
372 takes a flat list or a nested list as input. Using the flat list gets you a one-dimensional, N-element vector. By using the nested list, you can create arrays of any dimension that you want. A nested list means that there are one or more lists contained within an outer list. Here’s an example of a nested list

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. In terms of arrays, you can think of the number of elements of each inner list as the number of columns, and the number of nested lists is the number of rows. This is easier to see if you change the formatting

In [2]: import antigravity
14

This code is still valid Python syntax, but it emphasizes how the inner lists are each a row of the array, and the number of elements in each inner list is the number of columns. In this case, we would have an array with 2 rows and 3 columns. We can use these nested lists to create row-vectors and column-vectors in NumPy arrays

>>>

In [2]: import antigravity
15

In this code, you are creating a row array or vector by using a nested list. 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. On input line 5, you are displaying the shape of this array. As expected, the shape is

In [2]: import antigravity
008, or one row with three columns

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. Trên dòng đầu vào 7, bạn đang hiển thị hình dạng của mảng này. As expected, the shape is

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

Vì vectơ phần tử N chung không có ý nghĩa về hàng và cột, NumPy có thể định hình vectơ theo bất kỳ cách nào có ý nghĩa đối với thao tác đang được thực hiện. 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. Bạn có thể thực hiện phép chuyển vị bằng cách sử dụng thuộc tính

In [2]: import antigravity
011 hoặc
In [2]: import antigravity
012 của mảng

>>>

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. Lưu ý rằng hình dạng giống với hình dạng của bản gốc
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. Chẳng hạn, cố gắng lấy tích vô hướng của vectơ hàng sẽ dẫn đến lỗi

>>>

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]. Điều này được thể hiện trong dòng đầu ra tương ứng, trong đó các thành phần được sắp xếp để tạo thành một cột cho mục đích in. 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. Như được hiển thị trong hình, điều này tạo ra một mảng 3x3 với các phần tử từ 1 đến 9

Remove ads

Creating Arrays Is Very Flexible in NumPy

MATLAB và NumPy đều cho phép bạn chỉ định rõ ràng các phần tử cụ thể trong một mảng, như bạn đã thấy trong phần trước. 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. The NumPy project maintains a detailed list of the equivalent functions between MATLAB and NumPy

Many functions operate identically between MATLAB and NumPy. Điều này bao gồm các hàm thường được sử dụng như

In [2]: import antigravity
021 và
In [2]: import antigravity
022 để tạo dữ liệu cách đều nhau và
In [2]: import antigravity
023 và
In [2]: import antigravity
024 để tạo các mảng có hình dạng nhất định chứa đầy các số 1 và 0 tương ứng. 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

Trong MATLAB, bạn có thể sử dụng dấu hai chấm để tạo phạm vi đặc tả mảng. 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. Phương thức thứ hai bao gồm dấu hai chấm thứ hai, trong đó giá trị trước dấu hai chấm đầu tiên là điểm bắt đầu, giá trị ở giữa là bước và giá trị cuối cùng là điểm dừng

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. Bạn có thể thấy rằng khi bước này bị bỏ qua, nó sẽ mặc định có giá trị là 1. 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. Bước tiếp theo sẽ vượt quá giá trị dừng, vì vậy MATLAB không bao gồm giá trị dừng trong mảng. 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

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

In [2]: import antigravity
025, nó sẽ được hiểu là giá trị dừng. Giá trị bắt đầu mặc định là 0 và bước mặc định là 1. 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

Bạn có thể dùng thử

In [2]: import antigravity
025 với các ví dụ sau

>>>

In [2]: import antigravity
00

In this example, you are creating an array that contains the values from 1 to 6. Như trong MATLAB, nếu bước bị bỏ qua, nó sẽ mặc định là 1. Lưu ý rằng bạn phải chuyển giá trị dừng 7 để mảng dừng ở 6. However, the size of the resulting array is 7 - 1 = 6 elements long. Tiếp theo, bạn sẽ thấy cách thay đổi kích thước bước

>>>

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. Bước tiếp theo sẽ bằng giá trị dừng, nhưng NumPy không bao gồm giá trị dừng trong mảng. Lưu ý rằng công thức tính kích thước của mảng hơi khác một chút, vì kích thước bước không phải là 1

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. The next step would exceed the stop value, so NumPy stops at 6. Lưu ý rằng kích thước của mảng là [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. If you use floating point values [numbers with decimals], especially for the step, the elements may not come out exactly as you expect. If you want to use floating point numbers,
In [2]: import antigravity
021 is a better choice in general

Remove ads

The Colon Operator Is Very Powerful in 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. When indexing arrays, MATLAB supports the

In [2]: import antigravity
99 keyword to extend the specified range to the end of that dimension, as you saw earlier

>>>

In [2]: import antigravity
03

In this code, you are indexing

In [2]: import antigravity
350 starting at the second index and going to the end of the array. You can also specify a specific index as the stop value

>>>

In [2]: import antigravity
04

In this code, you are creating an array

In [2]: import antigravity
320 with the numbers 1 through 6, inclusive. Then, you are specifying the second element as the start value and the fourth element as the stop value in the slice. MATLAB 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

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

In [2]: import antigravity
320 bắt đầu từ giá trị cuối cùng, giảm dần 1 và kết thúc ở phần tử thứ 4. Finally, you can slice all of the element in a dimension by using just a bare colon

>>>

In [2]: import antigravity
07

Trong mã này, bạn đang chọn tất cả các chiều đầu tiên của mảng chỉ bằng cách sử dụng dấu hai chấm

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. Trong MATLAB, bạn phải chỉ định bắt đầu và dừng nếu bạn muốn chỉ định một trong hai. 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. Bạn đã thấy khi sử dụng

In [2]: import antigravity
025 rằng mảng không bao gồm giá trị dừng. 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]. Tuy nhiên, bạn đã chỉ định chỉ số dừng là 4 [phần tử thứ năm trong mảng, giá trị 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

Trong mã này, bạn đang cắt mảng bắt đầu từ phần tử thứ hai [chỉ số 1], đi đến cuối mảng và lấy mọi phần tử thứ hai. 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. Vì chỉ số bắt đầu không được chỉ định và bước là số âm, nên giá trị bắt đầu được coi là phần tử cuối cùng trong mảng [hoặc phần tử đầu tiên trong mảng đảo ngược]. 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. Điều này có nghĩa là khi bạn gán giá trị cho lát cắt, mảng ban đầu không bị ảnh hưởng. 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. Sau đó, bạn tạo một lát 2x2 của mảng ban đầu lưu trữ từ giá trị thứ hai đến giá trị cuối theo cả hai chiều,
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

Chi tiết kỹ thuật. 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. Bạn có thể đọc thêm về quản lý bộ nhớ MATLAB trong Quản lý bộ nhớ cho hàm và biến trên blog Mathworks và trong Tối ưu hóa bộ nhớ trong Matlab

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. Lưu ý rằng việc lập chỉ mục Python dựa trên 0, vì vậy phần tử thứ hai có chỉ mục 1. 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. Giống như trong ví dụ MATLAB, bạn nên thay đổi phần tử phía trên bên trái của
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. Điều này cũng diễn ra theo hướng khác, khi thay đổi giá trị trong
In [2]: import antigravity
350 sẽ cập nhật giá trị trong
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

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

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

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

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. Các nhà phát triển đến từ các ngôn ngữ khác thường bỏ lỡ điều gì tạo nên mã Pythonic trong các dự án đầu tiên của họ

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

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

In [2]: import antigravity
087 sẽ chặn đầu ra từ dòng đó. 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

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

In [2]: import antigravity
088 và chuyển khóa chuyển đổi
In [2]: import antigravity
089. 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.

Trong trường hợp này, bạn có hai câu lệnh logic cần được phân tách bằng dấu chấm phẩy. 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

Bạn không nên nhập
In [2]: import antigravity
202 từ một mô-đun trong Python

Trong phần trước, bạn đã đọc về cách không gian tên là một ý tưởng tuyệt vời trong Python. Trong MATLAB, theo mặc định, tất cả các hàm là một phần của không gian tên chung, vì vậy mọi hàm và tên lớp phải là duy nhất. Python 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. Tuy nhiên, đó không phải là một phương pháp hay vì bạn không biết tên nào được xác định trong
In [2]: import antigravity
095 và liệu chúng có ghi đè bất kỳ tên hiện có nào trong phạm vi hiện tại của bạn hay không

Technical Note. 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

You Should Take Advantage of the Different Data Types in Python

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

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. Thay vào đó, bạn nên lặp trực tiếp các mục trong danh sách

>>>

In [2]: import antigravity
21

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. Trên mỗi lần lặp lại, giá trị tiếp theo trong danh sách được đưa vào biến
In [2]: import antigravity
116 mà bạn đã chỉ định trên dòng
In [2]: import antigravity
97. Then, you are printing the value of
In [2]: import antigravity
116 on each iteration

Lưu ý trong ví dụ trước rằng bạn có thể lặp lại giá trị của từng phần tử trong danh sách mà không cần sử dụng chỉ mục. 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

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

In [2]: import antigravity
114 và sau đó bạn đang truy cập từng phần tử trong danh sách theo chỉ mục của nó. This can lead to off-by-one and fencepost errors. Instead, you should write code that loops over the list directly

In [2]: import antigravity
24

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

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

từ điển

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

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

In [2]: import antigravity
124 trên dòng đầu tiên. 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 có cấu trúc dữ liệu tương đương được gọi là từ điển. To create a Python dictionary, you can use curly braces and specify the keys and values with each other

>>>

In [2]: import antigravity
28

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

In [2]: import antigravity
716 trong các số, một tính năng có sẵn kể từ 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

Bạn có thể thêm các khóa mới vào từ điển bằng cách gán cho chúng

>>>

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. Nếu bạn cố gắng truy cập một khóa không có trong từ điển, bạn sẽ nhận được một
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. Tuy nhiên, khóa này không tồn tại trong từ điển, vì vậy Python đưa ra một
In [2]: import antigravity
130 để bạn biết rằng
In [2]: import antigravity
131 không phải là một tùy chọn

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. Bạn cũng có thể lặp qua từ điển và sử dụng cách hiểu từ điển, tương tự như cách hiểu danh sách. Bạn có thể đọc về các chủ đề này trong Cách lặp qua từ điển trong Python

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

MATLAB 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

Nếu bạn muốn giới thiệu tổng thể về ngoại lệ Python, bạn có thể đọc Ngoại lệ Python. 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. Khi bạn nhìn thấy một
In [2]: import antigravity
135, hãy kiểm tra mã của bạn để tìm lỗi chính tả và tên biến sai chính tả. 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 ngoại lệ có nghĩa là bạn đã nhập một số cú pháp không đúng. 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

Một

In [2]: import antigravity
137 phổ biến khác là chỉ sử dụng một dấu bằng trong câu lệnh
In [2]: import antigravity
96. 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

Chỉ mụcLỗi

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. Điều này thường có nghĩa là mảng hoặc danh sách bạn đang cố truy cập có ít phần tử hơn chỉ mục mà bạn đang cố truy cập. 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

The solution to this error is usually to

In [2]: import antigravity
151 or
In [2]: import antigravity
152 the package and make sure the correct environment is activated. 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. Chẳng hạn, một hàm làm việc với các số sẽ tăng giá trị
In [2]: import antigravity
661 nếu một chuỗi được truyền vào

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 exceptions happen when you try to access an attribute of an object when the object does not have that attribute. You will often see this error associated with the message
In [2]: import antigravity
160. This message most likely means that a function has returned
In [2]: import antigravity
601 instead of the object you were expecting and you are trying to access an attribute that would be present on the real object, but is not defined for
In [2]: import antigravity
601

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

MATLAB allows you to

In [2]: import antigravity
163 a statement of code and
In [2]: import antigravity
164 any errors that are thrown by the code. 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. Xử lý ngoại lệ

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

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

In [2]: import antigravity
163/______7166. Đầu tiên, bạn thử lấy căn bậc hai của đối số đầu vào và trả về kết quả. 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. Nếu
In [2]: import antigravity
690 tăng
In [2]: import antigravity
015, mã của bạn sẽ in thông báo rằng số này không thể thao tác được. 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. Tuy nhiên, thông thường nên giảm thiểu số lượng dòng mã trong khối
In [2]: import antigravity
163 để bạn có thể xác định cụ thể mã nào đang gây ra bất kỳ lỗi nào

On input line 3, you are testing out

In [2]: import antigravity
168. First, you pass the value 4. 0 to the function. Hàm in đối số và
In [2]: import antigravity
690 không gặp vấn đề gì khi lấy căn bậc hai của 4, kết quả là 2. 0 on the output line

Trên dòng đầu vào 4, bạn đang chuyển -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 có thể được tìm thấy đầy đủ trên trang web Python. 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. ” Điều này có nghĩa là bạn nên tuân theo các khuyến nghị trong PEP 8 cho hầu hết tất cả mã của mình, nhưng có thể có một số trường hợp hạn chế mà bạn không nên tuân theo các khuyến nghị của PEP 8. 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

Ngoài việc đọc PEP 8, bạn có thể sử dụng một vài gói Python để tự động đảm bảo rằng mã của bạn phù hợp với các nguyên tắc về kiểu dáng. Flake8 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. Các gói này có thể được cài đặt bằng cách sử dụng

In [2]: import antigravity
40, trình quản lý gói đi kèm với Python. 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. Bạn có thể đọc tất cả về những gì nó muốn tham dự trong Cách tận dụng tối đa PyCon

Python 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. ] hoặc nhận được câu trả lời hay từ người khác

Nếu bạn muốn theo dõi quá trình phát triển của Python, bạn có thể đăng ký một trong các danh sách gửi thư bao gồm các khía cạnh khác nhau của cộng đồng Python. 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

Sự kết luận

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 là một ngôn ngữ và cộng đồng thực sự rộng lớn, có rất nhiều thứ để học và rất nhiều người để học hỏi. 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. Hãy quay lại bài viết này thường xuyên nếu bạn cần cải thiện kỹ năng của mình và tìm hiểu thêm về cách trở thành một thuật sĩ Python

Đọc thêm

Có rất nhiều tài nguyên trên Web đề cập đến sự khác biệt giữa MATLAB và Python. 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. con trăn
  • 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. Không có thư rác bao giờ. Unsubscribe any time. Được quản lý bởi nhóm Real Python

Send Me Python Tricks »

Giới thiệu về Bryan Weber

Bryan is a core developer of Cantera, the open-source platform for thermodynamics, chemical kinetics, and transport. As a developer generalist, Bryan does Python from the web to data science and everywhere inbetween

» More about Bryan

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

Aldren

Geir Arne

Joanna

Master Real-World Python Skills With Unlimited Access to Real 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 »

Master Real-World Python Skills
With Unlimited Access to Real 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 »

What Do You Think?

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

Tweet Share Share Email

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

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

Chủ Đề