Useful tricks of the Python programming language

Use list datatype

Programming language Python, this feature it has is the commands coding in it to look perfectly crisp and clean they are posted. So, which is very close to the language of the speech is read, which, for example, the following code of the data type (data type) list of use in mind.

As you can see first we have created a variable of the list type entitled numbers and saved the desired values in it:

Next, we have defined a variable called evens in which all the values ​​in the list are stored in this variable, provided that the remainder of dividing each of these values ​​by two is equal to zero.

In other words, this variable holds all the even values ​​in the numbers list, and in the third line we say that it stores all the values ​​in the list minus the values ​​stored in the evens variable so that this variable holds all the values ​​of the person in the list. .

Next, we define a list type variable called cities and store three string values ​​in it, and then we define a function called visit and pass a parameter called city as the input argument to this function.

Inside this function, we say that the input argument to this function, city, is connected to the so-called “Welcome to” string and printed by the print function.

Now we need to call the defined function and in order for this function to run for all the values ​​in the cities list, we need to use the For loop.

Finally, this loop is executed 3 times and displays the following output:

Map function

Python language provides functional programming capability for programmers, in which case the map function is one of the best so-called Built-in functions in this language.

Which in combination with lambda functions provides better performance (in explaining the lambda function, it should be said that, in the Python programming language, it allows the programmers to write a series of so-called Anonymous or “anonymous” functions so that lambda first and then a set name The input argument is considered, followed by the symbol: and then only the allowed command to apply to the input arguments is written.)

Regarding the operation of the map function, it should be said that this function first creates a new array to store the values ​​obtained by calling the function of the programmer for each of the elements of the input argument, and remember that this method is the values ​​of the original array does not change:

operator overloading

The Python programming language has a number of operators that are defined as so-called (built-in) classes in this language.

Now, if we want to change the behavior of each of these operators, we must change the methods that are called when creating new objects from these classes according to our needs, and for this purpose, we define the desired class and the so-called methods in it. We overload.

For example, in the following code, we are going to change the behavior of the lt and gt methods, and as you can see, we first defined a class called Thing, which, while creating any object in the init method class from that class, initializes to It is called that the first argument of this method is self, which refers to the class itself and indicates that the constructed object belongs to this particular class, and the second argument represents the parameter that is supposed to be the input argument for each object constructed from this Class to be considered:

blank

Therefore, we define a method called unit for this class and give it two arguments, self and value, which self indicates that this method belongs to the Thing class, and value also represents the argument that must be set when creating a new object from this class.

Pprint module

This module allows Python programmers to print some complex or nested JSON data structures beautifully and legibly in the output.

Although the print function does the same, the print function has low readability for printing complex data, so let’s look at the following example for the pprint module:

blank

As you can see in the code above, we first import the requests module into the program, which is used to receive data for a specific url in Jason format, and then imports the pprint module and stores a variable called url in order to maintain it. We define the web address in question.

Next, we have created an object called users from the get class related to the requests module to fetch and store the desired data from the mentioned url in the form of json (fetch).

In the following, we have given this variable as an input argument to the pprint function of the pprint module to print the desired data in a structured way in the output.

Queue

Python has the ability to program so-called Multithreading.

Where some program instructions can be run concurrently, which is facilitated by using the standard Queue module in this language.

blank

This module allows programmers to create queue data structures.

So that they are able to handle some tasks based on a series of special rules, one of which is First In First Out or FIFO for short.

Where each of the tasks (tasks) are executed in the same order in which they entered the queue and the next rule is Last In First Out or LIFO for short, according to which the first task added to the queue is executed first.

Finally, there is another rule in which programmers define different priorities for each of the tasks in the queue, and the task with the higher priority is first retrieved and executed.

You can refer to this link to read more about these rules.

__repr__ function

This is also one of the built-in functions in the Python language that programmers can use to display a formal description of the properties of an object.

For example, in the following code:

blank

In the above code, we created an object called file from the open function and passed two arguments as input to this function, each of which is related to the file name that we gave as input to the function.

The second argument indicates our level of access to the file in question, where “r” refers to the word Read, and indicates that our level of access to this file is simply “reading” the file and we can not remove anything from it. Or add to it.

We can also use “w” and “a” instead of “r”. Which indicate the words write and append.

Next, we ask the program to print the information of the desired file stored in the file variable in the output.

Which is a common procedure for displaying file information, and in case we want a so-called professional description (for the programmer himself) to be exposed to this file, we use the __repr__ function, for which we have:

blank

As you can see in the code above, the __repr__ function is configured to suit the needs of the programmers. has it.

And someInstance indicates that we have created an object from the someClass class.

Finally, we can print the value of someInstance using the print function.

blank
sh library python

Sh library

This library provides an interface for programmers to integrate subroutine processes into a single function as a regular function and to access and handle some different libraries needed to run each of these processes. Things like automating workflows and different tasks seamlessly are useful.

The following is an example of how to use this library:

blank

Type hints

Python is a so-called dynamic programming language, which means that to define the type of variables, functions, and classes, we do not need to specify the data type for each of them in the program.

This feature increases the speed of software development. However, the lack of definition of data type in writing code also has disadvantages, the most important of which are errors caused by not recognizing data type in large projects and reduced code readability.

In this regard, from version 3.5 onwards of Python, a feature called Type Hint was added to this language, which allows programmers to refer directly to the data type of variables, as well as the output of program functions.

For example, in the following code:

blank

