Mastering File Handling in Python and Qt Designer Part 1

Hello everyone! I hope you will be good. Today I am here to participate in the contest of @kouba01 about Mastering File Handling in Python and Qt Designer Part 1. It is really an interesting and knowledgeable contest. There is a lot to explore. If you want to join then:



Join Here: SLC S21 Week 5|| Mastering File Handling in Python and Qt Designer Part 1




Creating Dynamic Interfaces with Python and Qt5 (1).png

Designed with Canva

The program calculates Mersenne numbers within a specified range using PyQt5


image.png

I have used these widgets for the formation of the above GUI:

Label Widgets

  • First label is used to display Mersenne Number.
  • Then I have used a label for A and B.

Input Fields

  • First input field is to get the input from the user for A.
  • The next input field is to get input from the user for B.

Button

  • I have used three pushButton.
  • One button is Mersenne.
  • The other button is Reset.
  • The last button is Display.

Table Widget

  • I have used a tableWidget to display the data in the form of the rows and column.

Setting Custom Names

  • I have set specific name for each widget used in this user interface to manage the working and functionality in the code.


I have used CSS to style the background and colour of the labels.



Helper Functions

is_prime(num)


image.png

  • Purpose: Determines if a number is prime.
  • Logic:
    • Numbers ≤ 1 are not prime.
    • Loops from 2 to the square root of the number, checking divisibility.
    • If divisible, the number is not prime.

calculate_mersenne_numbers(start, end)


image.png

  • Purpose: Calculates Mersenne numbers in a given range.
  • Logic:
    • A Mersenne number has the form M = 2^n - 1, where n is prime.
    • For every prime n, it calculates 2^n - 1.
    • If the result is within the user-specified range [start, end], it is added to the list.
  • Returns: A list of tuples (mersenne_number, n).

Main Class: MersenneApp

This class inherits from QMainWindow and implements the core functionality of the GUI.

__init__ Method


image.png

  • Purpose: Sets up the application.
  • Key Actions:
    • Loads the UI layout from mersenne.ui.
    • Connects buttons to their respective methods:
      • mersenne.clicked: Starts calculation and saves results.
      • reset.clicked: Clears inputs and the table.
      • display.clicked: Loads and displays saved results in the table.

calculate_and_save Method


image.png

  • Purpose: Calculates Mersenne numbers and saves them to a file.
  • Key Steps:
    1. Retrieves user input for the range (a and b).
    2. Validates that 2 < a < b < 50000. If invalid, shows a warning.
    3. Calls calculate_mersenne_numbers to get results.
    4. If results exist:
      • Saves them to mersenne.txt in the format: M = 2^n - 1 = mersenne_number.
      • Shows a success message.
    5. If no results exist, shows an informational message.
  • Error Handling:
    • Catches invalid input errors (ValueError).
    • Handles unexpected errors with a critical message.

display_results Method


image.png

  • Purpose: Reads Mersenne numbers from mersenne.txt and displays them in the table.
  • Key Steps:
    1. Reads lines from mersenne.txt.
    2. Clears the existing rows in the QTableWidget.
    3. Parses each line to extract the Mersenne number (M) and the corresponding n.
    4. Inserts these values as rows in the table.
  • Error Handling:
    • Shows a warning if the file does not exist.
    • Handles unexpected errors with a critical message.

4. reset_inputs Method


image.png

  • Purpose: Clears user inputs and the table.
  • Key Actions:
    • Clears input fields for the range (input_a, input_b).
    • Resets the row count of the table widget to 0.

Features of this Application

  1. Input Validation:
    • Ensures a and b are within the valid range (2 < a < b < 50000).
  2. Calculation:
    • Efficiently calculates Mersenne numbers for prime n.
  3. File Operations:
    • Saves results to mersenne.txt.
    • Reads results for display.
  4. GUI Display:
    • Dynamically populates a table with Mersenne numbers and their corresponding n.
  5. Reset Functionality:
    • Clears all user inputs and output data.

Live Working

Errors Validation:

image.pngimage.png
When the field is emptyWhen the range is not satisfied


image.png

This mersenne.txt file is saving the data.



