Python – Hurkle

HTML Hurkle

import random
secret_number = random.randint(1, 99)

import sys

print(
"""
+============================+
| Welcome to Robert's Hurkle.|
| Guess the Secret Number.   |
+============================+
""")
print ("The Secret Number is " + str(secret_number))

MyGuess = 0
guesses = 0

while MyGuess != secret_number:
    MyGuess = int(input("Enter your secret number guess:  "))
    if MyGuess > secret_number: hint="Lower"
    else: hint= "Higher"
    
    if MyGuess == secret_number:
        print ("Congratulations.  You guessed correctly.")
        print ("The number is " + str(MyGuess))
        print ("it took you " + str(guesses+1) + " guesses to get it right.")
        print()
    elif MyGuess == 0:
        print ("The number was " + str(secret_number) + ".")
        sys.exit()
    else:
        print ("Wrong.  " + str(MyGuess) + " is not the number.")
        print ("Enter ZERO to give up.")
        guesses += 1
        print ("So far, you guessed " + str(guesses) + " times.")
        print ("The secret number is " + hint)
        print()

Python – Disposal Evaluation

HTML Program

# Disposal Evaluation Program

def get_input(prompt):
    """Utility function to get user input with validation."""
    while True:
        try:
            value = input(prompt)
            # Accepting numerical values for certain prompts
            return float(value) if prompt.startswith(("How long", "cash value", "size", "emotional value")) else value
        except ValueError:
            print("Please enter a valid input.")

def evaluate_item(use_time, next_use_time, cash_value, size, emotional_value):
    """Evaluates the item's value based on the input factors."""
    score = 0

    # Evaluation Criteria
    score = 25 - use_time
    score += (25 - next_use_time)
    score += int(cash_value / 100)
    score += (25 - size)
    score += emotional_value
    return score

def main():
    print("Disposal Evaluation Program")
    
    while True:
        # Gather information from the user
        use_time = get_input("How long has it been (in months) since you have used this item? ")
        next_use_time = get_input("How long (in months) until you think you will use this item? ")
        cash_value = get_input("What is the cash value of the item? ")
        size = get_input("How much size (in cubic feet) does the item take up? ")
        emotional_value = get_input("Rate the emotional value of the item from 1 to 50. ")

        # Convert relevant inputs to float
        cash_value = float(cash_value)
        size = float(size)
        emotional_value = float(emotional_value)
        
        # Evaluate the item
        score = evaluate_item(use_time, next_use_time, cash_value, size, emotional_value)

        # Display the score and results
        print(f"\nFinal score for the item: {int(score)}")

        # Display results
        if score > 100:
            print("\nRecommendation: Keep the item.")
        elif score < 80:
            print("\nRecommendation: Dispose of the item.")
        else:
            print("\nRecommendation: This is something you should think about.")

        # Ask the user if they want to evaluate another item or quit
        another_item = input("\nWould you like to evaluate another item? (Y/N): ").strip().lower()
        if another_item != 'y':
            print("Thank you for using the Disposal Evaluation Program. Goodbye!")
            break

if __name__ == "__main__":
    main()

Python – QR Code Generator

BASE GENERATOR

Essential Widgets

import qrcode
from PIL import Image

# This QR  Code Generator was developed by Robert Andrews, Beatitudes Resident.
xx = input("Enter URL:  ")
xName = input("Enter QR Code File Name:  ")
# Website URL
website_url = xx


# ERROR TRAP URL
xTRAP = xx[0:4]
if xTRAP == "http":
    website_url = xx
else:
    website_url = "http://" + xx



# ERROR TRAP FILENAME
if xName.endswith(".JPG") or xName.endswith(".PNG"):
    xName = xName
else:
    xName = xName+".JPG"
    


# Create QR code instance
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)

# Add website URL to QR code
qr.add_data(website_url)
qr.make(fit=True)

# Create an image from the QR code with dark blue color
img = qr.make_image(fill_color="#295BB3", back_color="white")  # Use hex code for dark blue

