Starexx Documentation
Starexx is a comprehensive utility library for Python that provides simplified functions for common programming tasks, mathematical operations, file handling, text processing, and system utilities. It's designed to make Python programming more accessible and efficient.
The library offers a clean, intuitive API that reduces boilerplate code and handles common edge cases automatically.
Installation
Starexx is a single Python file that can be directly imported into your projects. No package installation required.
Basic Import
from starexx import *
Import all functions from the library for direct access without prefixes.
Import Methods
Starexx supports multiple import patterns to suit different coding styles and needs.
Method 1: Import All Functions
from starexx import *
# Usage
say("Hello World")
result = add(5, 3)
showTime()
Import everything - convenient for small scripts but may cause naming conflicts in larger projects.
Method 2: Import Specific Functions
from starexx import say, ask, add, multiply
# Usage
say("Hello World")
result = add(5, 3)
name = ask("What's your name?")
Import only what you need - reduces memory usage and improves readability.
Method 3: Import Entire Module
import starexx
# Usage
starexx.say("Hello World")
result = starexx.add(5, 3)
Explicit namespace - prevents naming conflicts, recommended for larger projects.
Quick Start
Get started quickly with these basic examples that demonstrate common use cases.
Basic Usage Examples
from starexx import *
# Basic output and input
say("Hello", "World!", "Welcome to Starexx")
name = ask("What's your name?")
# Math operations
result = add(5, 3)
average = average(10, 20, 30, 40, 50)
# File handling
writeFile("greeting.txt", f"Hello {name}!")
content = readFile("greeting.txt")
# Text processing
reversed_text = reverseText("hello")
upper_text = toUpper("hello world")
# Time utilities
showTime()
countdown(3) # 3-second countdown
This example shows the basic workflow: import the library, use input/output functions, perform calculations, handle files, process text, and use time utilities.
Output & Input Functions
Functions for console output and user input handling with automatic formatting and validation.
say() Function
from starexx import *
# Print multiple messages with automatic spacing
say("Hello", "World!", "How are you?")
# Output: Hello World! How are you?
# Print variables and text
name = "Alice"
age = 25
say("Name:", name, "Age:", age)
# Output: Name: Alice Age: 25
# Print lists and other objects
numbers = [1, 2, 3, 4, 5]
say("Numbers:", numbers)
# Output: Numbers: [1, 2, 3, 4, 5]
The say()
function automatically converts all arguments to strings and joins them with spaces. It handles any number of arguments and works with all data types.
ask() Function
from starexx import *
# Basic input with prompt
name = ask("What is your name?")
print(f"Hello, {name}!")
# Numeric input (requires conversion)
age_input = ask("How old are you?")
age = int(age_input) # Convert to integer
# Multiple inputs in sequence
city = ask("Which city do you live in?")
country = ask("Which country?")
say(f"Location: {city}, {country}")
The ask()
function displays a prompt and returns user input as a string. For numeric input, you need to convert the returned string to the appropriate type.
Mathematical Operations
Comprehensive mathematical functions including basic arithmetic, advanced calculations, and number utilities.
Basic Arithmetic
from starexx import *
# Addition
result = add(5, 3) # Returns: 8
result = add(2.5, 3.7) # Returns: 6.2
# Subtraction
result = subtract(10, 4) # Returns: 6
result = subtract(5.5, 2.2) # Returns: 3.3
# Multiplication
result = multiply(3, 7) # Returns: 21
result = multiply(2.5, 4) # Returns: 10.0
# Division with zero handling
result = divide(15, 3) # Returns: 5.0
result = divide(10, 4) # Returns: 2.5
result = divide(5, 0) # Returns: "Cannot divide by zero"
# Practical example
price = 100
tax_rate = 0.18
tax_amount = multiply(price, tax_rate)
total = add(price, tax_amount)
say(f"Total with tax: {total}")
Basic arithmetic functions that handle both integers and floats. Division includes automatic zero-division protection.
Advanced Math Functions
from starexx import *
# Exponentiation
square = square(5) # Returns: 25
cube = cube(3) # Returns: 27
power = power(2, 8) # Returns: 256
# Roots
sqrt = sqrt(16) # Returns: 4.0
sqrt = sqrt(2) # Returns: 1.4142135623730951
# Statistical functions
avg = average(10, 20, 30, 40, 50) # Returns: 30.0
max_val = maximum(4, 2, 8, 1, 9) # Returns: 9
min_val = minimum(4, 2, 8, 1, 9) # Returns: 1
total = total([1, 2, 3, 4, 5]) # Returns: 15
# Percentage calculation
percentage = percentage(25, 100) # Returns: 25.0
percentage = percentage(15, 200) # Returns: 7.5
# Practical example: Student grades
grades = [85, 92, 78, 96, 88]
average_grade = average(*grades)
highest_grade = maximum(*grades)
lowest_grade = minimum(*grades)
say(f"Average: {average_grade}, Highest: {highest_grade}, Lowest: {lowest_grade}")
Advanced mathematical functions for exponents, roots, statistics, and percentages. Note the use of *
to unpack lists when using variable arguments.
Number Utilities
from starexx import *
# Parity checking
print(isEven(4)) # Returns: True
print(isEven(7)) # Returns: False
print(isOdd(4)) # Returns: False
print(isOdd(7)) # Returns: True
# Rounding and absolute values
print(roundNumber(3.14159, 2)) # Returns: 3.14
print(floorNumber(3.7)) # Returns: 3
print(ceilingNumber(3.2)) # Returns: 4
print(absoluteValue(-5)) # Returns: 5
# Number properties
print(isPrime(17)) # Returns: True
print(isPrime(15)) # Returns: False
print(factorial(5)) # Returns: 120
# Sequences
fib_sequence = fibonacci(8) # Returns: [0, 1, 1, 2, 3, 5, 8, 13]
# Practical example: Number analysis
number = 29
say(f"{number} is even: {isEven(number)}")
say(f"{number} is prime: {isPrime(number)}")
say(f"Factorial of 5: {factorial(5)}")
say(f"First 10 Fibonacci numbers: {fibonacci(10)}")
Utility functions for number analysis including parity checking, rounding, prime detection, factorials, and Fibonacci sequence generation.
Text Processing
Comprehensive text manipulation functions for string operations, formatting, and analysis.
String Operations
from starexx import *
text = "hello world, how are you?"
# Splitting and joining
words = splitText(text, " ")
# Returns: ['hello', 'world,', 'how', 'are', 'you?']
joined = joinText(['a', 'b', 'c'], '-')
# Returns: 'a-b-c'
# Reversal and length
reversed_text = reverseText("hello")
# Returns: 'olleh'
length = textLength("hello")
# Returns: 5
# Case conversion
upper_text = toUpper(text)
# Returns: 'HELLO WORLD, HOW ARE YOU?'
lower_text = toLower("HELLO World")
# Returns: 'hello world'
capitalized = capitalizeText("hello")
# Returns: 'Hello'
title_text = titleText("hello world")
# Returns: 'Hello World'
# Practical example: Text normalization
user_input = " HELLO WORLD "
clean_text = trimText(user_input)
normalized = toLower(clean_text)
title_case = titleText(normalized)
say(f"Original: '{user_input}'")
say(f"Normalized: '{title_case}'")
Basic string operations including splitting, joining, case conversion, and text normalization. Essential for cleaning and processing user input.
Text Manipulation & Search
from starexx import *
text = "The quick brown fox jumps over the lazy dog"
# Replacement
new_text = replaceText("hello", "l", "x")
# Returns: 'hexxo'
new_text = replaceText(text, "fox", "cat")
# Returns: 'The quick brown cat jumps over the lazy dog'
# Trimming whitespace
trimmed = trimText(" hello ")
# Returns: 'hello'
# Search operations
starts = startsWith("hello", "he")
# Returns: True
ends = endsWith("hello", "lo")
# Returns: True
position = findText("hello", "ll")
# Returns: 2 (index where 'll' starts)
count = countText("hello", "l")
# Returns: 2
# Practical example: Text analysis
document = "Python is great. Python is powerful. Python is easy."
python_count = countText(document, "Python")
starts_with_python = startsWith(document, "Python")
ends_with_easy = endsWith(document, "easy.")
say(f"Document: {document}")
say(f"'Python' appears {python_count} times")
say(f"Starts with 'Python': {starts_with_python}")
say(f"Ends with 'easy.': {ends_with_easy}")
Advanced text manipulation including search, replace, and analysis functions. Useful for document processing and text mining.
File Operations
Complete file handling utilities for reading, writing, and managing files and directories.
Basic File Handling
from starexx import *
# Write to file
writeFile("example.txt", "Hello World!")
# Creates or overwrites example.txt with "Hello World!"
# Read from file
content = readFile("example.txt")
say(content) # Output: Hello World!
# Append to file
appendFile("example.txt", "\nThis is a new line")
# File now contains:
# Hello World!
# This is a new line
# Check if file exists
if fileExists("example.txt"):
say("File exists!")
else:
say("File not found!")
# Delete file
if deleteFile("example.txt"):
say("File deleted successfully")
else:
say("File deletion failed or file doesn't exist")
# Practical example: Logging system
log_message = "User logged in at " + showTime()
appendFile("app.log", log_message + "\n")
Basic file operations for creating, reading, updating, and deleting files. Includes automatic error handling for file operations.
File System Operations
from starexx import *
# List files in current directory
files = listFiles()
say("Files in current directory:", files)
# List files in specific directory
files = listFiles("/path/to/directory")
# Get current working directory
current_dir = getCurrentFolder()
say("Current folder:", current_dir)
# Change directory
changeFolder("/path/to/new/directory")
# Create directory
createFolder("new_folder")
# Check path types
if isFile("example.txt"):
say("This is a file")
if isFolder("new_folder"):
say("This is a directory")
# Get file size
size = fileSize("example.txt")
say(f"File size: {size} bytes")
# Practical example: Directory scanner
def scan_directory(path="."):
say(f"Scanning: {path}")
items = listFiles(path)
for item in items:
full_path = f"{path}/{item}"
if isFile(full_path):
size = fileSize(full_path)
say(f"File: {item} ({size} bytes)")
elif isFolder(full_path):
say(f"Folder: {item}")
scan_directory()
File system operations for directory navigation, listing contents, creating folders, and checking file properties.
Data Structures
Utilities for working with Python's core data structures - lists and dictionaries.
List Operations
from starexx import *
# Create lists
my_list = createList(1, 2, 3, 2, 4, 3)
say("Original list:", my_list)
# Output: Original list: [1, 2, 3, 2, 4, 3]
# Remove duplicates
unique_list = makeUnique(my_list)
say("Unique list:", unique_list)
# Output: Unique list: [1, 2, 3, 4]
# Sort lists
sorted_list = sortItems(my_list)
say("Sorted list:", sorted_list)
# Output: Sorted list: [1, 2, 2, 3, 3, 4]
# Search in lists
exists = findInList(3, my_list)
say("Is 3 in list?", exists)
# Output: Is 3 in list? True
# Count occurrences
count = countInList(2, my_list)
say("Count of 2:", count)
# Output: Count of 2: 2
# Practical example: Student management
students = createList("Alice", "Bob", "Charlie", "Alice")
unique_students = makeUnique(students)
sorted_students = sortItems(unique_students)
say("All students:", students)
say("Unique students:", unique_students)
say("Sorted students:", sorted_students)
say("Is David enrolled?", findInList("David", students))
List manipulation functions for creating, deduplicating, sorting, searching, and counting elements in lists.
Dictionary Operations
from starexx import *
# Create dictionary
person = createDict(name="John", age=30, city="New York")
say("Person:", person)
# Output: Person: {'name': 'John', 'age': 30, 'city': 'New York'}
# Get keys and values
keys = getKeys(person)
values = getValues(person)
say("Keys:", keys) # Output: Keys: ['name', 'age', 'city']
say("Values:", values) # Output: Values: ['John', 30, 'New York']
# Add to dictionary
addToDict(person, "job", "Developer")
say("After adding job:", person)
# Output: After adding job: {'name': 'John', 'age': 30, 'city': 'New York', 'job': 'Developer'}
# Remove from dictionary
removeFromDict(person, "city")
say("After removing city:", person)
# Output: After removing city: {'name': 'John', 'age': 30, 'job': 'Developer'}
# Merge dictionaries
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = mergeDicts(dict1, dict2)
say("Merged dictionary:", merged)
# Output: Merged dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Practical example: User profile management
user_profile = createDict(
username="johndoe",
email="john@example.com",
preferences=createDict(theme="dark", language="en")
)
addToDict(user_profile, "last_login", "2024-01-15")
say("User profile:", user_profile)
say("Profile keys:", getKeys(user_profile))
Dictionary operations for creating, modifying, merging, and extracting data from dictionaries. Essential for configuration management and data storage.
Time & Date Functions
Time and date utilities for displaying current time, creating timers, and measuring execution time.
Time Functions
from starexx import *
# Display current time and date
showTime() # Output: 14:30:25 (current time)
showDate() # Output: 2024-01-15 (current date)
# Wait for specified seconds
say("Starting wait...")
wait(2) # Pauses execution for 2 seconds
say("Wait complete!")
# Countdown timer
say("Starting countdown:")
countdown(5) # Counts down from 5 to 1
# Output:
# 5
# 4
# 3
# 2
# 1
# Time's up!
# Performance timing
start_time = timerStart()
# Simulate some work
wait(1)
elapsed = timerStop(start_time)
say(f"Operation took {elapsed:.2f} seconds")
# Measure function execution time
def expensive_operation():
wait(0.5)
return "Done"
result = measureTime(expensive_operation)
# Output: Time taken: 0.50 seconds
# Practical example: Execution timer
def process_data():
say("Processing data...")
wait(1.5) # Simulate processing time
return "Processing complete"
say("Starting data processing")
result = measureTime(process_data)
say(f"Result: {result}")
Time utilities for displaying current time, creating delays, countdown timers, and performance measurement. Essential for timing operations and creating time-based functionality.
Web Utilities
Functions for web-related tasks including opening URLs and performing web searches.
from starexx import *
# Open websites in default browser
openWebsite("https://www.google.com")
# Opens Google in your default web browser
openWebsite("https://www.github.com")
# Opens GitHub in your default web browser
# Search the web
searchWeb("Python programming")
# Opens Google search for "Python programming"
searchWeb("Starexx library documentation")
# Opens Google search for "Starexx library documentation"
# Practical example: Quick reference tool
def quick_search(topic):
say(f"Searching for: {topic}")
searchWeb(topic)
# Usage examples
quick_search("Python list comprehension")
quick_search("JavaScript array methods")
quick_search("Machine learning tutorials")
# Combined with user input
search_query = ask("What would you like to search for?")
if search_query:
searchWeb(search_query)
else:
say("No search query provided")
Web utilities for opening URLs and performing web searches directly from your Python code. These functions use the system's default web browser.
Unit Conversion
Utility functions for converting between different units of measurement.
from starexx import *
# Temperature conversion
celsius = 0
fahrenheit = convertCtoF(celsius)
say(f"{celsius}°C = {fahrenheit}°F") # Output: 0°C = 32.0°F
fahrenheit = 32
celsius = convertFtoC(fahrenheit)
say(f"{fahrenheit}°F = {celsius}°C") # Output: 32°F = 0.0°C
# Distance conversion
kilometers = 10
miles = convertKMtoMiles(kilometers)
say(f"{kilometers} km = {miles} miles") # Output: 10 km = 6.21371 miles
miles = 10
kilometers = convertMilesToKM(miles)
say(f"{miles} miles = {kilometers} km") # Output: 10 miles = 16.0934 km
# Practical example: Weather converter
def display_weather(temp_c, description, location):
temp_f = convertCtoF(temp_c)
say(f"Weather in {location}: {description}")
say(f"Temperature: {temp_c}°C ({temp_f:.1f}°F)")
# Usage
display_weather(25, "Sunny", "New York")
display_weather(-5, "Snowy", "Toronto")
display_weather(30, "Cloudy", "Miami")
# Practical example: Travel distance
def calculate_travel(distance_km, speed_kmh):
distance_miles = convertKMtoMiles(distance_km)
time_hours = distance_km / speed_kmh
say(f"Distance: {distance_km} km ({distance_miles:.1f} miles)")
say(f"At {speed_kmh} km/h, travel time: {time_hours:.1f} hours")
calculate_travel(100, 80) # 100 km at 80 km/h
calculate_travel(250, 60) # 250 km at 60 km/h
Unit conversion functions for temperature (Celsius/Fahrenheit) and distance (kilometers/miles). Useful for international applications and data processing.
Validation & Formatting
Functions for data validation and formatting output in standardized ways.
Validation Functions
from starexx import *
# Email validation
valid_email = validateEmail("test@example.com")
say("test@example.com is valid:", valid_email) # Output: True
invalid_email = validateEmail("invalid-email")
say("invalid-email is valid:", invalid_email) # Output: False
# Number validation
valid_number = validateNumber("123.45")
say("123.45 is a number:", valid_number) # Output: True
invalid_number = validateNumber("abc")
say("abc is a number:", invalid_number) # Output: False
# Mixed input
mixed_input = validateNumber("123abc")
say("123abc is a number:", mixed_input) # Output: False
# Practical example: User registration
def register_user():
email = ask("Enter your email: ")
if not validateEmail(email):
say("Invalid email address!")
return
age = ask("Enter your age: ")
if not validateNumber(age):
say("Age must be a number!")
return
age = int(age)
if age < 13:
say("You must be at least 13 years old!")
return
say("Registration successful!")
return {"email": email, "age": age}
# Test the function
user_data = register_user()
if user_data:
say("Registered user:", user_data)
Validation functions for checking email format and numeric input. Essential for user input validation in applications.
Formatting Functions
from starexx import *
# Currency formatting
amount = 1234.56
currency = formatCurrency(amount)
say(f"Amount: {currency}") # Output: Amount: $1234.56
amount = 99.99
currency = formatCurrency(amount)
say(f"Amount: {currency}") # Output: Amount: $99.99
# Percentage formatting
decimal = 0.756
percent = formatPercent(decimal)
say(f"Percentage: {percent}") # Output: Percentage: 75.6%
decimal = 0.1234
percent = formatPercent(decimal)
say(f"Percentage: {percent}") # Output: Percentage: 12.3%
# Number formatting with commas
large_number = 1234567
formatted = formatNumber(large_number)
say(f"Number: {formatted}") # Output: Number: 1,234,567
small_number = 1234
formatted = formatNumber(small_number)
say(f"Number: {formatted}") # Output: Number: 1,234
# Practical example: Financial report
def generate_report(revenue, expenses, profit_margin):
total_revenue = formatCurrency(revenue)
total_expenses = formatCurrency(expenses)
margin_percent = formatPercent(profit_margin)
say("=== FINANCIAL REPORT ===")
say(f"Revenue: {total_revenue}")
say(f"Expenses: {total_expenses}")
say(f"Profit Margin: {margin_percent}")
# Generate sample report
generate_report(1500000, 950000, 0.3667)
# Practical example: Data display
def display_population_data():
countries = {
"USA": 331000000,
"India": 1380000000,
"China": 1400000000
}
say("=== POPULATION DATA ===")
for country, population in countries.items():
formatted_pop = formatNumber(population)
say(f"{country}: {formatted_pop}")
display_population_data()
Formatting functions for displaying numbers as currency, percentages, and with comma separators. Essential for professional-looking output in business applications.
System Utilities
System-level utilities for terminal control, application management, and system information.
from starexx import *
# Clear terminal screen
clearScreen()
# Clears the terminal/console screen
# Display system information
getSystemInfo()
# Output example:
# Python version: 3.9.7 (default, Sep 16 2021, 13:09:58)
# Platform: darwin
# Create counter function
counter = createCounter()
print(counter()) # Output: 1
print(counter()) # Output: 2
print(counter()) # Output: 3
# Create multiple counters
counter1 = createCounter()
counter2 = createCounter()
print(counter1()) # Output: 1
print(counter1()) # Output: 2
print(counter2()) # Output: 1 (independent counter)
print(counter1()) # Output: 3
# Pause execution
say("Program will pause...")
pause()
# Displays: "Press Enter to continue..." and waits for user input
# Exit application
# exitApp()
# Uncommenting this will immediately terminate the program
# Practical example: Interactive menu
def interactive_menu():
while True:
clearScreen()
say("=== MAIN MENU ===")
say("1. View System Info")
say("2. Count Demo")
say("3. Exit")
choice = ask("Enter your choice (1-3): ")
if choice == "1":
getSystemInfo()
pause()
elif choice == "2":
counter = createCounter()
say("Counter demo:")
for i in range(5):
say(f"Count: {counter()}")
pause()
elif choice == "3":
say("Goodbye!")
# exitApp() # Uncomment to actually exit
break
else:
say("Invalid choice!")
pause()
# Run the interactive menu
# interactive_menu()
System utilities for terminal control, application flow, and system information. The counter function creates stateful counters that maintain their count between calls.
Complete Program Example
A comprehensive example demonstrating how to use multiple Starexx functions together in a real-world application.
from starexx import *
def user_profile_manager():
"""
A complete user profile management system using Starexx library.
Demonstrates multiple functions working together.
"""
clearScreen()
say("=== USER PROFILE MANAGER ===")
# Collect user information
name = ask("What's your name?")
while True:
age_input = ask("How old are you?")
if validateNumber(age_input):
age = int(age_input)
break
else:
say("Please enter a valid number for age!")
email = ask("What's your email address?")
while not validateEmail(email):
say("Invalid email format! Please try again.")
email = ask("What's your email address?")
city = ask("Which city do you live in?")
# Calculate additional information
current_year = 2024
birth_year = subtract(current_year, age)
# Check age properties
age_is_even = isEven(age)
age_is_prime = isPrime(age)
# Create user profile
user_profile = createDict(
name=name,
age=age,
email=email,
city=city,
birth_year=birth_year,
age_is_even=age_is_even,
age_is_prime=age_is_prime,
created_at=showDate()
)
# Display profile information
say("\n=== PROFILE SUMMARY ===")
say(f"Name: {toUpper(name)}")
say(f"Age: {age} years old")
say(f"Email: {toLower(email)}")
say(f"City: {capitalizeText(city)}")
say(f"Birth Year: {birth_year}")
say(f"Age is even: {age_is_even}")
say(f"Age is prime: {age_is_prime}")
# Generate some fun facts
say("\n=== FUN FACTS ===")
say(f"Your name has {textLength(name)} characters")
say(f"Your name backwards: {reverseText(name)}")
if age_is_prime:
say("Your age is a prime number! 🎉")
else:
say("Your age is a composite number.")
# Save profile to file
filename = f"profile_{toLower(replaceText(name, ' ', '_'))}.txt"
profile_content = f"User Profile\\n{'-'*20}\\n"
for key, value in user_profile.items():
profile_content += f"{capitalizeText(replaceText(key, '_', ' '))}: {value}\\n"
writeFile(filename, profile_content)
say(f"\\nProfile saved to: {filename}")
# Display file information
if fileExists(filename):
file_size = fileSize(filename)
say(f"File size: {file_size} bytes")
# Read and display the saved file
say("\\n=== SAVED PROFILE CONTENT ===")
saved_content = readFile(filename)
say(saved_content)
say("\\nThank you for using User Profile Manager!")
sayGoodbye()
def main():
"""
Main function with error handling and user interaction.
"""
try:
user_profile_manager()
except KeyboardInterrupt:
say("\\nProgram interrupted by user.")
except Exception as e:
say(f"An error occurred: {e}")
finally:
say("Program execution completed.")
if __name__ == "__main__":
main()
This complete example demonstrates a user profile management system that uses multiple Starexx functions including: input/output, validation, math operations, text processing, file operations, and data structures. It shows how different functions can be combined to create a practical application.