This program calculates the prime factors of a given number and saves the results in a text file named factors.txt


image.png

I have used these widgets for the formation of the above GUI:

Label Widgets

  • First label is used to display Prime Factors.
  • Then I have used a label for Type a number and Prime Factors.

Input Fields

  • There is one input field to get the input from the user for type a number.

Button

  • I have used three pushButton.
  • One button is Decompose.
  • The other button is Reset.
  • The last button is Display.

Table Widget

  • I have used a tableWidget to display the data in the form of the rows and column.

Setting Custom Names

  • I have set specific name for each widget used in this user interface to manage the working and functionality in the code.


I have used CSS to style the background and colour of the labels.



This application calculates the prime factors of a given number, stores the results in a file (factors.txt) and displays them in a GUI table. Below is a detailed breakdown of the code:

Helper Function

prime_factors(n)

  • Purpose: Computes the prime factors of a number n.
  • Logic:
    1. Initial Setup: Starts with divisor = 2 (the smallest prime).
    2. Looping Process:
      • While n > 1, check if n is divisible by divisor.
      • If divisible, add divisor to the factors list and reduce n by dividing it by divisor.
      • If n is no longer divisible by divisor, increment the divisor by 1 and repeat the process.
    3. Return: The list factors contains the prime factors of n.

Main Class: PrimeFactorsApp

This class inherits from QMainWindow and implements the main functionality of the GUI.

1. __init__ Method


image.png

  • Purpose: Initializes the main window and sets up the user interface.
  • Key Actions:
    • Loads the UI file (primefactors.ui) using loadUi.
    • Connects button clicks to their respective methods:
      • decompose.clicked.connect(self.calculate_factors): Initiates factor calculation when clicked.
      • reset.clicked.connect(self.reset_inputs): Clears the input field and table when clicked.
      • display.clicked.connect(self.display_factors): Displays the calculated factors from the file.

2. calculate_factors Method


image.png

  • Purpose: Calculates the prime factors of a user input and saves the result to a file.
  • Key Actions:
    1. Retrieves the user input (number) from the input field (self.number).
    2. Validates the input:
      • Checks if the input is not empty and is a valid positive integer.
    3. Calls the prime_factors() function to compute the factors.
    4. Formats the factors into a string (factors_str).
    5. Appends the result (number and its prime factors) to factors.txt in the format: number: prime_factors.
    6. Displays a success message to the user (QMessageBox.information).
    7. Clears the input field after the calculation.
  • Error Handling:
    • Shows a warning if the input is invalid (e.g., empty or non-positive).
    • Catches any other unexpected errors with a critical message.

3. reset_inputs Method


image.png

  • Purpose: Clears the input field and resets the table widget.
  • Key Actions:
    • Clears the input field (self.number.clear()).
    • Resets the table row count to 0 (self.table.setRowCount(0)), effectively clearing the table.

4. display_factors Method

image.png

  • Purpose: Reads the contents of factors.txt and displays the results in the table.
  • Key Actions:
    1. Opens and reads the factors.txt file.
    2. Clears any existing data in the table (self.table.setRowCount(0)).
    3. Iterates over each line in the file:
      • Splits the line at the first colon (:) to separate the number from its prime factors.
      • Adds the number and factors to a new row in the table.
    4. If the file is not found, displays a warning message (QMessageBox.warning).
    5. Catches any unexpected errors with a critical message.

Features of Application

  1. Input Validation:
    • Ensures that the input is a positive integer.
  2. Prime Factor Calculation:
    • Efficiently calculates the prime factors using trial division.
  3. File Operations:
    • Appends results to factors.txt.
    • Reads and displays saved results from the file.
  4. GUI Table Display:
    • Dynamically populates a table with calculated prime factors.
  5. Reset Functionality:
    • Clears inputs and output data.

User Flow

  1. Input: User enters a number in the input field.
  2. Calculate: User clicks the "Decompose" button to calculate prime factors.
  3. Display: Results are saved to a file and shown in a table when the "Display" button is clicked.
  4. Reset: User can clear the input and reset the table.

Live Working

Errors Validation:

image.png

When the input field is empty then this error is displayed.


image.png

