Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- # Filename: parity_number_counter.py
- # Version: 1.0.2
- # Author: Jeoi Reqi
- """
- This script counts the parity of numbers based on user input or file input.
- **Included Stand-Alone Modules**:
- - 'create_example_txt' -- https://pastebin.com/fF1Uhj63
- - 'create_example_csv' -- https://pastebin.com/vencCaYU
- - 'create_example_json' -- https://pastebin.com/CDG0mY3V
- Options:
- 1. Manual Input: Allows the user to enter numbers manually until 0 is entered.
- 2. CSV File: Reads numbers from a CSV file.
- 3. TXT File: Reads numbers from a TXT file.
- 4. JSON File: Reads numbers from a JSON file.
- 0. Exit: Exits the program.
- The script calculates and displays the count of even and odd numbers and saves the results to a dynamically named text file.
- Output File Naming:
- - Manual Input: manual_output.txt
- - CSV File: csv_output.txt
- - TXT File: txt_output.txt
- - JSON File: json_output.txt
- """
- import json
- import csv
- def get_user_input():
- """
- Get user input for numbers.
- """
- while True:
- try:
- user_input = int(input("Enter a number (enter 0 to stop): "))
- return user_input
- except ValueError:
- print("Invalid input. Please enter a valid integer.")
- def create_example_text(filename):
- """
- Create an example TXT file with predefined data.
- Note: Each number must be on a separate line or it will not function properly
- """
- text_data = """1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
- 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
- 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
- 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
- 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
- """
- with open(filename, 'w') as textfile:
- textfile.write(text_data)
- def create_example_csv(filename):
- """
- Create an example CSV file with predefined data.
- """
- data = [
- ['Name', 'Age', 'City'],
- ['John Doe', 25, 'New York'],
- ['Jane Smith', 30, 'San Francisco'],
- ['Bob Johnson', 22, 'Los Angeles']
- ]
- with open(filename, 'w', newline='') as csvfile:
- csvwriter = csv.writer(csvfile)
- csvwriter.writerows(data)
- def create_example_json(filename):
- """
- Create an example JSON file with predefined data.
- """
- example_data = [
- {
- "name": "John Doe",
- "age": 30,
- "city": "New York",
- "interests": ["reading", "traveling", "coding"]
- },
- {
- "name": "Jane Smith",
- "age": 25,
- "city": "Los Angeles",
- "interests": ["hiking", "photography", "music"]
- }
- ]
- with open(filename, 'w') as jsonfile:
- json.dump(example_data, jsonfile, indent=2)
- def txt_input(filename):
- """
- Read numbers from a TXT file.
- Note: Each number must be on a separate line or it will not function properly
- """
- if not filename:
- filename = 'manual_output.txt'
- create_example_text(filename)
- print(f"Created example text file '{filename}'.")
- with open(filename, 'r') as txtfile:
- numbers = [int(num) for line in txtfile for num in line.split()]
- print("\nParity in the TXT file:")
- print(numbers)
- return numbers
- def csv_input(filename):
- """
- Read numbers from a CSV file.
- """
- with open(filename, 'r') as csvfile:
- csvreader = csv.reader(csvfile)
- next(csvreader) # Skip the header row
- numbers = [int(row[1]) for row in csvreader]
- print("\nParity in the CSV file:")
- print(numbers)
- return numbers
- def json_input(filename):
- """
- Read numbers from a JSON file.
- """
- with open(filename, 'r') as jsonfile:
- data = json.load(jsonfile)
- numbers = []
- for person in data:
- for key, value in person.items():
- if isinstance(value, (int, float)):
- numbers.append(value)
- print("\nParity in the JSON file:")
- print(numbers)
- return numbers
- def create_output_filename(extension, choice):
- """
- Create the output filename based on the option type.
- """
- option_types = {
- 1: 'manual',
- 2: 'csv',
- 3: 'txt',
- 4: 'json'
- }
- return f"{option_types.get(choice, 'unknown')}_output.{extension}"
- def main():
- """
- Main function for the Parity Number Counter program.
- """
- print("Welcome to the Parity Number Counter Program!")
- while True:
- # Get user choice
- print("\nOptions:")
- print("1. Manual Input")
- print("2. CSV File")
- print("3. TXT File")
- print("4. JSON File")
- print("0. Exit")
- choice = int(input("Enter your choice: "))
- if choice == 1:
- numbers = []
- while True:
- number = get_user_input()
- print(f"User entered: {number}")
- if number == 0:
- break
- numbers.append(number)
- elif choice == 2:
- filename = input("Enter the CSV filename (press Enter for 'csv_output.txt'): ")
- if not filename:
- filename = 'csv_output.txt'
- create_example_csv(filename)
- numbers = csv_input(filename)
- elif choice == 3:
- filename = input("Enter the TXT filename (press Enter for 'txt_output.txt'): ")
- if not filename:
- filename = 'txt_output.txt'
- create_example_text(filename)
- numbers = txt_input(filename)
- elif choice == 4:
- filename = input("Enter the JSON filename (press Enter for 'json_output.txt'): ")
- if not filename:
- filename = 'json_output.txt'
- create_example_json(filename)
- numbers = json_input(filename)
- elif choice == 0:
- print("Exiting the program.")
- break
- else:
- print("Invalid choice. Please choose a valid option.")
- # Process numbers
- even_count = sum(1 for num in numbers if num % 2 == 0)
- odd_count = len(numbers) - even_count
- # Display results
- print("\nResults:\n")
- print(f"Even numbers entered: {even_count}")
- print(f"Odd numbers entered: {odd_count}")
- print("\nThank you for using the program!\n")
- # Write results to a text file
- output_filename = create_output_filename('txt', choice)
- with open(output_filename, "w") as text_file:
- text_file.write(f"User inputs: {numbers}\n")
- text_file.write(f"Even numbers entered: {even_count}\n")
- text_file.write(f"Odd numbers entered: {odd_count}\n")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement