Python Tutorial

Tram Ho

Python is a high-level programming language, python code is often thought to be almost like pseudocode, so it allows you to express strong ideas with few lines of code and it’s also easy to read and understand. Python has many popular libraries such as numpy, scipy, matplotlib, … so it becomes a very powerful environment for data science, artificial intelligence.

In this article, I will summarize the main structures in Python , using short examples to give you an overview. If you have experience learning other languages, it is easy to learn this new language. I also encourage you to try all the examples on your own computer.

Environment settings

I recommend using Anaconda , which is an easy way to manage many different environments, each with its own Python versions and dependencies. How to install, you can go to the homepage for more details. 😆 .

And if you do not want to install many things on your computer, you can use Google’s colab.

Use Interpreter

Python can run 1 of 2 modes. It can interact via an interpeter, or it can be called from a command line to execute a script. We will first use the Python interpreter.

You can call the interpreter with the Python command on the Unix command prompt, while on the window you can use it on the Command Prompt (Admin) . And it runs will have the following result:

It will display the current version you are using. You can also view with the Python --version command

The basic data types

The Python interpreter can be used to evaluate expressions. Example of simple arithmetic expressions. If we enter the expression at the prompt ( >>> ) and press enter, we will get the result in the next line.

Number data type

The integer and real float data types work like other languages, and in Python will force the data type for you without declaring types like int, float in C, C ++.

Note: unlike many other languages, Python does not have a unit of increase ( x ++ ) or decrease of unit ( x– ) but instead you have an example. Python also provides a built-in type for complex numbers, you can find all the detailed documentation in the document .

Boolean

Python also exists with Boolean to manipulate True and False primitive values ​​but uses English rather than symbols ( && , || , ! , …) as in other languages.

String

Like Java, Python has string types. The + operator adds strings together.

There are many appropriate methods that allow us to manipulate strings:

Note that we can use ' ' parentheses or " " parentheses to surround strings. This allows easy feathering of the chains.

We can also store strings as variables as the following example:

String objects have a variety of useful methods, for example:

You can see the list of string methods in the document

Integrated data structure (Built-in DATA structure)

Python is equipped with a number of useful integrated data structures, similar to collections packages in Java. It includes: lists, dictionaries, sets, and tuples

Lists

A list in Python is equivalent to an array, but it can be resized and may contain many components of different types. Example 1 list contains a sequence of items that can be changed:

We can use the + operator to append to the list:

Python also allows negative-indexing from the end of the list. For example, fruist[-1] will access the last banana element:

As usual, you can find all the details of the list in the document

Slicing : In addition to accessing each item in the list, Python provides a concise syntax for accessing sublists, which is known as slicing (cắt lát) . For example, fruits[1:3] returns a list of elements at positions 1 and 2 (in python, elements start at position 0). In general, fruits[start:stop] will take parts from start, start+1, ..., stop-1 . We can also write fruits[start:] return all values ​​from the start position, or fruits[:end] return all elements before the end position.

We will see slicing content again in the numpy library.

As mentioned above, the data stored in the list can be any Python data. For example, we can have 1 list of lists:

Tuples

A data structure similar to list is tuples , like list except that it is immutable once it is created (ie we cannot change its value once we have created it). Note that tuples are surrounded by parentheses while the list has square brackets.

Attempting to modify an immutable structure will throw an exception. Exceptions show errors: index out of bounds errors, type error, … all will report exceptions in the same way as above (write to the screen).

Documentation so you can learn more about tuples

Sets

A set is another data structure like a list but there is no sequence and no duplicate values. Below, I present a way to create a set :

Another way to create a set is shown below:

Next, I will show you how to add an element to a set , type to find an element belonging to `set ‘and perform operations on the set (difference, intersection, union):

As usual, you can learn about the set in the documentation

Note: the objects in the set are unordered, so you cannot assume that their print and print orders will be the same on computers!

Dictionaries (dictionary)

A dictionary stores pairs (key, value) similar to map in Java or an object in Javascript. You can use it as follows:

You can read more about dictionaries in the document .

Write scripts

Now that we’ve familiarized ourselves with the Python compiler, it’s easy to do if you are not running long single statements. We will be familiar with writing a python program and running it. For example, we write a simple Python script that represents the for loop in python. You will write to any text editor and save it as a file .py , here I will save it as foreach.py . It will contain the following code:

At the command line, use the following command in the directory containing foreach.py :

If you like functional programming you might like the map and filter :

Loops

We can loop the elements in the list as follows:

If you want to access the number of each element in the loop body, use enumerate :

We can also duplicate values ​​in the dictionary:

If you want to access the keys and their corresponding values, use the itém method:

Comprehensions

I will take you to the more advanced section, which will learn about comprehensions that make the code more concise and easier to understand.

Comprehensions (inclusions) are structures that allow chains to be built from other chains. Python 2.0 introduced us to the concept of list comprehensions, and Python 3.0 took it further by including the words dict comprehensions and set comprehensions.

List comprehensions

When programming, we often want to convert one type of data to another. For a simple example, consider the following code to calculate the square of each number in the list:

You can make this code simpler by list comprehension:

List comprehension may also contain conditions:

Dictionary comprehensions

Similar to list comprehensions, but allows you to easily build dictionaries. For example :

Set comprehensions

Similar to lists and dictionaries, we can build sets using set comprehensions:

Be careful with change

Unlike many other languages, Python uses indentation in source code to interpret. For example, for the script below:

will output an Thank you for playing output

But if you write the script as follows:

It will produce no result. The main content here is to be careful with indenting, it’s best to use 4 spaces to indent

Jaw

Python functions are defined using the keyword def . For example:

We can also pass optional parameters to the flagship, for example:

For more on Python functions, read the documentation

Classes

The syntax for defining classes in Python is very simple, I will not go into details about this part for an introduction only:

You can read more about Python classes in the document

References

TL; DR

Thank you for reading up to this line, if there is anything that does not understand or I am wrong, you can comment below. See you in the next post.

Share the news now

Source : Viblo