Here you can see the text filefactors.txt where the calculated prime factors of the number are being saved and then the application can fetch and display these prime factors.



This program is designed to validate 13-digit codes based on specific criteria and manage them using a file named Codes.txt

image.png

I have used these widgets for the formation of the above GUI:

Label Widgets

  • First label is used to display Recharge Codes.
  • Then I have used a label for Enter your Code.

Input Fields

  • There is one input field to get the input from the user for Enter your Code.
  • And another field to display the status of the code.
  • At the end there is a field to display the output results.

Button

  • I have used four pushButton.
  • One button is Verify.
  • The other button is Reset.
  • The next button is Close.
  • The last button is Display Codes.

Radio Button

  • I have used a radioButton to display the codes in the descending order.

Setting Custom Names

  • I have set specific name for each widget used in this user interface to manage the working and functionality in the code.


I have used CSS to style the background and colour of the labels.



This is a PyQt5-based application that verifies, saves, displays and validates codes. The codes are validated based on a specific set of criteria and are stored in a file (Codes.txt). The application also allows users to view the codes in descending order. The user can reset input fields and handle code verification and saving.

Constants

  • FILE_NAME: Specifies the name of the file where codes will be stored (Codes.txt).

Helper Functions

  1. is_prime(number):


    image.png

    • Purpose: Checks if a given number is prime.
    • Logic:
      • If the number is less than 2, it's not prime.
      • It checks divisibility from 2 up to the square root of the number (int(number ** 0.5) + 1), ensuring efficient prime checking.
  2. validate_code(code):


    image.png

    • Purpose: Validates the code input based on three criteria:
      1. The code must be exactly 13 digits long.
      2. The first three digits must be prime.
      3. The middle five digits, when converted to binary, must contain more than eight zeros.
      4. The last five digits must be divisible by the first three digits.
    • Validation Logic:
      • First three digits: Checks if the number formed by the first three digits is prime using is_prime().
      • Middle five digits: Converts the middle five digits to binary and checks if there are more than 8 zeros in the binary representation.
      • Last five digits: Checks if the last five digits are divisible by the first three digits.
  3. load_codes():


    image.png

    • Purpose: Loads the stored codes from Codes.txt.
    • Logic: Reads the file line by line and returns the list of codes.
  4. save_code(code):


    image.png

    • Purpose: Saves a valid code to Codes.txt.
    • Logic: Appends the new code to the file.

Main Class: RechargeApp

The RechargeApp class handles the core logic and interaction between the PyQt5 interface and the backend functions.

  1. __init__(self):


    image.png

    • Purpose: Initializes the application and the UI.
    • Logic:
      • Loads the UI (recharge.ui) using uic.loadUi.
      • Connects UI elements (buttons, radio buttons) to their respective functions using .clicked.connect or .isChecked().
  2. verify_code(self):


    image.png

    • Purpose: Verifies the code entered by the user.
    • Logic:
      • Retrieves the code from the input field (self.window.code.text()).
      • Validates the code using the validate_code() function.
      • If valid, checks if the code is already in use by searching in the existing codes.
      • If the code isn't already used, it is saved to Codes.txt.
      • Displays appropriate messages in the UI (self.window.warning.setText or self.window.output.setText).
  3. display_codes(self):


    image.png

    • Purpose: Displays all the stored codes in either ascending or descending order based on the user's preference.
    • Logic:
      • Loads all stored codes using load_codes().
      • Sorts the codes either in ascending or descending order based on the desorder radio button.
      • Displays the sorted codes in the output area.
      • If no codes are found, a message box is shown with the text "No codes stored."
  4. reset_fields(self):


    image.png

    • Purpose: Clears all the input and output fields.
    • Logic: Clears the text fields for code input, warning messages, and output area.
  5. run(self):


    image.png

    • Purpose: Starts and runs the application.
    • Logic: Shows the main window and starts the PyQt application event loop (self.app.exec()).

Main Application Flow

  1. Code Verification:

    • The user enters a code and clicks the Verify button.
    • The code is validated based on the criteria (prime, binary zeros, divisibility).
    • If valid, it checks if the code is already in use. If not, it is saved.
  2. Display Codes:

    • The user clicks Display to view all the stored codes, sorted by the selected order (ascending or descending).
  3. Reset Fields:

    • The user can click Reset to clear all fields (input and output).
  4. Close Application:

    • The user can click Close to exit the application.

Features of Application

  • Code Validation: Ensures that entered codes meet specific criteria.
  • Code Storage: Codes are stored in a text file (Codes.txt) for later access.
  • Sorting: Users can choose to view codes in ascending or descending order.
  • UI Interaction: Allows users to verify, display, and reset codes with user-friendly feedback.


image.png

Here you can see the text filecodes.txt where the codes are being saved and then the application can fetch and display these codes.



This program identifies Smith numbers within a user-defined range through a graphical user interface.


image.png

I have used these widgets for the formation of the above GUI:

Label Widgets

  • First label is used to display header_image.
  • Then I have used a label for Finding Smith numbers in the interval [a,b]; as a hint for the user.
  • Then there is a label for Terminal a (integer>=4) and Terminal b (integer>=a).

Input Fields

  • There are total of three input fields and two are to get the input from the user for Terminal a (integer>=4) and Terminal b (integer>=a) respectively.
  • The last input field has been used to display the dynamic output results.

Button

  • I have used three pushButton.
  • One button is Find.
  • The other button is Reset.
  • The last button is Close.

Setting Custom Names

  • I have set specific name for each widget used in this user interface to manage the working and functionality in the code.


I have used CSS to style the background and colour of the labels.



The Python script whivh I have used is a PyQt5 application that lets users find Smith numbers within a specified range. Here's an explanation of the code:


image.png

  1. Constants:
    • FILE_NAME: The name of the file where Smith numbers will be saved.
    • HEADER_IMAGE_PATH and SIDE_IMAGE_PATH: File paths for images displayed in the UI.

Mathematical Helper Functions

These functions implement the logic for Smith numbers:

  1. is_prime(n):


    image.png

    • Checks if a number n is prime.
    • Prime numbers are ignored when finding Smith numbers.
  2. prime_factors(n):


    image.png

    • Finds and returns all prime factors of n.
  3. sum_of_digits(n):


    image.png

    • Computes the sum of the digits of a number n.
    • Used to compare the sum of a number's digits with the sum of the digits of its prime factors.
  4. is_smith_number(n):


    image.png

    • Determines if n is a Smith number.
    • Smith numbers are composite numbers where the sum of their digits equals the sum of the digits of their prime factors.
  5. find_smith_numbers(start, end):


    image.png

    • Returns a list of Smith numbers within the range [start, end].

SmithNumberApp Class

This class implements the PyQt5 application logic:

  1. Initialization:


    image.png

    • Creates the application (QApplication) and loads the user interface from the smithnumbers.ui file.
    • Connects buttons in the UI (find, reset, close_button) to their corresponding logic.
  2. load_images Method:


    image.png

    • Loads images for the header and side sections of the UI using QPixmap.
    • Scales the images to fit their respective labels.
    • Displays warnings if the images are not found.
  3. process_range Method:


    image.png

    • Reads user input for the range [a, b] from text fields.
    • Validates the range:
      • a must be at least 4 (Smith numbers start at 4).
      • b must be greater than or equal to a.
    • Finds Smith numbers in the range using find_smith_numbers.
    • Saves the results to SmithNumbers.txt.
    • Displays the Smith numbers in the output field or a message if none are found.
  4. reset_fields Method:


    image.png

    • Clears all input and output fields in the UI.
  5. run Method:


    image.png

    • Displays the main window and starts the application loop.

Main Execution

  • The program instantiates SmithNumberApp and calls its run method to start the application.

Example Usage

  1. User enters a range such as a=4 and b=100.
  2. The application checks the range and finds all Smith numbers between 4 and 100.
  3. Results are displayed in the output field and saved to SmithNumbers.txt.
  4. Users can reset the input fields using the "Reset" button or close the app using the "Close" button.


image.png

Here you can see the text filesmithnumbers.txt where the smith numbers are being saved for a = 4 and b= 500.



I would like to invite @heriadi, @chant and @jospeha to join this contest.

Sort:  
Loading...