In the above code, we have defined a function called addTwo and passed the x parameter as the input argument to it, and after the symbol: we said that the input parameter x must be of type int (integer) and the sign <- and then the word int This means that the output of the function will also be of the genus int, which we finally said in the second line to add the input number to the number 2 and return to the output.

Python also has a feature called Type aliase in which you can assign your data to a hypothetical variable.

In fact, we assign a nickname to the data type we want so that if we need to mention it during the program, mentioning this nickname reduces the complexity of the code and makes it more readable, and for this purpose, a modular Python language called typing It has:

blank

In the explanation of the above code, we must say that first we import the typing module and in the next line we assign the nickname Vector to the data type “list of decimal numbers” and in the next line we say that for the data type (list of a set of Vector) which represents Nested lists are decimal numbers, or in other words, a list consisting of several rows of decimal numbers, we have chosen the alias Matrix.

In the following, we have defined a function called addMatrix, and we intend to add this function to two hypothetical matrices a and b. , (Matrix is ​​an alias for the multi-line list of decimal numbers) and we have said that the output of this function will also be Matrix.

In the next line, we define the result variable, which is supposed to hold the output of the sum of the two matrices.

In the next line we have defined two variables called i and row so that we can navigate the elements of each row of the matrix.

Next, we will store all the traversed rows of the matrix in a variable called result_row, and the enumerate is used as a counter to trace the individual elements of each row of this matrix.

In the next line we have defined two variables j and col so that we can navigate each of the elements in the rows of the result_row matrix, which means scrolling the elements in each column of the rows of the matrix.

In the next line, we have asked the program to add the corresponding elements from each column and row and keep them in the result_row matrix, which will eventually add the values ​​of each row of this matrix and save the result in the result matrix. .

To call this function, we define two matrices under the headings x and y and give it as an input argument to the said function. We have given the input title to this function that the result of the sum of these two matrices will be stored in the variable z.

Uuid module

UUID stands for Universally Unique Identifier, and a module under the same heading in Python allows programmers to generate unique 128-bit random numbers.

So that these numbers can be used as a unique identifier to identify documents, hosts, clients, and anything that needs a unique naming.

For example, in the following code:

blank

In the above code, first, import the relevant module, and then by calling the uuid4 function of this module, a random number will be generated, which is stored in a variable called user_id, which is executed by executing the last line command of the said random number by print function. It becomes.

Virtual Environment

In the Python programming language, we may need to use packages or modules that belong to different versions of the language to develop applications in certain situations.

For example, application (a) requires a special module of Python version 3, but application (b) requires the same module from the second version of this language.

In such a situation, the best solution to solve this problem is to create a so-called Virtual Environment, which can be used to install another version of this language on our system, which is the Python programming language for building and managing this environment. The system has a module called venv, to download and install it, type the following command in the command line:

blank

As shown in the above command, we have written the version of Python we want and then we have given the name of the module needed to build the virtual environment, and then we enter the appropriate directory to build this environment.

Within this directory, a number of other subdirectories will be created to install the modules and dependencies required by the application, for which purpose we must first activate the virtual environment created.

Wikipedia module

The Wikipedia website has a set of APIs that allow programmers to access the website’s vast data by accessing them.

In this regard, the Python programming language has a module called wikipedia that provides programmers with access to this web service. Also, this module has the ability to support different languages ​​such as English, Persian, etc.

Other features of this module include the ability to recognize pages, topics and content with similar titles.

As you can see in the following code:

blank

First, it retrieves the information about the words “Roocket.ir” from the Wikipedia website and saves it in the result variable, and in the next line, the collected data is printed by the print function.

We have also said that for all the links in the collected data, print links in the output that use the word “Roocket.ir” in their title.

Xkcd module

In the documents related to some standard Python modules, we see some humorous visual designs. In this regard, the website (xkcd site for publishing humorous visual designs related to language, jokes and mathematics) publishes part of its content to publish topics related to language. Python is assigned.

In addition, the language has a module called xkcd, which provides an interface for programmers to access the website and retrieve their data in json format.

You can also access the Python programming language web page by executing the following command in Commandline:

blank

Needless to say, to use the xkcd module features, you must first download and install it according to the procedure in the previous examples.

YAML

YAML stands for YAML Ain’t Markup Language and is a common standard for converting data into a format that allows data to be transferred, stored and reconstructed on the web.

The YAML standard also has a number of features for displaying data, which has led to it being considered as a so-called Superset or “subset” of the Jason standard, such as the ability to store more complex objects with constituent elements. Pointed to it and wrote Config files.

In this regard, the PyYAML module allows programmers to use the YAML data format in the Python programming language.

This module gives them the ability to store all the data types and objects of the classes defined in the program.

To download and install it, type the following command in Commandline:

blank

Zip function

The predefined zip function has the ability to receive values of objects belonging to two lists and convert them into a kind of dictionary data consisting of the values of these two arrays.

For example, in the following code:

blank

In the first line, we define an array with the desired title keys and store three string values ​​in it.

In the next line, we define another array called vals and store three numeric values ​​in it.

Now, using the last line command, we create a dictionary called zipped, whose keys are selected from the array of keys and their corresponding values ​​from the vals array, exactly according to the order in the two arrays, the result of which is the result stored in the zipped variable. Dict to the predefined function to expose the output as a dictionary data type.

Concluding remarks

Finally, we hope you enjoy this series of useful Python programming language articles.

Leave a Reply

Your email address will not be published. Required fields are marked *