Advertisement
Python253

parity_number_counter

Mar 12th, 2024 (edited)
836
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.97 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: parity_number_counter.py
  4. # Version: 1.0.2
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. This script counts the parity of numbers based on user input or file input.
  9.  
  10. **Included Stand-Alone Modules**:
  11.  
  12. - 'create_example_txt'  --  https://pastebin.com/fF1Uhj63
  13. - 'create_example_csv'  --  https://pastebin.com/vencCaYU
  14. - 'create_example_json'  --  https://pastebin.com/CDG0mY3V
  15.  
  16. Options:
  17. 1. Manual Input: Allows the user to enter numbers manually until 0 is entered.
  18. 2. CSV File: Reads numbers from a CSV file.
  19. 3. TXT File: Reads numbers from a TXT file.
  20. 4. JSON File: Reads numbers from a JSON file.
  21. 0. Exit: Exits the program.
  22.  
  23. The script calculates and displays the count of even and odd numbers and saves the results to a dynamically named text file.
  24.  
  25. Output File Naming:
  26. - Manual Input: manual_output.txt
  27. - CSV File: csv_output.txt
  28. - TXT File: txt_output.txt
  29. - JSON File: json_output.txt
  30. """
  31.  
  32. import json
  33. import csv
  34.  
  35. def get_user_input():
  36.     """
  37.    Get user input for numbers.
  38.    """
  39.     while True:
  40.         try:
  41.             user_input = int(input("Enter a number (enter 0 to stop): "))
  42.             return user_input
  43.         except ValueError:
  44.             print("Invalid input. Please enter a valid integer.")
  45.  
  46. def create_example_text(filename):
  47.     """
  48.    Create an example TXT file with predefined data.
  49.    Note: Each number must be on a separate line or it will not function properly
  50.    """
  51.     text_data = """1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20
  52. 21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40
  53. 41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60
  54. 61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80
  55. 81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99  100
  56. """
  57.  
  58.     with open(filename, 'w') as textfile:
  59.         textfile.write(text_data)
  60.  
  61. def create_example_csv(filename):
  62.     """
  63.    Create an example CSV file with predefined data.
  64.    """
  65.     data = [
  66.         ['Name', 'Age', 'City'],
  67.         ['John Doe', 25, 'New York'],
  68.         ['Jane Smith', 30, 'San Francisco'],
  69.         ['Bob Johnson', 22, 'Los Angeles']
  70.     ]
  71.  
  72.     with open(filename, 'w', newline='') as csvfile:
  73.         csvwriter = csv.writer(csvfile)
  74.         csvwriter.writerows(data)
  75.  
  76. def create_example_json(filename):
  77.     """
  78.    Create an example JSON file with predefined data.
  79.    """
  80.     example_data = [
  81.         {
  82.             "name": "John Doe",
  83.             "age": 30,
  84.             "city": "New York",
  85.             "interests": ["reading", "traveling", "coding"]
  86.         },
  87.         {
  88.             "name": "Jane Smith",
  89.             "age": 25,
  90.             "city": "Los Angeles",
  91.             "interests": ["hiking", "photography", "music"]
  92.         }
  93.     ]
  94.  
  95.     with open(filename, 'w') as jsonfile:
  96.         json.dump(example_data, jsonfile, indent=2)
  97.  
  98. def txt_input(filename):
  99.     """
  100.    Read numbers from a TXT file.
  101.    Note: Each number must be on a separate line or it will not function properly
  102.    """
  103.     if not filename:
  104.         filename = 'manual_output.txt'
  105.         create_example_text(filename)
  106.         print(f"Created example text file '{filename}'.")
  107.        
  108.     with open(filename, 'r') as txtfile:
  109.         numbers = [int(num) for line in txtfile for num in line.split()]
  110.  
  111.     print("\nParity in the TXT file:")
  112.     print(numbers)
  113.     return numbers
  114.  
  115. def csv_input(filename):
  116.     """
  117.    Read numbers from a CSV file.
  118.    """
  119.     with open(filename, 'r') as csvfile:
  120.         csvreader = csv.reader(csvfile)
  121.         next(csvreader)  # Skip the header row
  122.         numbers = [int(row[1]) for row in csvreader]
  123.  
  124.     print("\nParity in the CSV file:")
  125.     print(numbers)
  126.     return numbers
  127.  
  128. def json_input(filename):
  129.     """
  130.    Read numbers from a JSON file.
  131.    """
  132.     with open(filename, 'r') as jsonfile:
  133.         data = json.load(jsonfile)
  134.         numbers = []
  135.  
  136.         for person in data:
  137.             for key, value in person.items():
  138.                 if isinstance(value, (int, float)):
  139.                     numbers.append(value)
  140.  
  141.         print("\nParity in the JSON file:")
  142.         print(numbers)
  143.         return numbers
  144.  
  145. def create_output_filename(extension, choice):
  146.     """
  147.    Create the output filename based on the option type.
  148.    """
  149.     option_types = {
  150.         1: 'manual',
  151.         2: 'csv',
  152.         3: 'txt',
  153.         4: 'json'
  154.     }
  155.  
  156.     return f"{option_types.get(choice, 'unknown')}_output.{extension}"
  157.  
  158. def main():
  159.     """
  160.    Main function for the Parity Number Counter program.
  161.    """
  162.     print("Welcome to the Parity Number Counter Program!")
  163.  
  164.     while True:
  165.         # Get user choice
  166.         print("\nOptions:")
  167.         print("1. Manual Input")
  168.         print("2. CSV File")
  169.         print("3. TXT File")
  170.         print("4. JSON File")
  171.         print("0. Exit")
  172.  
  173.         choice = int(input("Enter your choice: "))
  174.  
  175.         if choice == 1:
  176.             numbers = []
  177.             while True:
  178.                 number = get_user_input()
  179.                 print(f"User entered: {number}")
  180.                 if number == 0:
  181.                     break
  182.                 numbers.append(number)
  183.         elif choice == 2:
  184.             filename = input("Enter the CSV filename (press Enter for 'csv_output.txt'): ")
  185.             if not filename:
  186.                 filename = 'csv_output.txt'
  187.                 create_example_csv(filename)
  188.             numbers = csv_input(filename)
  189.         elif choice == 3:
  190.             filename = input("Enter the TXT filename (press Enter for 'txt_output.txt'): ")
  191.             if not filename:
  192.                 filename = 'txt_output.txt'
  193.                 create_example_text(filename)
  194.             numbers = txt_input(filename)
  195.         elif choice == 4:
  196.             filename = input("Enter the JSON filename (press Enter for 'json_output.txt'): ")
  197.             if not filename:
  198.                 filename = 'json_output.txt'
  199.                 create_example_json(filename)
  200.             numbers = json_input(filename)
  201.         elif choice == 0:
  202.             print("Exiting the program.")
  203.             break
  204.         else:
  205.             print("Invalid choice. Please choose a valid option.")
  206.  
  207.         # Process numbers
  208.         even_count = sum(1 for num in numbers if num % 2 == 0)
  209.         odd_count = len(numbers) - even_count
  210.  
  211.         # Display results
  212.         print("\nResults:\n")
  213.         print(f"Even numbers entered: {even_count}")
  214.         print(f"Odd numbers entered: {odd_count}")
  215.         print("\nThank you for using the program!\n")
  216.  
  217.         # Write results to a text file
  218.         output_filename = create_output_filename('txt', choice)
  219.         with open(output_filename, "w") as text_file:
  220.             text_file.write(f"User inputs: {numbers}\n")
  221.             text_file.write(f"Even numbers entered: {even_count}\n")
  222.             text_file.write(f"Odd numbers entered: {odd_count}\n")
  223.  
  224. if __name__ == "__main__":
  225.     main()
  226.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement