Before practicing the examples of this tutorial, you have to complete the following tasks:
A. To create a Django app named viewapp, run the following command:
B. To create the user for accessing the Django database, run the following command. If you have created the user before then skip this part:
C. Add the app name in the INSTALLED_APP part of the settings.py file.
D. Create a folder named templates inside the viewapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file.
Open the views.py file from the viewapp folder and replace the content of this file with the following script. index() function is used in the script to create the HTML content that will be sent to the browser using the HttpResponse() method. Here, the current date and time of the system will be read using the today() function and the current date value will be generated before sending to the browser.
Views.py
Modify the content of the urls.py file with the following script. In the script, the ‘welcome/’ path is defined to call the index() function that will send the HTML content to the template file.
urls.py
Run the following URL from the browser that will show the following output. A formatted headline text and the current date value are shown in the output.
http://localhost:8000/welcome/
Create a views2.py file inside the viewapp folder and add the following script. MyView class is defined in the script that contains a method named get(). A list variable named listdata is declared in the script to create a list of 10 random numbers. The values of the list will be passed to the template through the HttpResponse() method when this view is called. the random module has been used in the script to generate a random integer number in each iteration of the for loop using the randint() function.
views2.py
Modify the content of the urls.py file with the following script. In the script, the “number/” path is defined to call the MyView.as_view() method that will send the data of the list to the template file.
urls.py
Run the following URL from the browser that will show the following output. The numbers of the output will be changed if the page is refreshed because each number of the list will be generated randomly.
The output of the web application depends on the script of the view file that is a major part of any web application. Function-based views are mostly used in the early version of the Django app and now class-based vies are used in most applications of Django. The ways of creating both types of views have been shown in this tutorial to help the new Django users create their views based on their application.
]]>Django logging contains four types of configurations which are explained below.
1. Django Logger
The logger records the events when the application is executed, and the logging is called. The log entries are stored in a file by categorizing them in different log levels. Every log level indicates the severity of the events. The purposes of these log levels are mentioned below:
2. Django Handler
The main task of the handler is to transmit the log information that is stored in the log file. The logging module contains many types of handlers and multiple of them can be defined for the same logger.
3. Django Formatter
It is used to format the log data. The data of the handler cannot be sent directly to the log file and the handler data requires it to be converted by using the formatter before sending. The formatter converts the log records into the string. The format of the data depends on the business logic of the handler.
4. Django Filter
It is used to filter the log messages. It is unnecessary to store all log messages into the log file. Different handlers can be used for different messages and the required log messages can be filtered using the required filters.
Before practicing the script of this tutorial, you must complete the following tasks:
Open the settings.py file from the Django project folder and add the following content to define the logging information. The properties of the handlers and loggers are set here. According to the logging property values, DEBUG level logging information will be stored in a log file named djangoapp.log when the Django app will be executed.
Open the djangoapp.log file to check log entries are stored in the file or not.
Logging information can be defined using the view file also. Open the views.py file from the logapp folder and replace the content with the following script. In this script, formatters, handlers, and loggers parts of Django logging are defined in the config.dictConfig() method. DEBUG level logging information will be stored in a log file named djangoapp.log and will be printed in the console when the Django app will be executed. index() function is used to send a simple headline text to the browser and the display_log() function is defined to send a simple text in the terminal and a headline text to the browser.
views.py
Modify the content of the urls.py file with the following script. In the script, the empty path(”) path is defined to call the index() function of the views and the ‘log/’ path is used to call the display_log() function of the views.
urls.py
Run the following URL to display the index page.
Run the following URL to call the display_log() method that will display a text message in the browser and a text message in the terminal. Log entries will be appended in the djangoapp.log file.
Two ways of using python logging in the Django application to keep the DEBUG level logging information are shown in this tutorial. The basic concept regarding Django logging is expected to be understood by the readers after reading this tutorial.
]]>Before practicing the examples of this tutorial, you must complete the following tasks:
A. Run the following command to create a Django app named filterapp.
B. Run the following command to create the user for accessing the Django database. If you have created the user before then don’t need to run the command.
C. Add the app name in the INSTALLED_APP part of the py file.
D. Create a folder named templates inside the filterapp folder and set the template’s location of the app in the TEMPLATES part of the py file.
Open the models.py file from the filterapp folder and add the following script to define the structure of employees tables. Employee class is defined to create a table named employees with name, post, email, department, and joining_date fields. Here, name, post, and department fields will store character data, the email field will store the email address and the joining_date field will store date data.
models.py
Run the makemigrations command to create a new migration based on the changes made by the models.
Run the migrate command to execute the SQL commands and create all tables in the database that are defined in the models.py file.
Modify the content of the admin.py file with the following content. Here, the Employee class of the models is registered using the register() method to display the records of employees tables in the Django administration dashboard.
admin.py
Run the following URL to open the Django admin login page. Provide the valid username and password to open the Django Administration Dashboard to access the database tables.
Insert two or more Employee records to apply the filter on the data. Here five records are inserted.
Create the search.html file inside the filterapp/templates/ folder with the following script. The data from the employee table will be displayed in this template file. for loop is used to read the content of the object_list variable that will be passed from the view file. The name, post, and department values of the employees table will be displayed by using the list.
search.html
Open the views.py file from the filterapp folder and modify the content of the file with the following script. Model and template names are defined in the script.
views.py
Modify the content of the urls.py file with the following content. In the script, the ‘searchEmp’ path is defined to call the SearchEmployee.as_view() method that will send all data and the filtered data of the employees table to the template file.
urls.py
The following output will appear without applying any filtering for the following URL.
http://localhost:8000/SerachEmp
Add the following line at the end of the views.py file to filter the records of the employees table where the value of the post field is ‘Accountant’.
The following output will appear after applying basic filtering.
Add the following line at the end of the views.py file to filter the records of the employees table where the value of the department field is ‘HT’ and the email field is ‘[email protected]’.
The following output will appear after applying multiple filtering.
Add the following line at the end of the views.py file to filter the records of the employees table where the value of the post field is ‘Manager’ or the value of the department field is ‘Sales’.
The following output will appear after applying Q object filtering.
Add the following line at the end of the views.py file to filter the records of the employees table where the value of the department field will be checked first and if it returns true then the value of the name field will be checked.
The following output will appear after applying filter chaining.
The data can be filtered in Django in many ways based on the application requirements. Four different ways of filtering were explained in this tutorial to understand the basics of Django filtering. These are simple filtering, multiple filtering, filtering with Q object, and filter chaining.
]]>How the Django template can be created and how the DTL can be used to add static or dynamic content to the template have been shown in this tutorial.
There are many benefits of using DTL in Django templates. Some of them are mentioned below.
Before practicing the script of this tutorial, you have to complete the following tasks:
Run the following command to create a Django app named tempapp:
Run the following command to create the user for accessing the Django database, but if you have created the user before, then don’t need to run the command shown below:
Add the app name in the INSTALLED_APP part of the settings.py file, as shown below:
Create a folder named templates inside the tempapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file, as shown below:
Create the index.html file inside the tempapp/templates/ folder with the following HTML script to display the formatted static text of two lines in the browser. HTML file can’t be displayed directly in the browser and the views.py file is used to render the HTML file in the Django application.
index.html
Open the views.py file from tempapp folder and add the following script. The rander() method is used in the views.py file to display any template file into the browser.
In the following script, the index() function is defined to display the content of the index.html file. When this function call from the urls.py file, then the template file will be displayed in the browser.
views.py
Modify the content of the urls.py file with the following script. According to the script, the index() function of the views.py will be called for the path, ‘index/’.
urls.py
Run the following URL from the browser to get the following output. The static data is displayed in the output.
http://localhost:8000/index/
Create the customers.html file inside the tempapp/templates/ folder with the following HTML script. DTL is used in this script to display the data of the dictionary variable that is initialized by the data of nested lists in the views2.py file. The first for loop is used to read the values of the outer list and the second for loop is used to read the values of the inner list.
customers.html
Create another view file named views2.py under tempapp folder with the following script. A dictionary variable named data is declared in the script that contains a nested list to generate tabular data of 4 rows and 4 columns. The data variable will be sent to the template when the customers() function of this script will be called from the urls.py file.
views2.py
Modify the urls.py file with the following script. ‘customers/’ path is defined in the script to load the customers.html file in the browser with the data of the dictionary.
urls.py
Run the following URL from the browser to get the following output. The records of all customers from the database tables have been displayed in the browser using the DTL.
http://localhost:8000/customers/
The ways of creating a simple template and a template with Django Template Language (DTL) have been shown in this tutorial. The new Django users will be able to create the template for the Django app properly after practicing the script of this tutorial.
]]>How HTML form can be used to take data from the user, read the input values, and print the values in the browser using Django is shown in this tutorial.
You have to create a Django project before creating the Django form. To create a new Django project and go to the project folder, run the following commands:
To create necessary files and apply migrations for the project, run the following command:
To check if the Django server is working properly or not, run the following command:
To create the formapp under django_pro project, run the following command:
Open the views.py file that is inside formapp folder and modify its content with the following content. The following script will check whether the form is submitted or not. If the form is submitted then the value of the request.method will be POST and request.POST.get() method is used to read its submitted values. The is_valid() function will check whether the data of the form is valid or not. If this function returns true, then a success message with the valid user’s data will be printed in the browser, otherwise, the error message that appears on the particular field of the form will be displayed. Other than that, the render() method is used to load the form in the browser and HttpResponse() method is used to send the response from the server to the browser after submitting the form.
Create forms.py inside the formapp folder and add the following content. The following script will create a form of four fields. The name field is defined to take the character data and it can be 40 characters long. The email field is defined to take any valid email address using the character data and it can be 50 characters long. The username field is defined to take the character data, and it can be 20 characters long. The password field is defined to take the character data and it can be a minimum of 10 characters and a maximum of 20 characters long. The forms.PasswordInput widget is used for the password field to hide the content of the password field.
Create a folder named templates inside the formapp folder. Go to the TEMPLATES section of the settings.py file and set the location of the template folder for the DIRS property.
settings.py
Create form.html inside the template folder with the following content.
{% csrf_token %} is used in the HTML script to prevent CSRF(Cross-Site Request Forgeries) attacks. {{ form.as_p }} will load the Django form that is designed by the forms.py file. When the Submit button is pressed, the form data will be submitted to the server.
Open the urls.py from the django_pro folder and modify the content with the following content.
Here, the ‘register/’ path is used to load the form in the browser.
Open any browser and type the following URL to load the user registration form in the browser.
http://localhost:8000/register
The following output will appear after running the URL. The validation for the empty field, the maximum length value of name, email, and password fields, and the minimum and maximum length values of the password field will be checked after submitting the form.
The following output shows that the password field is invalid. According to the form, the length of the password value must be within 10 to 20 characters. 5 characters have been given as input in the following form. For this, the form is showing the error message.
After entering the valid output in every field of the form, the following output will appear.
The way of creating a very simple user registration form in the Django application has been shown in this tutorial. Django has many methods for creating different types of fields of the form, such as CharField(), EmailField(), TextFiled, etc. The form validation task becomes very easier when the form is designed by Django form.
]]>Before practicing the examples of this tutorial, you have to complete the following tasks.
Setup a Django app:
Run the following command to create a Django app named model app.
Run the following command to create the user for accessing the Django database. If you have created the user before, then you don’t need to run the command.
Add the app name in the INSTALLED_APP part of the py file.
Create a folder named templates inside the model app folder and set the template’s location of the app in the TEMPLATES part of the py file.
Create a model for the database table:
Open the models.py file from the model app folder and add the following script to define the structure of two relational tables. Teacher class is defined to create a table named teachers with name, department, email, and phone fields. Course class is defined to create a table named courses with code, name, credit, and teacher fields. Here, the teacher field of Courses table is the foreign key that will appear from the Teachers table.
models.py
Run the makemigrations command to create a new migration based on the changes made by the models.
Run the migrate command to execute the SQL commands and create all tables in the database defined in the models.py file.
Modify the content of the admin.py file with the following content. Here, Teacher and Course classes of the models are registered by using the register() method to display the Teachers and Courses tables in the Django administration dashboard.
admin.py
Set URL for admin login:
The path for admin login is defined in the urls.py file for any Django app by default. If the path is not defined in the file, modify the urls.py file with the following script to open the built-in Django Administration Dashboard for the path’ admin/‘.
urls.py
Insert records in the tables:
Run the following URL from the browser to open the Django Administration Dashboard.
The following tables will be shown for the model app. Any record of the tables can be read, inserted, updated, and deleted from this page.
Click on the Teachers table to insert some records into the table. A form with the necessary fields like the following image will appear for inserting record. There are three buttons in the form to insert records in the table. ‘Save and add another‘ button is used to insert the record and open the form again for inserting the next record. The ‘Save and continue editing‘ button is used to insert the record and open the form again with the data for editing. The ‘Save‘ button is used to insert the record only. Every entry form will contain these three buttons.
After inserting the two teacher’s records, the following information will appear in the browser.
The following form will appear after clicking on the courses table. The Teacher field of the Courses table is related to the Teachers table by the foreign key. The dropdown list with inserted Teacher objects will appear to add the data in this field from the list.
After inserting three records into the Courses table, the following information will appear in the browser. If you want to modify any records of the Courses or the Teachers table, then click on that particular object to open the edit form with the existing data.
You can display the records of both tables in the browser by using the views.py file and creating the temples in the defined template location. You can check the Django View and Django Template tutorials for these.
The table data can be accessed or modified by Django Administration Dashboard, as explained in this tutorial. But the data can be inserted into the tables by writing a script in the views.py file with or without using the template file.
]]>Django framework can be used to create a web application with a database by writing script in models.py and views.py files of the Django app. The data can be inserted into the database tables by using Django Administration Dashboard or by writing a script in the views.py file. Django Administration Dashboard requires a login for an authenticated user to access the tables of the database. Single or multiple records can be inserted into the database tables by writing a script. bulk_create() method is one of the ways to insert multiple records in the database table. How the bulk_create() method is used to insert the multiple data in a Django database table will be shown in this tutorial.
Before practicing the script of this tutorial, you have to complete the following tasks:
Run the following command to create a Django app named bookapp.
Run the following command to create the user to access the Django database. If you already created one, then you don’t need to run the command.
Add the app name in the INSTALLED_APP part of the settings.py file.
Create a folder named templates inside the bookapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file.
Open the models.py file from the bookapp folder and add the following script to define the structure of books tables. Book class is defined to create a table named books with title, author, price, and published_year fields. According to the script, title and author fields will store character data, and price and published_year fields will store the integer data. Here, the title field is defined with the unique attribute. That means that the value of the title field will not accept any duplicate data.
Run the makemigrations command to create a new migration based on the changes made by the models.
Run the migrate command to execute the SQL commands and create all tables in the database that are defined in the models.py file.
Modify the content of the admin.py file with the following content. Here, the Book class of the models is registered using the register() method to display the books tables in the Django administration dashboard.
Create a template file named DisplayBookList.html inside the bookapp/templates/ folder with the following script. This script will display all data of books table in tabular form. Other than that, for loop is used in the script to iterate the data passed from the views.py file.
Modify the content of the views.py file with the following script. The model and template names are defined in the BulkInsert class. get_queryset() method of the class is defined in the script to return all records of the books table. On the other hand, Book.objects.all() method is used to return all records of the books table. exists() method is used in the script to check the books table is empty or not. If this method returns False then five records will be inserted into the books table using the bulk_create() method.
Modify the content of the urls.py file with the following script. In the script, the ‘admin/’ path is defined to open the Django Administration Dashboard and the ‘books/’ path is defined to call the BulkInsert.as_view() method that will insert five records to the books table and return the records to the template file.
Open the Django Administration Dashboard to check whether the data is inserted properly or not using the bulk_create() function.
The inserted records of the books table will be displayed in the browser after executing the following URL.
Multiple records can be inserted into the Django database table in different ways using the bulk_create(). A simple way of inserting multiple records in the database table using this method was shown in this tutorial to help Django users understand the logic behind the process.
]]>Before practicing the script shown in this tutorial, be sure to complete the following tasks.
Run the following command to create a Django app named socketapp:
Run the following command to install the channel:
Add the channels and app name to the INSTALLED_APP part of the settings.py file:
Define the value of ASGI_APPLICATION in the settings.py file:
Create a folder named templates inside the socketapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file:
The following output will appear in the terminal after running the Django server. The output shows that ASGI/Channels version 3.0.3 is running.
Create a template file named index.html in the defined template location to display the data sent by the WebSocket. The socket object that is created using JavaScript will read the data using the JSON.parse() method, then pass the value into the content of the <h1> tag that contains the ID value, ‘msg.’
index.html
Modify the views.py file of the socketapp with the following content. The index.html template file will be displayed in the browser with the text variable when the index() method of this script is called from the urls.py file. If no message is transmitted from the socket, then the text ‘LinuxHint’ will be displayed in the browser.
views.py
Modify the urls.py file of the socketapp with the following content. Two paths are defined in the script: the ‘admin/’ path is used to open the Django Administration Dashboard, and the ‘msg/‘ path is used to read the WebSocket message.
urls.py
When the following URL is executed without defining the consumer and routing files, the HTTP protocol will work and the following output will appear.
Now, create a consumers.py file inside the socketapp folder with the following script. The connect() method of ws_consumer will be used to accept the socket connection, read the current time value every second, and send the current time in JSON format via WebSocket when this method is called from the routing file.
consumers.py
Create the routing.py inside the socketapp folder with the following script. The ‘msg/’ path is defined in the script to call the consumer for sending the data to the socket.
routing.py
Modify the asgi.py file with the following script. The modules that are required to handle HTTP and WebSocket requests are imported in the script.
asgi.py
Now, run the following URL from the browser again to read the data from the WebSocket.
If the consumer and router are working properly, then the following digital clock will be displayed in the browser. Here, the router has sent the WebSocket request using the ‘msg/‘ path to the consumer that has accepted the request and sent the data to the template to show the digital clock in the browser where the second value of the current time is updating every second.
This tutorial showed you how to implement a real-time application using the Django framework and channels by creating a simple digital clock. Other types of real-time applications can also be implemented using Django and channels, such as online chatting systems. The scripts used in this tutorial work for Django versions 3+ and Channel versions 3+ only. So, if you are using an earlier Django or Channel version, then you will need to upgrade the version before testing the script provided in this tutorial.
]]>Before practicing the script of this tutorial, you have to complete the following tasks.
Run the following command to create a Django app named serialapp.
Run the following command to create the user for accessing the Django database. If you have created the user before, then you don’t need to run the command.
Run the following command to install Django REST Framework.
Add the rest_framework and app name in the INSTALLED_APP part of the settings.py file.
Open the models.py file from the serialapp folder and add the following script to define the structure of customers tables. Customer class is defined to create a table named customers with name, address, email, contact_no, and created fields. Here, name, email, and contact_no fields will store character data, the address field will store the text data, and created field will store the DateTime data.
models.py
Run the makemigrations command to create a new migration based on the changes made by the models.
Run the migrate command to execute the SQL commands and create all tables in the database defined in the models.py file.
Modify the content of the admin.py file with the following content. Here, the Customer class of the models is registered by using the register() method to display the customers tables in the Django administration dashboard.
admin.py
urls.py
Open the Django Administration page and add some records into the customers table displayed to the browser in JSON format. Here, three records have been inserted.
Open the views.py file from the serialapp and replace the content with the following script. CustomerList class is defined to serialize all the customers’ records and return the data to the browser in JSON format. CustomerDetail class is defined to serialize the particular customer record based on the ID value and return the browser’s data in JSON format. CustomerSerializer is a serializers file that has been created in the next part of this tutorial.
views.py
Create serializers.py file in the same location of the views.py file with the following script. ModelSerializer class is used here to create CustomerSerializer class that returns the serializers class with the fields of the Customer model. The Customer model fields that will be converted into JSON format are mentioned in the Meta class.
serializers.py
Modify the content of the urls.py file with the following script. In the script, the ‘customers/‘ path is defined to display all records of the customers table in JSON format, and the ‘customers/<int:pk>/‘ path is defined to display the particular data of the customers table in JSON format based on ID value.
urls.py
All records of the customers table will be shown in JSON format if the following URL will execute.
http://localhost:8000/customers
The record of the second customer will be shown in JSON format if the following URL executes.
http://localhost:8000/customers/2
The use of serializers in the Django application to convert the model instance into JSON format has shown in this tutorial by using a simple script. The Django users will understand the purpose of using serializers and apply them in their application if required after reading this tutorial.
]]>Before practicing the script of this tutorial, you have to complete the following tasks.
Run the following command to create a Django app named queryapp.
Run the following command to create the user for accessing the Django database. If you have created the user before, then you don’t need to run the command.
Add the app name in the INSTALLED_APP part of the settings.py file.
Create a folder named templates inside the queryapp folder and set the template’s location of the app in the TEMPLATES part of the settings.py file.
Open the models.py file from the queryapp folder and add the following script to define the structure of products tables. Product class is defined to create a table named products with name, type, brand, and price fields. Here, name, type, and brand fields will store character data, and the price field will store the integer data.
models.py
Run the makemigrations command to create a new migration based on the changes made by the models.
Run the migrate command to execute the SQL commands and create all tables in the database that are defined in the models.py file.
Modify the content of the admin.py file with the following content. Here, the models’ Product class is registered by using the register() method to display the products tables in the Django administration dashboard.
admin.py
Create a template file named productList.html inside the queryapp/templates/ with the following script. This script will display all data of products table in tabular form with a search box. The user will be able to search the particular records from the products table by using the search form. for loop is used in the script to iterate the data passed from the views.py file.
productList.html
Modify the content of the views.py file with the following script. The model and template names are defined in the ProductList class. get_queryset() method of the class is defined in the script to filter the data based on the content submitted by the search box of the template. Product.objects.all() method returns all records of the products table. request.GET.keys() method is used in the script to check any data is submitted by the search form. If this method returns true, then the request.GET.get(‘src’) method is used to check the submitted value is empty or not. If this method returns a non-empty value, then the value will be stored in the variable, keyword, and it will be used for filtering the data based on the brand and type fields from the products table.
views.py
Modify the content of the urls.py file with the following script. In the script, the ‘searchPro/’ path is defined to call the ProductList.as_view() method that will send all data and the filtered data of the products table to the template file.
urls.py
Open the Django Administration page and add some records into the products table to apply the queryset on then. Here, five records have been inserted.
All records of the products with the search box will be displayed in the browser after executing the following URL.
http://localhost:8000/searchPro
All the shampoo products displayed if the product type, ‘shampoo‘ will be searched in the search box.
The milk powder products of the Fresh brand will be displayed if the product brand, ‘fresh‘ will be searched in the search box.
The way of filtering the data of a simple database table by using queryset has explained in this tutorial. The data can be filtered in different ways. The readers will understand using a queryset to filter or search data in the browser after reading this tutorial.
]]>The following sections provide examples that illustrate how to implement two different applications using the QTimer class.
The following script will implement a stopwatch application in Python using the QTimer class. This application will count the number of seconds and the number of minutes. Two buttons are used to start, stop, resume, and reset the counter. When the user clicks the Start button, the counter will start counting, and the caption of the Start button will be changed to Stop. When the user clicks the Start button with the caption Stop, the counter will stop temporarily, and the caption of the Start button will be changed to Resume to continue the counter to the next time. When the user clicks the Reset button, all the values of the counter will be initialized to 0.
The following window will appear after the above script is executed.
The stopwatch will start working after the user clicks the Start button.
The counter will stop counting after the user clicks the Stop button.
The following script will implement a digital clock in Python using the QTimer class. The script will display the digital clock in a label by reading the current system time once every second.
The following output window will appear after the above script is executed.
The date and time value of the current system time can be read in various ways using the QTimer class of the PyQt library. The QTimer class was used in this tutorial to execute various example time-related scripts.
]]>The QTableWidget class includes many methods to perform tasks related to table creation. Some of the more commonly used methods of this class are explained below:
Method Name | Purpose |
---|---|
setRowCount() | Used to define the number of rows. |
setColumnCount() | Used to define the number of columns. |
setHorizontalHeaderLabels() | Used to set the header labels of the table. |
setItem() | Used to set the cell value of the table. |
resizeColumnsToContents() | Used to resize the columns of the table based on the content. |
resizeRowsToContents() | Used to resize the rows of the table based on the content. |
setMinimumWidth() | Used to set the minimum width of the table. |
setMinimumHeight() | Used to set the minimum height of the table. |
show() | Used to display the table. |
The following sections provide simple examples to explain how to create a table in the PyQt application using static data and list data.
The following script creates a table of static data with five rows and four columns using the QTableWidget class. Two for loops with range values have been used in the script to add the static data into the table cells. The row and column positions of each cell have been added as the content of each cell. The QDesktopWidget is used in the script to display the window with the table in the center of the screen.
The following window with a table will appear the above script is executed. According to the values of the for loops, the cell value of the first row and the first column is ‘Row-1, Col-1,’ and the cell value of the last row and last column is ‘Row-5, Col-4.’
The following script creates a table with the content of a Python dictionary and list using the QTableWidget class. The script also adds a tool-tip text for the table header. A Python dictionary named marks is also declared in the script. The course codes are used as the key values of the dictionary. A Python list is declared to define the student IDs. The key values of the dictionary are added to the header of the table, the values of the list are added to the first column of the table, and the values of the dictionary are added to the other columns of the table.
The following window with the table will appear after the above script is executed.
This tutorial showed you how to create tables with fixed data, dictionary data, and list data using two examples. Tables can also be created with dynamic data using database tables or other data sources.
]]>The QPushButton class has many methods to perform various button-related tasks. Some of the more commonly used methods of this class are mentioned below:
Method Name | Purpose |
---|---|
text() | Used to read the caption of the button. |
setText() | Used to set text in the caption of the button. |
setIcon() | Used to set an icon in the caption of the button. |
setDefault() | Used to set the default button. |
setEnabled() | Used to enable or disable buttons. A value of True is used to enable the button, and a value of False is used to disable the button. |
setCheckable() | Used to identify whether the button is pressed or released. |
isChecked() | Used to read the state of the button that is a boolean value. |
toggle() | Used to toggle between states. If the current value of the button state is True, then the value will change to False, and vice versa. |
The following sections provide several simple examples to explain the usage of QPushButton.
The following script is used to create a single button in the window. The script will attach a custom function with the clicked event of the button to check whether the button has been clicked. The window will display a button following the execution of the code. If the user clicks the button, the text ‘Button is pressed’ will show in the label.
The following window will appear after executing the script.
If the user clicks the Çlick Me button, then the following text will appear in the caption beneath the button.
The following script will create multiple pushbuttons using the QPushButton class. Two buttons are created in the script. The clicked event of the ‘Yes’ button is attached to a method named btn1_onClicked(), and the clicked event of the ‘No’ button is attached to a method named btn2_onClicked(). A caption created below the buttons will display the specified message based on the button clicked by the user. The setGeometry() function is used for each label and button to set the position of the objects in the window.
The following window will appear after executing the script.
If the user clicks the Yes button, the message, ‘You clicked Yes’ will be displayed as the label text.
If the user clicks the No button, the message, ‘You clicked No’ will be displayed as the label text.
The QPushButton class allows users to create one or more buttons based on the application requirements. This tutorial showed the usage of this class for creating one or multiple buttons, as well as how to handle click events of buttons using custom event handler functions.
]]>The QMessageBox class has many methods for creating various types of message boxes. Some of the more commonly used methods of the QMessageBox class are described below:
Method Names | Purpose |
---|---|
setTitle() | Used to display the custom title. |
setText() | Used to set the text of the main message. |
setDetailText() | Used to display a window with a details button; the message text will appear after the user clicks on the button. |
setInformativeText | Used to display the additional message. |
setIcon() | Used to set an icon in the message box based on the message type. |
setWindowTitle() | Used to set the title of the message window. |
setDefaultButton() | Used to set the button in the message box default; the button will release a clicked signal when the Enter key is pressed. |
setEscapeButton() | Used to set any button to work as an escape key; the button will release a clicked signal when the Escape key is pressed. |
setStandardButtons() | Various standard buttons can be used in the message box based on the message type, such as OK, Yes, No, Cancel, Close, etc. |
The following sections of this tutorial provide examples that will show you how to create different message boxes using the QMessageBox class.
The following script will create a simple informational message box using the QMessageBox class. This type of message box provides the informational message for the user only. OK is the default button in the message box. Here, QMessageBox.Information is used in the setIcon() method to display the information icon in the message box.
The following message box will appear after the above script is executed.
The following script will create the warning message box using the QMessageBox class. This type of message box provides the warning message for the user. The warning is used in the setIcon() method to display the warning icon in the message box. The OK and Cancel buttons are added to the message box using the setStandardButtons() method. A custom method called msgButton() is defined in the class to trace the button in the message box that has been clicked by the user. If the user clicks the OK button, then the text, ‘OK button is pressed,’ will print; otherwise, the ‘Cancel button is pressed’ text will print.
The following message box will appear after the above script is executed.
If the user clicks the OK button, the following output will appear.
The following script will create the question message box using the QMessageBox class. This type of message box provides the question message for the user to take the particular action based on the user’s decision. Here, QMessageBox.Question is used in the setIcon() method to display the question icon in the message box. The Yes and No buttons are added to the message box using the setStandardButtons() method. The No button is set as the default button using the setDefaultButton() method. A custom method called msgButton() is defined in the class to trace the button in the message box that has been clicked by the user.
The following message box will appear after the above script is executed.
If the user clicks the Enter key without selecting any buttons, then the No button will be activated by default, and the following output will appear:
In this tutorial, three different types of message boxes were created using the QMessageBox class. Hopefully, this tutorial helped you to better understand the usage of this class. You should now be able to create a message box for the PyQt application.
]]>A ComboBox is used to select one item from a list of items, much like the radio button. The QComboBox class of PyQt is used to create drop-down lists using Python script. It brings up a list of items for the user to select. The items of the ComboBox can be added, changed, and removed using the script. Multiple items can be selected like the CheckBox button from the list of items from the ComboBox then it is called ListBox. This tutorial shows you how to use QComboBox to create a drop-down list in Python.
The QComboBox class contains many methods for performing various tasks related to ComboBox. Some of the more commonly used methods of this class are described below:
Method Name | Purpose |
---|---|
count() | Used to count the total number of items in the list. |
addItem() | Used to add a single new item to the list. |
addItems() | Used to add multiple items to the list. |
itemText() | Used to read the text of a particular item based on an index. |
setItemText() | Used to set the text of a particular item based on an index. |
currentText() | Used to read the text of the selected item. |
currentIndex() | Used to read the index of the selected item. |
clear() | Used to delete all items from the list. |
highlighted() | Used when an item in the list is highlighted. |
activated() | Used when an item is selected by the user. |
currentIndexChanged() | Used when the item in the list has changed. |
The following sections provide examples that explain some different uses of the ComboBox using the QComboBox module of the PyQt library.
This example shows you how to create a simple drop-down list using the QComboBox class. Here, a drop-down list of five elements is created and is attached to a custom function that will print the selected value from the list. One label is used in the function of the drop-down list to display static text, and another label is used below the drop-down list to show the selected value.
If the user clicks on the drop-down list after executing the script, the following list will appear.
If the user selects the value Bash from the drop-down list, the value of the second label will be changed to ‘You have selected: Bash.’
In the previous example, the drop-down list was created with static data using the addItem() method of the QComboBox class. This example shows you how to add multiple items in the drop-down list by defining a Python list. First, we will add static text to the first item of the drop-down list using the addItem() method. Next, we will define a list of five elements in the script, and we will add these elements to the drop-down list using the addItems() method. A custom function is attached to the drop-down list to display the message in the label based on the user selection.
If the user clicks the drop-down list after executing the script, then the following list will appear.
If the user selects any item except the first item in the drop-down list, then the selected value will be shown in the label by combining with the other text.
If the user selects the first item in the drop-down list, then the value, ‘You have selected nothing’ will be shown in the label.
This article showed you how to create and use drop-down lists in Python using the QComboBox class using simple examples to help you to better understand the use of this class.
]]>PyQt is a popular Python library used to implement graphical applications in Python more easily. This library comes with a GUI (Graphical User Interface) builder tool called Qt Designer. The GUI can be built quickly in Python using the drag-and-drop feature of this library, though this tool has no debugging facility like the standard IDE. This tutorial shows you how to implement the GUI using the Qt Designer class of PyQt.
You must install the Qt Designer tool before practicing the examples provided in this tutorial. Run the following commands to install the Qt Designer on your system:
Run the following command to change the current directory location to the Qt Designer folder.
Run the following command to open the Qt Designer application.
If the Qt Designer has been installed properly, the following window will appear. The Widget box shown on the left side of the main window contains various widgets that you can use to design the user interface of the application. The New Form window is used to create a new window using the default buttons. The windows shown on the right side of the main window provides information about the widgets that can be read or modified.
To begin designing the interface for the Python application, we will click the Create button in the following window to open the dialog box with two default buttons.
Next, we will design a login form using the Label, Text Edit, and Push Button widgets. The dialog box will be saved with the name Login.ui, which will be used later in the Python script. The QObject name will be changed to Logindialog using the Property Editor Window of this application.
The user interface file created by the Qt Designer can be used in the Python script in two ways. The file can be used directly in the Python script, or the converted Python file of the Qt Designer file can be used in the Python script. Both ways of using the dialog box of Qt Designer are shown in the following section of the tutorial.
The UIC module of the PyQt library is used to load the file created by the Qt Designer, and the loadUI() method of the UIC module is used to load the UI file. The following script shows how to load the Qt Designer file named Login.ui that we created before. The necessary modules are imported at the beginning of the script. The object of the application is created using the QApplication(), and the Qt Designer file is loaded using the loadUI() method. Next, the exec() method is called to start the event loop of the application.
The following dialog box will appear after executing the above script.
The UI file created by the Qt Designer can be converted into a Python file using the pyuic5 command. Run the following command to convert the Login.ui file into the loginForm.py file. The Login.ui file must be stored in the current location to run the following command; otherwise, an error will be generated.
The following code will be generated in the loginForm.py file after executing the above command.
The following will display the Login dialog box by importing the loginForm.py file created using the pyuic5 command. The object of the application is created using QApplication(), and the Login dialog box is loaded using the setupUi() method. The Login button is attached with the loginClicked() method to check whether the username and password taken from the user are valid. The Cancel button is attached to the cancelClicked() method to quit from application. The exec() method is called to start the event loop of the application.
The following dialog box will appear after executing the above script.
If the user enters the wrong username or password in the Login form, then the following output will appear after clicking the Login button.
If the user enters the correct username and password in the Login form, then the following output will appear after clicking on the Login button.
If the user clicks the Cancel button in the Login form, then the dialog box will disappear.
This tutorial showed you how to install Qt Designer and how to design a simple form using this application. The tutorial also showed you how to load the UI dialog box directly and after converting it into the Python script have shown in the other part of this tutorial. Hopefully, this article helped you to better understand the usage of Qt Designer for building and using the GUI in applications.
]]>The steps of implementing a simple PyQt application to calculate the sum of two numbers are shown in this section of the tutorial. Here, the number values will be taken from the user using textboxes, after executing the script, then the sum of the values will be displayed after clicking a button. A window with the necessary fields has been created here to build the design of the application; next, the Python script is used to calculate the sum.
Steps:
You have to import the required modules of Python to design the PyQt application of this tutorial. To design this application, it will require two labels, two text boxes, and a push-button.
QApplication, QMainWindow, QLabel, QTextEdit, and QPushButton modules will be required to design the application.
Add the following lines at the beginning of the script to use these modules.
Add the following lines to create the application object and start the event loop. Nothing will appear after executing the script now.
Create the class to add the necessary objects in this step to design the application window.
Add the following lines to create a class with a window object. Here, the title, size, and position of the window are set. Next, the show() method is called to display the window as output.
You have to create the object of the class before running the event loop.
The following blank window will appear after executing the script.
Now, add the necessary objects required to implement the application. The three objects of the QLabel widget, two objects of the QTextEdit widget, and a button object of the QPushButton widget are created in this step. The first two label objects will be used to provide the helping text before the textboxes. QTextEdit objects will be used to take two number values from the user. QPushButton object will be created to calculate the sum of the input numbers using an event handler function that will be created in the next step. The last label object will be used to display the summation of the two numbers. Here, the setGeometry() function is called for every object to set the position of the object in the window.
The following output will appear after executing the script. No event handler function is created in this step, which is used to calculate the sum of the numbers. So, if the user clicks the button, nothing will happen.
Create a method named onClicked() with the following lines inside the addition class to handle the click event of the button. The values of the textboxes are converted into integer numbers using the int() function and stored into the num1 and num2 variables. Next, the sum of num1 and num2 are stored in the result variable. The values of num1, num2, and result variables are converted into string values using the str() function, before storing the values in the output variable. The third label object is used to display the content of the output variable.
Add the following lines in the class after the button object to call onClicked() method when the button will be clicked.
After executing the script, if the user entered 12 and 18 in the textboxes and clicked on the Calculate Sum button, and the following formatted output will appear below the button.
The implementation of a very simple PyQt application has been explained in this tutorial starting from the basic to help the new Python users. Hopefully, the user will be able to design and create a simple PyQt application after completing and understanding the steps of this tutorial properly.
]]>The scientific or numerical visualization tasks can be done in python easily using various Python libraries, such as Plotly, Matplotlib, Seaborn, ggplot, PyQt, etc. PyQtGraph is a useful module of the PyQt library to create a graph. This module can create graphs very fast. 2D and 3D graphics can be created by using this module. How to use the PyQtGraph module to draw different types of graphs has shown in this tutorial.
You have to install the PyQtGraph module in your system before creating the graph. Run the following command to install PyQtGraph by using pip3.
A line chart or line graph is a chart that displays information by using a series of data plots. PlotWidget widget is used to create all plots of PyQtGraph. This widget contains a canvas on which any plot can be added or removed.
The following script shows the way to draw a line graph using random numbers. range() function is used to generate 10 sequential numbers that are used for x-axis values. The random module of python is used to generate 10 random integer numbers used for y-axis values. plot() method is used to draw each plot of the line graph based on the values of the x-axis and y-axis. When the code is executed in interactive mode, then sys.flags.interactive flag will be True. If this flag’s value is not True, then it indicates that the Qt event loop does not require to run because the REPL (Run, Evaluate, Print, Loop) already has an event loop.
Output:
The following similar line graph will be appeared after executing the above script. The graph will vary in each execution for the random values.
The following script shows how to draw a stylist line graph based on the values of a python list. mkPen() function is used to set the color and width of the line. ‘o‘ is used as the marker in the graph, and the color and width of the marker are set by using symbolPen and symbolSize properties.
Output:
The following line graph will be appeared after executing the above script.
A set of data can be visualized by using a bar graph. A simple bar creates by comparing the list of data with a related range of data. BarGraphItem class is used to create the bar graph by using PyQtGraph.
The following script shows how to draw a bar graph based on the values of a NumPy array. BarGraphItem is used to draw a bar graph with blue color and a width value of 0.5.
Output:
The following bar graph will be appeared after executing the above script.
Creating three different types of graphs with random values, list items, and NumPy array have shown in this tutorial by using three simple examples. The readers will be able to use the PyQtGraph module for implementing line and bar graphs after reading this tutorial.
]]>The checkbox is used to select zero or more options from many options using the graphical user interface. A form with a checkbox can be created by using QCheckBox class in a Python script or using the QCheckBox widget of Qt Designer without writing any script.
When a form with a checkbox is created using QCheckBox class, then stateChanged.connect() function is called to apply the action done by the user’s input. If the user checked any checkbox option, then the value of QtCore.Qt.checked will be True. Multiple checkboxes with a single selection like Radio Button can be created using QbuttonGroup class.
How a form with a checkbox can be created by writing a Python script is shown in this tutorial.
QCheckBox class has many functions to do different types of tasks with the checkbox. Some most commonly used methods of this class are described below:
Method Name | Purpose |
---|---|
isChecked() | It returns a boolean value. When the user clicks to check the checkbox, it returns True, otherwise, it returns False. |
setChecked() | It is used to change the state of the checkbox. True value is set to make the checkbox checked, and False value is set to make the checkbox unchecked. |
text() | It is used to read the label of the checkbox. |
setText() | It is used to set the label of the checkbox. |
isTriState() | It returns a boolean value. It is used to check the tri-state to know whether the checkbox is enabled or not. |
setTriState() | It is used to enable the third state of the checkbox that indicates the neutral state. |
The uses of the checkbox are shown in this section using different types of examples. The use of a single checkbox, as shown in the first example, and the use of multiple checkboxes are shown in the second example.
The way of creating a single checkbox using QCheckBox class and reading the input value of the checkbox provided by the user are shown in this example. The necessary modules are imported at the beginning of the script. A label is used in the above checkbox for providing the information for the user. If the user clicks on the checkbox to check, then the script will print, “Wow! You like programming”, otherwise the script will print, “Oh no!, You don’t like programming”.
The following window with a checkbox will appear after executing the script.
In the following output, the user has checked the checkbox twice and unchecked the checkbox once.
The method of creating multiple checkboxes using QCheckbox class and reading multiple values of the multiple checkboxes are shown in this example. Two labels and three checkboxes are added to the window. The first label is added at the beginning of the checkboxes to provide information for the user, while the second label is added at the end of the checkboxes to display the values of the selected checkbox or checkboxes.
The following window will appear after executing the script. The default value of the second label is “Nothing is selected” and the value of the label will be changed when any checkbox is checked or unchecked by the user.
In the following output, two checkboxes are checked by the user, and the value of the second label is changed to “Chocolate, Pasta”.
The way of defining one or multiple checkboxes and reading the values of the selected checkbox(es) have been explained in this tutorial using two simple examples. The groups of checkboxes can be defined to select a particular checkbox from a group that is not shown here.
]]>Python NumPy library has many aggregate or statistical functions for doing different types of tasks with the one-dimensional or multi-dimensional array. Some of the useful aggregate functions are mean(), min(), max(), average(), sum(), median(), percentile(), etc. The uses of mean(), min(), and max() functions are described in this tutorial. The mean() function is used to return the arithmetic mean value of the array elements. The arithmetic mean is calculated by dividing the sum of all elements of the array by the total number of array elements. If the particular axis is mentioned in the function, then it will calculate the mean value of the particular axis. max() function is used to find out the maximum value from the array elements or the elements of the particular array axis. min() function is used to find out the minimum value from the array elements or the particular array axis.
The syntax of the mean() function is given below.
Syntax:
This function can take five arguments. The purposes of these arguments are described below:
input_array
It is a mandatory argument that takes an array as the value and the average of the array values is calculated by this function.
axis
It is an optional argument, and the value of this argument can be an integer or the tuple of integers. This argument is used for the multi-dimensional array. If the value of the axis is set to 0, then the function will calculate the mean of the column values, and if the value of the axis is set to 1, then the function will calculate the mean of the row values.
dtype
It is an optional argument that is used to define the data type of the mean value.
out
It is an optional argument and is used when the output of the function will need to store in an alternative array. In this case, the dimension of the output array must be the same as the input array. The default value of this argument is None.
keepdims
It is an optional argument, and any Boolean value can be set in this argument. It is used to transmit the output properly based on the input array.
This function returns an array of mean values if the value of the out argument is set to None, otherwise the function returns the reference to the output array.
The following example shows how the mean value of a one-dimensional and two-dimensional array can be calculated. Here, the first mean() function is used with a one-dimensional array of integer numbers, and the second mean() function is used with a two-dimensional array of integer numbers.
Output:
The following output will appear after executing the above script.
The syntax of the max() function is given below.
Syntax:
This function can take six arguments. The purposes of these arguments are described below:
input_array
It is a mandatory argument that takes an array as the value, and this function finds out the maximum value of the array.
axis
It is an optional argument, and its value can be an integer or the tuple of integers. This argument is used for the multi-dimensional array.
out
It is an optional argument and is used when the output of the function will need to store in an alternative array.
keepdims
It is an optional argument, and any Boolean value can be set in this argument. It is used to transmit the output properly based on the input array.
initial
It is an optional argument that is used to set the minimum value of the output.
where
It is an optional argument that is used to compare the array elements to find out the maximum value. The default value of this argument is None.
This function returns the maximum value for the one-dimensional array or an array of the maximum values for the multi-dimensional array.
The following example shows the use of the max() function to find out the maximum value of a one-dimensional array.
Output:
The following output will appear after executing the above script.
The syntax of the min() function is given below.
Syntax:
The purposes of the arguments of this function are the same as the max() function that has been explained in the part of the max() function. This returns the minimum value of the input array.
The following example shows the use of the min() function to find out the minimum value of a one-dimensional array.
Output:
The following output will appear after executing the above script.
The purposes of three useful aggregate functions (mean(), max(), and min()) have been explained in this tutorial to help the readers to know the ways of using these functions in python script.
]]>where the () function can take two arguments. The first argument is mandatory, and the second argument is optional. If the value of the first argument (condition) is true, then the output will contain the array elements from the array, x otherwise from the array, y. This function will return the index values of the input array if no optional argument is used.
Different types of Boolean operators can be used to define the condition of this function. The uses of where a () function with multiple conditions are shown in this part of the tutorial.
The following example shows the use of the where() function with and without the optional argument. Here, the logical OR has used to define the condition. The first where() function has applied in a one-dimensional array that will return the array of indices of the input array where the condition will return True. The second where() function has applied in two one-dimensional arrays will retrieve the values from the first array when the condition will return True. Otherwise, it will retrieve the values from the second array.
The following output will appear after executing the above script. Here, the condition has returned True for the values 23,11,18,33, and 38 of the first array. The condition has returned False for the values 45, 43, 60, 71, and 52. So, 42, 43, 44, and 48 have been added from the second array for the values 45, 43, 60, and 52. Here, 71 is out of range.
The following example shows how the () function can be used with the multiple conditions defined by logical and applied in two one-dimensional arrays. Here, two one-dimensional NumPy arrays have been created by using the rand() function. These arrays have been used in the where() function with the multiple conditions to create the new array based on the conditions. The condition will return True when the first array’s value is less than 40 and the value of the second array is greater than 60. The new array has printed later.
The following output will appear after executing the above script. The condition has returned False for all elements. So, the returned array contains the values from the second array only.
The following example shows how where the () function can be used with the multiple conditions defined by logical AND that will be applied in two multi-dimensional arrays. Here, two multi-dimensional arrays have been created by using lists. Next, these functions have applied in where() function to create the new array based on the condition. The condition used in the function will return True where the value of the first array is even and the value of the second array is odd; otherwise, the condition will return False.
The following output will appear after executing the above script. In the output, 43, 12, 7, 34, 9, 22, 41, 5, and 12 have added in the new array from the second array because the condition is False for these values. The first 12 value in the new array has added from the first array because the condition is True for this value only.
where the () function of the NumPy library is useful for filtering the values from two arrays. Creating a new array by filtering the data from two arrays based on multiple conditions defined by logical OR and logical AND has been explained in this tutorial. I hope the readers will be able to use this function in their script properly after practicing the examples of this tutorial.
]]>This function can take six arguments to return the computed histogram of a set of data. The purposes of these arguments are explained below.
This function can return two arrays. One is the hist array that contains the set of histogram data. Another is the edge array that contains the values of the bin.
The following example shows the use of the histogram() function with a one-dimensional array and the bins argument with the sequential values. An array of 5 integer numbers has been used as an input array, and an array of 5 sequential values has been used as bins value. The content of the histogram array and bin array will print together as output.
The following output will appear after executing the above script.
The following example shows how the histogram array and the bin array can be created by using the histogram() function. A NumPy array has been created by using arrange() function in the script. Next, the histogram() function has called to return the histogram array and bin array values separately.
The following output will appear after executing the above script.
The following example shows the use of the density argument of the histogram() function to create the histogram array. A NumPy array of 20 numbers is created by using arange() function. The first histogram() function is called by setting the density value to False. The second histogram() function is called by setting the density value to True.
The following output will appear after executing the above script.
You have to install the matplotlib library of python to draw the bar chart before executing this example’s script. hist_array and bin_array have been created by using the histogram() function. These arrays have been used in the bar() function of the matplotlib library to create the bar chart.
The following output will appear after executing the above script.
The histogram() function has been explained in this tutorial by using various simple examples that will help the readers know the purpose of using this function and apply it properly in the script.
]]>NumPy library is used in python to create one or more dimensional arrays, and it has many functions to work with the array. The unique() function is one of this library’s useful functions to find out the unique values of an array and return the sorted unique values. This function can also return a tuple of array values, the array of the associative indices, and the number of times each unique value appears in the main array. The different uses of this function are shown in this tutorial.
The syntax of this function is given below.
This function can take five arguments, and the purpose of these arguments is explained below.
The unique() function can return four types of arrays based on the argument values.
The following example shows the use of the unique() function to create an array with the unique values of a one-dimensional array. A one-dimensional array of 9 elements has been used as the unique() function’s argument value. The returned value of this function has printed later.
Output:
The following output will appear after executing the above script. The input array contains 6 unique elements that are shown in the output.
The following example shows how the unique values and indices of the two-dimensional array can be retrieved using the unique() function. A two-dimensional array of 2 rows and 6 columns has been used as the input array. The value of the return_index argument has been set to True to get the input array indices based on the unique array values.
Output:
The following output will appear after executing the above script. The input array contains 7 unique values. The output shows the array of 7 unique values and 7 indices of those values from the input array.
The following example shows how the unique values of a one-dimensional array and the indices based on the unique values by using the unique() function. In the script, a one-dimensional array of 9 elements has used as the input array. The value of the return_inverse argument is set to True that will return another array of indices based on the unique array index. Both unique array and index array have printed later.
Output:
The following output will appear after executing the above script. The output showed the input array, unique array, and inverse array. The input array contains 5 unique values. These are 10, 20, 30, 40, and 60. The input array contains 10 in three indices that are the first element of the unique array. So, 0 has appeared three times in the inverse array. The other values of the inverse array have been placed in the same way.
The following example shows how the unique() function can retrieve the unique values and the frequency of each unique value of the input array. The value of the return_counts argument has been set to True for getting the array of frequency values. A one-dimensional array of 12 elements has been used in the unique() function as an input array. The array of unique values and the frequency values have been printed later.
Output:
The following output will appear after executing the above script. The input array, unique array, and count array have been printed in the output.
The detailed uses of unique() functions have been explained in this tutorial by using multiple examples. This function can return the values of different arrays and have shown here by using one-dimensional and two-dimensional arrays.
]]>When the value of the number changes in each execution of the script, then that number is called a random number. The random numbers are mainly used for the various types of testing and sampling. Many ways exist in Python to generate the random number, and using a random module of the NumPy library is one way to do it. Many functions exist in random module to generate random numbers, such as rand(), randint(), random(), etc. The uses of the random() function of the random module to generate random numbers in Python are shown in this tutorial.
The syntax of the random() function of the random module is given below.
This function can take one optional argument, and the default value of this argument is None. Any integer or the tuple of integers can be given as the argument value that defined the shape of the array that will be returned as the output. If no argument value is provided, then a single floating number will be returned instead of an array. Different uses of the random() function are shown below.
The following example shows the use of random() function without any argument that generates a scalar random number. The returned value of this function is printed later.
Output:
The following output will appear after executing the above script. It shows fractional random numbers.
The following example shows the use of the random() function with an integer in the value of the size argument. Here, 4 is set to the size argument. The means that the random() function will generate an array of four fractional random numbers. The output of the function is printed later.
Output:
The following output will appear after executing the above script. It shows the one-dimensional array of fractional numbers.
The following example shows how the random() function can be used to create a two-dimensional array of fractional random numbers. Here, (2,5) is used as the value of size argument, and the function will return a two-dimensional array of fractional numbers with 2 rows and 5 columns.
Output:
The following output will appear after executing the above script. It shows a two-dimensional array of fractional random numbers.
The following example shows how the random() function can be used to create a three-dimensional array of fractional random numbers. Here, (2,3,4) is used as the value of size argument, and the function will return a three-dimensional array of fractional numbers with 3 rows and 4 columns of 2 times.
Output:
The following output will appear after executing the above script. It shows a three-dimensional array of fractional random numbers.
The following example shows the way to generate coin flips using random numbers. A NumPy array of 10 random fractional numbers has been created using the random() function. heads array has been created with the boolean values by comparing the array values with 0.7. Next, the values of the heads array and the total number of True values in the heads array have been printed.
Output:
The following similar output will appear after executing the script. The different outputs will be generated at different times for random numbers. According to the following output, the total number of True values is 4.
The following example shows the way to generate the plots of a chart using the random() function. Here, the values of the x-axis have been generated using random() and sort() functions. The values of the y-axis have been generated using arange() function. Next, the plot() function of matplotlib.pyplot has been used to draw the plots of the chart. show() function has been used to display the chart.
Output:
The following similar output will appear after executing the above script.
The random() function is a very useful function of Python to perform different types of tasks. Various uses of the random() function have been shown in this tutorial using multiple examples. The purpose of using this function will be cleared for the readers after practicing the examples of this tutorial properly.
]]>