# Open the logo image
logo = Image.open("LOGO.png")
logo = logo.resize((59, 59))  # Resize the logo image if necessary

# Get the position to paste the logo in the center of the QR code image
position = ((img.size[0] - logo.size[0]) // 2, (img.size[1] - logo.size[1]) // 2)

# Paste the logo onto the QR code image
img.paste(logo, position)

# Save the QR code image with the logo
img.save(xName)

print ("QR Code is on the desktop under QR Code Generator.")



Python – Stopwatch

HTML STOPWATCH


import tkinter as tk
from tkinter import simpledialog

class TimerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Timer")

        self.count = 0.0  # Use float to accommodate tenths of a second
        self.is_running = False
        self.is_counting_up = True

        self.label = tk.Label(root, text=str(self.count), font=("Helvetica", 48))  # Increased font size to 48
        self.label.pack(pady=20)

        self.up_button = tk.Button(root, text="Count Up", command=self.start_counting_up, font=("Helvetica", 18))
        self.up_button.pack(side=tk.LEFT, padx=20)

        self.down_button = tk.Button(root, text="Count Down", command=self.start_counting_down, font=("Helvetica", 18))
        self.down_button.pack(side=tk.RIGHT, padx=20)

        self.stop_button = tk.Button(root, text="Stop", command=self.stop_timer, font=("Helvetica", 18))
        self.stop_button.pack(pady=20)

        self.update_timer()

    def start_counting_up(self):
        self.is_counting_up = True
        self.is_running = True
        self.count = 0.0  # Reset count
        self.label.config(text=str(self.count))

    def start_counting_down(self):
        self.is_counting_up = False
        self.is_running = True
        # Ask user for countdown time in seconds
        countdown_time = simpledialog.askfloat("Input", "Set countdown time in seconds:", minvalue=0.1)
        if countdown_time is not None:
            self.count = countdown_time  # Set countdown start
            self.label.config(text=str(self.count))

    def stop_timer(self):
        self.is_running = False

    def update_timer(self):
        if self.is_running:
            if self.is_counting_up:
                self.count += 0.1  # Increment by tenths of a second
            else:
                self.count -= 0.1  # Decrement by tenths of a second
            
            # Ensure count doesn't go below 0 for countdown
            if not self.is_counting_up and self.count < 0:
                self.count = 0
            
            self.label.config(text=f"{self.count:.1f}")  # Format to one decimal place
        
        self.root.after(100, self.update_timer)  # Update every 100 milliseconds

if __name__ == "__main__":
    root = tk.Tk()
    app = TimerApp(root)
    root.mainloop()

Swift 2 – Code Examples

CLICK HERE for the Apple xCode Project Examples Developer Library, or just type http://tinyurl.com/xcodelibrary if you are not on this page.


USEFUL SYNTAX(es) AND CODE EXAMPLES


IF STATEMENT

var myString = String()
if X == array_Name.indexOf(myCharacters) {
myString = “Statement One”
}
else if X = Y {
MyString = “Second Statement”
}
else {
MyString = “This is the default”
}
// endIf is not necessary in Swift


HOW TO DEFINE AN ARRAY OF STRINGS

 

 


HOW TO CREATE AN ARRAY FROM ONE LONG STRING

 

 


HOW TO CREATE AN ARRAY OF NUMBERS

 


HOW TO GET THE VALUE OF AN ARRAY MEMBER

 


HOW TO GET THE POSITION OF A LETTER WITHIN AN ARRAY

 


REPEAT – WHILE

 


DO – WHILE

 


FOR – NEXT

 


LOOP

 


DO – CATCH

do {
let contents = try…
// OK let run
} catch {
// error
}


OPENING AND CLOSING A FILE

let file = openfile()

close file (file)


 

DEFER – DO THIS WHEN FUNCTION EXITS

defer { whatever }

 


PASSING DATA FROM ONE VIEW CONTROLLER TO ANOTHER

This was very complex, so I am posting it to it’s own page. CLICK HERE TO ACCESS IT or use the navigation bar to the right.