├── anagram.py ├── arrows-tkinter.py ├── arrows.py ├── aspen.jpg ├── aspen2.jpg ├── aspen5.jpg ├── choose.py ├── clocks.py ├── draw.py ├── filez.py ├── flash.py ├── generator.py ├── guessing_game.py ├── guessing_game_gui.py ├── hangman.py ├── images.py ├── palindrome.py ├── rps.py ├── speed.py ├── sub.py ├── tictactoe.py ├── todo.py ├── validate.py └── wordcount.py /anagram.py: -------------------------------------------------------------------------------- 1 | import os 2 | os.system("clear") 3 | #print(sorted("dogs", reverse=True)) 4 | #print(sorted("god")) 5 | #print(sorted("dogs") == sorted("god")) 6 | 7 | # Function to check if two words are anagrams 8 | def are_anagrams(word1, word2): 9 | # Decide if two words are anagrams? 10 | #sorted(john) == hjno 11 | return sorted(word1) == sorted(word2) 12 | 13 | # Function to find all anagrams of a word from a list of dictionary words 14 | def find_anagrams(word, word_list): 15 | # conver word to lowercase 16 | word = word.lower() 17 | 18 | # Return a list of words that are anagrams of the input word 19 | return [w for w in word_list if are_anagrams(word, w.lower()) and w.lower() != word] 20 | 21 | 22 | # Main Function 23 | def anagram_solver(): 24 | # Create a list of dictionary words to check against 25 | word_list = ["listen", "silent", "enlist", "tinsel", "google", "elder", "dog", "god", "evil", "vile", "live"] 26 | 27 | # Prompt the user 28 | word = input("Enter a word to find it's anagrams: ") 29 | 30 | # Find anagrams for the word 31 | anagrams = find_anagrams(word, word_list) 32 | 33 | # Output 34 | if anagrams: 35 | print(f'Anagrams of "{word}" are: {', '.join(anagrams)}') 36 | else: 37 | print(f'No anagrams found for word "{word}".') 38 | 39 | 40 | 41 | 42 | 43 | # Run the thing 44 | anagram_solver() -------------------------------------------------------------------------------- /arrows-tkinter.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | 3 | 4 | 5 | 6 | # Build out a simple app gui 7 | root = Tk() 8 | root.title("Arrows!") 9 | root.geometry("300x100") 10 | 11 | def key_pressed(event): 12 | key = event.keysym 13 | if key == "Up": 14 | my_label.config(text="Up!") 15 | elif key == "Down": 16 | my_label.config(text="Down...") 17 | elif key == "Left": 18 | my_label.config(text="<-- Left") 19 | elif key == "Right": 20 | my_label.config(text="Right -->") 21 | elif key == 'q': 22 | root.destroy() 23 | 24 | 25 | 26 | # Label 27 | my_label = Label(root, text="Press arrow keys. Press 'q' to exit...") 28 | my_label.pack(pady=20) 29 | 30 | 31 | # Focus the window 32 | root.focus_set() 33 | 34 | # Bind the keyboard 35 | root.bind('', key_pressed) 36 | 37 | 38 | root.mainloop() -------------------------------------------------------------------------------- /arrows.py: -------------------------------------------------------------------------------- 1 | from pynput import keyboard 2 | import os 3 | 4 | # Clear the screen 5 | os.system("clear") 6 | 7 | 8 | def on_press(key): 9 | try: 10 | # Check for q 11 | if key.char == 'q': 12 | print('Exiting Program...') 13 | return False # Stop listener 14 | except AttributeError: 15 | pass 16 | 17 | # Check for arrow Keys 18 | if key == keyboard.Key.up: 19 | print("Up!") 20 | elif key == keyboard.Key.down: 21 | print("Down...") 22 | elif key == keyboard.Key.left: 23 | print("<-- Left") 24 | elif key == keyboard.Key.right: 25 | print("Right -->") 26 | 27 | 28 | 29 | # Prompt the user 30 | print("Press arrows keys! Press 'q' to exit...") 31 | 32 | # Create and start a keyboard listener 33 | with keyboard.Listener(on_press=on_press) as listener: # Create listener object that listens for keyboard events 34 | listener.join() # Start the listener and wait for it to finish -------------------------------------------------------------------------------- /aspen.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flatplanet/python-projects-course/9d2bbc4625a887eb3584cf378277cdca9d57d325/aspen.jpg -------------------------------------------------------------------------------- /aspen2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flatplanet/python-projects-course/9d2bbc4625a887eb3584cf378277cdca9d57d325/aspen2.jpg -------------------------------------------------------------------------------- /aspen5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flatplanet/python-projects-course/9d2bbc4625a887eb3584cf378277cdca9d57d325/aspen5.jpg -------------------------------------------------------------------------------- /choose.py: -------------------------------------------------------------------------------- 1 | import os 2 | import random 3 | 4 | 5 | 6 | ''' 7 | num = random.random() 8 | print(num) 9 | print(num < 0.2) 10 | ''' 11 | 12 | # function to display the intro text 13 | def diplay_inro(): 14 | print("Welcome to the big time adventure game!") 15 | print("You're on a quest to rescue the princes in the castle.") 16 | print("Navigate carefully using directions: N (north), S (south), E (east), W (west).") 17 | print("Watch out for pits! They could pop up anywhere...") 18 | print("Good Luck on your adventure!!\n") 19 | 20 | 21 | 22 | # Function to check for danger/pit 23 | def check_for_pit(): 24 | # Set random level for pit falling - 10% 25 | # Generate a random float between 0 and 1 .05, .2, .9 26 | return random.random() < 0.10 27 | # True for pit, False for No Pit 28 | 29 | 30 | 31 | 32 | 33 | # Function for the game 34 | def adventure_game(): 35 | # Clear the screen 36 | os.system("clear") 37 | # Call the display menu thing 38 | diplay_inro() 39 | #Keep track of the steps 40 | steps = 0 41 | 42 | # game loop 43 | while True: 44 | direction = input("Choose a direction (N/S/E/W): ").upper() 45 | 46 | # check for errors 47 | if direction not in ['N', 'S', 'E', 'W']: 48 | print("Invalid Direction, please choose N, S, E, or W.") 49 | continue 50 | 51 | # increase the step cout 52 | steps += 1 53 | 54 | # Check if player fell into the pit 55 | if check_for_pit(): 56 | print(f"Oh No! You chose {direction} and fell into a pit! Game over!") 57 | break 58 | 59 | # Check for 5 steps 60 | if steps >= 5: 61 | print(f"Congrats! After {steps} steps, you have reached the castle and rescued the princess! You Win!") 62 | break 63 | else: 64 | print(f"You moved {direction}. Keep going!") 65 | 66 | 67 | 68 | 69 | 70 | # Main function 71 | def main(): 72 | while True: 73 | # Call the game function 74 | adventure_game() 75 | # ask to play again 76 | replay = input("\nWould you like to play again (y/n): ").lower() 77 | # Logic to determine if they want to play again 78 | if replay != 'y': 79 | print("Thanks for playing! Later duder!") 80 | break 81 | 82 | 83 | 84 | 85 | # Run the game 86 | main() -------------------------------------------------------------------------------- /clocks.py: -------------------------------------------------------------------------------- 1 | import time 2 | from datetime import datetime 3 | import os 4 | import threading 5 | from zoneinfo import ZoneInfo 6 | # pip install tzdata 7 | 8 | # clear the screen 9 | def clear_screen(): 10 | os.system('clear') 11 | 12 | # Wait for user to hit enter 13 | def input_thread(stop_event): 14 | input() 15 | stop_event.set() 16 | 17 | 18 | 19 | def main(): 20 | # Set up our time zones 21 | time_zones = { 22 | '1': ('Eastern Time', 'America/New_York'), 23 | '2': ('Central Time', 'America/Chicago'), 24 | '3': ('Pacific Time', 'America/Los_Angeles') 25 | } 26 | # Prompt the user to pick a time zone 27 | print("Select a time zone:") 28 | # Loop thru our time_zones dictionary 29 | for key, (name, _) in time_zones.items(): 30 | print(f'{key}. {name}') 31 | 32 | # Assign their selection to a variable 33 | choice = input("Enter the number of your choice: ").strip() 34 | 35 | # Error handling for choice selection 36 | if choice not in time_zones: 37 | print("Invalid Choice. Defaulting to Eastern Time.") 38 | tz_name = "America/New_York" 39 | tz_display_name = "Eastern Time" 40 | else: 41 | tz_display_name, tz_name = time_zones[choice] 42 | 43 | 44 | # Create an event to signal when to stop the clock 45 | stop_event = threading.Event() 46 | 47 | # Start the input thread 48 | thread = threading.Thread(target=input_thread, args=(stop_event, )) 49 | thread.daemon = True 50 | thread.start() 51 | 52 | 53 | # Loop to update our time in seconds till enter is pressed 54 | while not stop_event.is_set(): 55 | # Clear the screen 56 | clear_screen() 57 | # get current time 58 | #current_time = time.strftime("%H:%M:%S") 59 | current_time = datetime.now(ZoneInfo(tz_name)).strftime("%I:%M:%S %p") 60 | # print the current time 61 | print(f'Current time: {current_time} - {tz_display_name}') 62 | # Prompt the user to stop the clock 63 | print("Press Enter to stop the clock...") 64 | # run the loop once per second 65 | time.sleep(1) 66 | 67 | # Print and end message 68 | print("Clock Stopped...") 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | # Clear the screen 80 | clear_screen() 81 | 82 | # Call the main function 83 | main() -------------------------------------------------------------------------------- /draw.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | import os 3 | 4 | 5 | # Clear screen 6 | os.system("clear") 7 | 8 | # Create a turtle object 9 | t = turtle.Turtle() 10 | # Create a screen object 11 | screen = turtle.Screen() 12 | 13 | 14 | # Reset the screen 15 | def reset_turtle(): 16 | t.clear() 17 | t.penup() 18 | t.home() 19 | t.pendown() 20 | 21 | 22 | # Draw a square 23 | def draw_square(size): 24 | #reset_turtle() 25 | # For loop to do 4 lines 26 | for _ in range(4): 27 | t.forward(size) 28 | t.right(90) 29 | 30 | # Draw a triangle 31 | def draw_triangle(size): 32 | #reset_turtle() 33 | for _ in range(3): 34 | t.forward(size) 35 | t.left(120) 36 | 37 | # Draw a circle 38 | def draw_circle(radius): 39 | #reset_turtle() 40 | t.circle(radius) 41 | 42 | 43 | 44 | 45 | # Main function 46 | def draw_shape(): 47 | while True: 48 | # Clear the screen 49 | os.system("clear") 50 | print("\nSelect a Shape to Draw:") 51 | print("1. Square") 52 | print("2. Circle") 53 | print("3. Triangle") 54 | print("4. Exit") 55 | 56 | # Prompt the user 57 | choice = input("Enter the number of your choice: ") 58 | 59 | # Choice logic 60 | if choice == "1": 61 | size = int(input("Enter the Size of the Square: ")) 62 | draw_square(size) 63 | elif choice == "2": 64 | size = int(input("Enter the Radius of the Circle: ")) 65 | draw_circle(size) 66 | 67 | elif choice == "3": 68 | size = int(input("Enter the Size of the Triangle: ")) 69 | draw_triangle(size) 70 | 71 | elif choice == "4": 72 | print("Exiting the program. Later!") 73 | # close turle screen 74 | turtle.bye() 75 | break 76 | 77 | 78 | # Catch errors 79 | else: 80 | print("Invalid Choice, please try again...") 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | # Run the app 89 | draw_shape() 90 | 91 | 92 | # # Complete the drawing 93 | #turtle.done() 94 | -------------------------------------------------------------------------------- /filez.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | # Clear 4 | os.system("clear") 5 | 6 | 7 | # Function to create and save a file 8 | def create_file(): 9 | # Prompt for file details 10 | text = input("Enter the text you want to save in the file: ") 11 | file_name = input("Enter the filename (example: myfile.txt): ") 12 | file_location = input("Enter the file location (c:/python-projects/): ") 13 | 14 | # Ensure the directory exists or create it 15 | if not os.path.exists(file_location): 16 | os.makedirs(file_location) 17 | 18 | # Full file path - c:/python-projects/myfile.txt 19 | file_path = os.path.join(file_location, file_name) 20 | 21 | # Write the text to the file 22 | with open(file_path, 'w') as file: 23 | file.write(text) 24 | print(f"File '{file_name}' saved successfully at {file_location}.") 25 | 26 | 27 | # Function to open and read a file 28 | def open_file(): 29 | # prompt the user for file details 30 | file_name = input("Enter the filename to open (example: myfile.txt): ") 31 | file_location = input("Enter the file location (example: c:/python-projects/): ") 32 | 33 | # Get the full path 34 | file_path = os.path.join(file_location, file_name) 35 | 36 | # Check if the file exists 37 | if os.path.exists(file_path): 38 | # Read and output the file contensts 39 | with open(file_path, 'r') as file: 40 | # Print the contents 41 | print("\nFile Contents:") 42 | print(file.read()) 43 | else: 44 | print(f"File '{file_name}' not found at {file_location}.") 45 | 46 | 47 | 48 | 49 | # The main function 50 | def file_manager(): 51 | while True: 52 | print("\n--- File Manager ---") 53 | print("1. Create and save a file") 54 | print("2. Open and read a file") 55 | print("3. Quit") 56 | 57 | # Get selection 58 | choice = input("Choose and option (1/2/3): ") 59 | 60 | if choice == "1": 61 | create_file() 62 | elif choice == "2": 63 | open_file() 64 | elif choice == "3": 65 | print("Exiting the program. Later duder!") 66 | break 67 | else: 68 | print("Invalid selection. Please choose 1, 2, or 3.") 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | # Call the program 77 | file_manager() -------------------------------------------------------------------------------- /flash.py: -------------------------------------------------------------------------------- 1 | import random 2 | import os 3 | 4 | 5 | # Function to generate a math problem 6 | def generate_flashcard(operation): 7 | # generate two random number 8 | num1 = random.randint(1, 10) 9 | num2 = random.randint(1, 10) 10 | 11 | # Logic to do the thing 12 | if operation == "addition": 13 | correct_answer = num1 + num2 14 | question = f'{num1} + {num2} = ?' 15 | 16 | elif operation == "subtraction": 17 | correct_answer = num1 - num2 18 | question = f'{num1} - {num2} = ?' 19 | 20 | elif operation == "multiplication": 21 | correct_answer = num1 * num2 22 | question = f'{num1} * {num2} = ?' 23 | 24 | elif operation == "division": 25 | # Ensure the second number is not zero and num1 is divisible by num2 26 | while num2 == 0 or num1 % num2 != 0: 27 | # Get new numbers 28 | num1 = random.randint(1, 10) 29 | num2 = random.randint(1, 10) 30 | 31 | correct_answer = num1 // num2 32 | question = f'{num1} / {num2} = ?' 33 | 34 | # Return the results 35 | return question, correct_answer 36 | 37 | 38 | # Main Menu function 39 | def main_menu(): 40 | # Clear the screen 41 | os.system("clear") 42 | # Create a menu 43 | print("\n--- Math Flashcard App ---") 44 | print("1. Addition") 45 | print("2. Subtraction") 46 | print("3. Multiplication") 47 | print("4. Division") 48 | print("5. Quit") 49 | 50 | # Get the user choice 51 | choice = input("Choose an option (1-5): ") 52 | return choice 53 | 54 | 55 | 56 | # Function to create a flashcard session 57 | def flashcard_session(operation): 58 | while True: 59 | # clear the screen 60 | os.system("clear") 61 | question, correct_answer = generate_flashcard(operation) 62 | 63 | # Print the question 64 | print(f"\nFlashcard: {question}") 65 | 66 | # Prompt user for answer 67 | user_answer = input("Your answer: ") 68 | 69 | # Error handling 70 | try: 71 | user_answer = int(user_answer) 72 | except ValueError: 73 | print("Invalid Input. Please enter a valid number.") 74 | 75 | # Answer solution 76 | if user_answer == correct_answer: 77 | print("Correct!") 78 | else: 79 | print(f'Wrong. The correct answer is {correct_answer}') 80 | 81 | # Ask to play again 82 | next_step = input("\nWould you like another flashcard (y/n)? ").lower() 83 | 84 | if next_step == 'n': 85 | break 86 | 87 | 88 | # Main function 89 | def math_flashcard_app(): 90 | while True: 91 | # Call menu function 92 | choice = main_menu() 93 | 94 | # Logic to determine choice 95 | if choice == "1": 96 | flashcard_session("addition") 97 | elif choice == "2": 98 | flashcard_session("subtraction") 99 | elif choice == "3": 100 | flashcard_session("multiplication") 101 | elif choice == "4": 102 | flashcard_session("division") 103 | elif choice == "5": 104 | print("Goodbye") 105 | break 106 | else: 107 | print("Invalid choice, please try again.") 108 | 109 | 110 | 111 | 112 | 113 | 114 | # Run the app 115 | math_flashcard_app() -------------------------------------------------------------------------------- /generator.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | import os 4 | 5 | # Clear the screen 6 | os.system("clear") 7 | print(string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation) 8 | # Actually validate the password: 9 | def validate_password(password): 10 | # Check our password rules 11 | if len(password) < 8: 12 | return False, "Password must be at least 8 character long." 13 | # Check for digits 14 | if not any(char.isdigit() for char in password): 15 | return False, "Password must contain at least one digit." 16 | # Check for lowercase 17 | if not any(char.islower() for char in password): 18 | return False, "Password must contain at least one lowercase letter." 19 | # Check for uppercase 20 | if not any(char.isupper() for char in password): 21 | return False, "Password must contain at least one r." 22 | # Check for special characters 23 | if not any(char in string.punctuation for char in password): 24 | return False, "Password must contain at least one special character." 25 | 26 | # Return true if all the rules were true 27 | return True, "Password is strong!!" 28 | 29 | # Generate the password 30 | def generate_password(length): 31 | while True: 32 | # Ensure we meet the basic criteria (the four things) at least once 33 | password = [ 34 | random.choice(string.ascii_lowercase), # At least one lowercase 35 | random.choice(string.ascii_uppercase), # At least one uppercase 36 | random.choice(string.digits), # At least one digit 37 | random.choice(string.punctuation), # At least one special character 38 | ] 39 | 40 | # Fill the rest of the password with random characters from all the charcter sets 41 | # Get remaining character count 42 | remaining_length = length - 4 43 | # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 44 | password += random.choices(string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation, k=remaining_length) 45 | # password = ["s", "G", "6", "%", "9", "$", "H", "1"] 46 | 47 | # Shuffle the list 48 | random.shuffle(password) 49 | 50 | # Convert our list into a string using join() 51 | password = ''.join(password) 52 | 53 | # Validate 54 | is_valid, message = validate_password(password) 55 | if is_valid: 56 | return password 57 | 58 | 59 | # Prompt the user 60 | def password_generator(): 61 | while True: 62 | try: 63 | # get the password length 64 | length = int(input("Enter the desired password length (minimum 8): ")) 65 | if length < 8: 66 | print("Password length mush be at least 8 characters.") 67 | continue 68 | break 69 | except ValueError: 70 | print("Invalid input. Please enter a number.") 71 | 72 | # Generate the password 73 | password = generate_password(length) 74 | print(f'Generated Password: {password}') 75 | print("This password is strong!") 76 | 77 | 78 | 79 | 80 | # Run the progam 81 | #password_generator() -------------------------------------------------------------------------------- /guessing_game.py: -------------------------------------------------------------------------------- 1 | # Import the os module/library 2 | import os 3 | # Import the random library 4 | import random 5 | 6 | # Create a play again function 7 | def play_again(): 8 | # Prompt the user 9 | again = input("Would you like to play again? y/n ") 10 | # Logic to figure out what to do 11 | if again == "y" or again == "yes" or again == "YES" or again == "Yes": 12 | game() 13 | else: 14 | print("Thanks for playing!") 15 | return 16 | 17 | # Create our main game function 18 | def game(): 19 | # Create a variable to keep track of the number of guesses 20 | number_of_guesses = 0 21 | correct = False 22 | 23 | # Clear The Screen 24 | os.system("clear") 25 | 26 | # Generate a random number and assign it to a variable 27 | number_to_guess = random.randint(1,10) 28 | 29 | # Get user input 30 | print("Guess a Number between 1 and 10") 31 | 32 | # Create guessing loop 33 | while correct == False: 34 | # Try/except block 35 | try: 36 | guess = int(input("Enter your Guess: ")) 37 | except Exception as e: 38 | print("Something went wrong! Game Over") 39 | return 40 | 41 | # Create some logic to check the guess 42 | if guess < number_to_guess: 43 | print("Too Low! - Try Again!") 44 | # Increment the number of guesses 45 | number_of_guesses += 1 46 | elif guess > number_to_guess: 47 | print("Too High! - Try Again!") 48 | # Increment the number of guesses 49 | number_of_guesses += 1 50 | 51 | elif guess == number_to_guess: 52 | # Increment the number of guesses 53 | number_of_guesses += 1 54 | print(f"Correct! The number was {number_to_guess} and you guessed it in {number_of_guesses} guesses!") 55 | # Set correct to TRUE 56 | correct = True 57 | # Run the play_again Function to see if the user wants to play again 58 | play_again() 59 | 60 | 61 | 62 | 63 | # Call our game function 64 | game() -------------------------------------------------------------------------------- /guessing_game_gui.py: -------------------------------------------------------------------------------- 1 | # Import Tkinter 2 | from tkinter import * 3 | # Import the os module/library 4 | import os 5 | # Import the random library 6 | import random 7 | 8 | 9 | 10 | 11 | # Create a play again function 12 | def reset_game(guess_entry, result_label, submit_button, play_again_button, state): 13 | # Generate a random number and assign it to a variable 14 | state['number_to_guess'] = random.randint(1,10) 15 | # Set number of guesses to zero 16 | state['number_of_guesses'] = 0 17 | # Delete result label 18 | result_label.config(text="") 19 | # Clear the entry box 20 | guess_entry.delete(0, END) 21 | # Set the submit button back to normal 22 | submit_button.config(state=NORMAL) 23 | # Hide the play again button...again 24 | play_again_button.pack_forget() 25 | 26 | 27 | 28 | # Create our main game function 29 | def check_guess(guess_entry, result_label, submit_button, play_again_button, state): 30 | 31 | # Try/except block 32 | try: 33 | guess = int(guess_entry.get()) 34 | state['number_of_guesses'] +=1 35 | # Create some logic to check the guess 36 | if guess < state['number_to_guess']: 37 | result_label.config(text="Too Low! - Try Again!") 38 | 39 | elif guess > state['number_to_guess']: 40 | result_label.config(text="Too High! - Try Again!") 41 | 42 | else: 43 | result_label.config(text=f"Correct! The number was {state['number_to_guess']} and you guessed it in {state['number_of_guesses']} guesses!") 44 | # Disable the guess button 45 | submit_button.config(state=DISABLED) 46 | # Enable the play again button 47 | play_again_button.pack() 48 | 49 | except ValueError: 50 | result_label.config(text="Invalid Input! Please enter a number.") 51 | 52 | 53 | 54 | 55 | 56 | def setup_gui(): 57 | # Create the window 58 | root = Tk() 59 | # Add a title 60 | root.title("Guessing Game") 61 | # Set the size of the app 62 | root.geometry('500x350') 63 | 64 | # Set the game state 65 | state = {'number_to_guess':None, 'number_of_guesses':0} 66 | 67 | # Create a Label 68 | instruction_label = Label(root, text="Guess a Number between 1 and 10", font=("Helvetica", 18)) 69 | instruction_label.pack(pady=20) 70 | 71 | # Create an entry box 72 | guess_entry = Entry(root, font=("Helvetica", 18)) 73 | guess_entry.pack(pady=10) 74 | 75 | # Create another Label 76 | result_label = Label(root, text="") 77 | result_label.pack(pady=20) 78 | 79 | 80 | # Create some buttons 81 | submit_button = Button(root, text="Submit Guess", command=lambda: check_guess(guess_entry, result_label, submit_button, play_again_button, state)) 82 | submit_button.pack(pady=20) 83 | 84 | play_again_button = Button(root, text="Play Again?", command=lambda: reset_game(guess_entry, result_label, submit_button, play_again_button, state)) 85 | play_again_button.pack() 86 | # Hide this button 87 | play_again_button.pack_forget() 88 | 89 | 90 | 91 | 92 | 93 | # On start, reset the game 94 | reset_game(guess_entry, result_label, submit_button, play_again_button, state) 95 | 96 | # Start the app 97 | root.mainloop() 98 | 99 | 100 | # Call our main function' 101 | setup_gui() -------------------------------------------------------------------------------- /hangman.py: -------------------------------------------------------------------------------- 1 | import os 2 | import random 3 | 4 | # clear screen 5 | os.system("clear") 6 | 7 | # creating a list of words 8 | word_list = ['python', 'javascript', 'ruby', 'perl', 'hangman', 'developer', 'coder', 'variable', 'syntax', 'function'] 9 | 10 | # Select random word from our word_list 11 | def get_random_word(): 12 | return random.choice(word_list) 13 | 14 | # Display the current state of the guessed word 15 | def display_word(word, guessed_letters): 16 | return ' '.join([letter if letter in guessed_letters else '_' for letter in word]) 17 | 18 | # Main game logic 19 | def play_hangman(): 20 | # Get the random word 21 | word = get_random_word() 22 | # Get the length of that word 23 | word_length = len(word) 24 | 25 | # Keep track of guessed letters and incorrect gueses 26 | # my_set = {"python", "ruby", "js"} 27 | # sets can't have duplicates, so same letter cant be guessed multiple times 28 | # can check them faster than scanning a list 29 | guessed_letters = set() # letters the player guessed correctly 30 | incorrect_guesses = set() # incorrect letters guessed by the player 31 | lives = 6 # number of incorrect guesses allowed 32 | 33 | # Prompt the user 34 | print("Welcome to Hangman!") 35 | print(f'The word has {word_length} letters') 36 | 37 | # Main game loop 38 | while lives > 0: 39 | # Display the current word status 40 | print("\n" + display_word(word, guessed_letters)) 41 | print(f"Incorrect guesses: {', '.join(incorrect_guesses)}") 42 | print(f'Lives Remaining: {lives}') 43 | 44 | # Prompt the user for a guess 45 | guess = input("Guess a letter: ").lower() 46 | 47 | # Validate the guesses 48 | if len(guess) != 1 or not guess.isalpha(): 49 | os.system("clear") 50 | print("Invalid input. Please enter a single letter.") 51 | continue 52 | # Check if the letter has already been guessed 53 | if guess in guessed_letters or guess in incorrect_guesses: 54 | os.system("clear") 55 | print(f"You already guessed {guess}. Try a different letter.") 56 | continue 57 | # Check if the guess is correct 58 | if guess in word: 59 | os.system("clear") 60 | guessed_letters.add(guess) 61 | print(f'Good Guess! "{guess}" is in the word.') 62 | else: 63 | os.system("clear") 64 | incorrect_guesses.add(guess) 65 | # remove a life 66 | lives -= 1 67 | print(f'Wrong Guess! "{guess}" is not in the word.') 68 | 69 | # check if the player has guessed the entire word 70 | if all(letter in guessed_letters for letter in word): 71 | print(f"\nCongrats!! You guessed the word: {word}") 72 | break 73 | 74 | 75 | 76 | # if the player runs out of lives 77 | if lives == 0: 78 | print("\nYou ran out of lives! The word was: ", word) 79 | 80 | 81 | 82 | 83 | play_hangman() -------------------------------------------------------------------------------- /images.py: -------------------------------------------------------------------------------- 1 | # pip install Pillow 2 | from PIL import Image 3 | 4 | # Function to resize the image 5 | def resize_image(input_path, output_path, new_width): 6 | # Error handling for opening the image with PIL 7 | try: 8 | # Open The Image 9 | # img = Image.open(input_path) 10 | with Image.open(input_path) as img: 11 | # Get the original dimensions 12 | # print(img.size) 13 | # img.size == (960, 720) 14 | width,height = img.size 15 | # Print out our dimensions 16 | print(f"Original Size: {width} x {height}") 17 | 18 | # Calculate the new height to maintain the aspect ratio 19 | aspect_ratio = height / width 20 | 21 | # Aspen.jpg width=960 height=720 22 | # Aspen aspect ratio = .75 23 | # Resized width = 480 resized height = 360 24 | 25 | # get the new height 26 | new_height = int(new_width * aspect_ratio) 27 | 28 | # Resize the image 29 | resized_image = img.resize((new_width, new_height)) 30 | 31 | # Save the new image 32 | resized_image.save(output_path) 33 | 34 | # Output the results to the user 35 | print(f"Image resied and saved as {output_path}. New Size: {new_width} x {new_height}") 36 | 37 | 38 | 39 | 40 | except IOError: 41 | print("Error: Unable to open or save the image. Please check the file paths.") 42 | 43 | 44 | # Main Function 45 | def image_resizer(): 46 | # c:/python-projects/aspen.jpg 47 | input_path = input("Enter the path of the image to resize: ") 48 | output_path = input("Enter the output path for the resized image: ") 49 | new_width = int(input("Enter the new width for the resized image: ")) 50 | 51 | # Resize the image 52 | resize_image(input_path, output_path, new_width) 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | # Call the main function 62 | image_resizer() 63 | -------------------------------------------------------------------------------- /palindrome.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | os.system("clear") 4 | 5 | def is_palindrome(string): 6 | # Remove the spaces and covert to lowercase and strip notation 7 | ''' 8 | cleaned_string = '' 9 | # Loop through our user input 10 | for character in string: 11 | # Check to see if the charcer is a charcter 12 | if character.isalnum(): 13 | cleaned_string += character.lower() 14 | ''' 15 | # Shorthand for the above code: 16 | cleaned_string = ''.join(character.lower() for character in string if character.isalnum()) 17 | 18 | 19 | # Check if the string is the same forwards and backwards 20 | return cleaned_string == cleaned_string[::-1] # backwards slicey thing 21 | 22 | 23 | 24 | 25 | 26 | # Ask the user for input 27 | user_input = input("Enter a Word or phrase to check if it's a palindrome: ") 28 | 29 | # Slice = [start:stop:step] 30 | #user_input = user_input[::-1] 31 | 32 | # Check if true or false 33 | if is_palindrome(user_input): 34 | print(f'{user_input} is a palindrome!') 35 | else: 36 | print(f'{user_input} is NOT a palindrome!') 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /rps.py: -------------------------------------------------------------------------------- 1 | import random 2 | import os 3 | 4 | # Ask to play again 5 | def play_again(): 6 | while True: 7 | # ask to play again 8 | user_input = input("Do you want to play again? (yes/no): ").lower() 9 | # logic for choice 10 | if user_input in ['yes', "no"]: 11 | return user_input == "yes" 12 | else: 13 | print("Invalid input. Please enter 'yes' or 'no'.") 14 | 15 | 16 | # Determine winner 17 | def determine_winner(user_choice, computer_choice): 18 | # Determine tie 19 | if user_choice == computer_choice: 20 | return "It's a tie!!!" 21 | # Determine user winning 22 | elif (user_choice == "rock" and computer_choice == "scissors") or \ 23 | (user_choice == "scissors" and computer_choice == "paper") or \ 24 | (user_choice == "paper" and computer_choice == "rock"): 25 | return "You Win!" 26 | else: 27 | return "Computer Wins!" 28 | 29 | # Get Computers choice 30 | def get_computer_choice(): 31 | # Have the computer select rock, paper, or scissors 32 | choices = ["rock", "paper", "scissors"] 33 | return random.choice(choices) 34 | 35 | # Get users choice 36 | def get_user_choice(): 37 | choices = {1:"rock", 2:"paper", 3:"scissors"} 38 | try: 39 | user_input = int(input("Enter 1 for Rock, 2 for Paper, or 3 for Scissors: ")) 40 | if user_input in choices: 41 | return choices[user_input] 42 | else: 43 | print("Invalid Choice. Please try again.") 44 | return get_user_choice() 45 | 46 | 47 | except ValueError: 48 | print("Invalid Input. Please Enter a Number between 1 and 3.") 49 | return get_user_choice() 50 | 51 | 52 | # Set up the game 53 | def play_game(): 54 | while True: 55 | # Clear the screen 56 | os.system("clear") 57 | # Get the users choice 58 | user_choice = get_user_choice() 59 | # Get the computers choice 60 | computer_choice = get_computer_choice() 61 | 62 | # User output 63 | print(f"You Chose: {user_choice}") 64 | # Computer output 65 | print(f"Computer Chose: {computer_choice}") 66 | 67 | # Determine the winner! 68 | result = determine_winner(user_choice, computer_choice) 69 | # Print the results 70 | print(result) 71 | 72 | # end the game 73 | if not play_again(): 74 | print("Thanks for playing! Goodbye!") 75 | break 76 | 77 | 78 | 79 | 80 | # Play the game! 81 | play_game() -------------------------------------------------------------------------------- /speed.py: -------------------------------------------------------------------------------- 1 | import time 2 | import random 3 | import os 4 | 5 | # Clear the screen 6 | os.system("clear") 7 | 8 | 9 | # List of sentences for the typing 10 | sentences = [ 11 | "The quick brown fox jumps over the lazy dog.", 12 | "Python is an easy to learn programming language.", 13 | "Artificial intelligence will shape the future of technology.", 14 | "Typing speed tests are quite stupid, and a waste of time!", 15 | "Consistent practice is key to mastering any skill." 16 | ] 17 | 18 | 19 | # Function to calculate words per minute (WPM) 20 | def calculate_wpm(start_time, end_time, typed_text): 21 | # calculate the time in seconds that it took to finish 22 | time_taken = end_time - start_time # in seconds 23 | # Calculate the number of words 24 | num_words = len(typed_text.split()) 25 | # Calculate WPM words per minute 26 | wpm = (num_words / time_taken) * 60 # words per minute formula 27 | # return the results 28 | return(round(wpm, 2)) 29 | 30 | 31 | 32 | 33 | # Function to run the typing speed test 34 | def typing_speed_test(): 35 | # Choose a random sentence from our list 36 | sentence = random.choice(sentences) 37 | 38 | print("\n--- Typing Speed Test ---") 39 | print("Type the following sentence as fast as you can:") 40 | print(f"\n{sentence}\n") 41 | 42 | # Tell the user to hit enter to start 43 | input("Press Enter when you're ready to start...") 44 | 45 | # Start the timer 46 | start_time = time.time() 47 | 48 | # Prompt the user to start typing 49 | typed_text = input("\nStart typing here: (hit enter when finished)\n") 50 | 51 | # Get the end time 52 | end_time = time.time() 53 | 54 | # Calculate WPM (words per minute) 55 | wpm = calculate_wpm(start_time, end_time, typed_text) 56 | 57 | # Output the results / check for errors 58 | if typed_text == sentence: 59 | print(f"Great job! Your typing speed is {wpm} words per minute!") 60 | else: 61 | print(f"Your typing speed is {wpm} words per minute, but there were some mistakes in your typing.") 62 | 63 | 64 | 65 | 66 | 67 | 68 | # Main function 69 | def main(): 70 | while True: 71 | # clear the screen 72 | os.system("clear") 73 | # Start the test 74 | typing_speed_test() 75 | # Ask user to try again 76 | retry = input("\nWould you like to try again? (y/n)?").lower() 77 | # Logice to determine what they selected y/n 78 | if retry != "y": 79 | print("Thanks for using the Typing Speed test! Later Duder!") 80 | break 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | # Run our app 90 | main() 91 | 92 | -------------------------------------------------------------------------------- /sub.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import os 3 | 4 | # Clear the screen 5 | os.system("clear") 6 | 7 | # Function to run a selected Python file: 8 | def run_file(filename): 9 | try: 10 | # Run the file 11 | subprocess.run(["winpty", "python", filename], check=True) 12 | 13 | except subprocess.CalledProcessError: 14 | print(f"Error: Could not run {filename}") 15 | 16 | 17 | # Main function 18 | def main_menu(): 19 | while True: 20 | 21 | print("\n--- Main Menu ---") 22 | print("1. Anagram Solver") 23 | print("2. Use Arrows") 24 | print("3. Use Arrows With Tkinter") 25 | print("4. Choose Your Own Adventure") 26 | print("5. Clocks") 27 | print("6. Draw Turtles") 28 | print("7. Open Save Filez") 29 | print("8. Flashcard Game") 30 | print("9. Password Generator") 31 | print("10. Number Guessing Game") 32 | print("11. Number Guessing Game GUI") 33 | print("12. Hangman Game") 34 | print("13. Images") 35 | print("14. Palindrome Checker") 36 | print("15. Rock Paper Scissors") 37 | print("16. Typing Speed Texts") 38 | print("17. Tic Tac Toe") 39 | print("18. To-Do List") 40 | print("19. Password Validator") 41 | print("20. Word Counter") 42 | print("21. Quit") 43 | 44 | # Get choice 45 | choice = input("Choose an option (1-21): ") 46 | 47 | if choice == '1': 48 | run_file('anagram.py') 49 | elif choice == '2': 50 | run_file('arrows.py') 51 | elif choice == '3': 52 | run_file('arrows-tkinter.py') 53 | elif choice == '4': 54 | run_file('choose.py') 55 | elif choice == '5': 56 | run_file('clocks.py') 57 | elif choice == '6': 58 | run_file('draw.py') 59 | elif choice == '7': 60 | run_file('filez.py') 61 | elif choice == '8': 62 | run_file('flash.py') 63 | elif choice == '9': 64 | run_file('generator.py') 65 | elif choice == '10': 66 | run_file('guessing_game.py') 67 | elif choice == '11': 68 | run_file('guessing_game_gui.py') 69 | elif choice == '12': 70 | run_file('hangman.py') 71 | elif choice == '13': 72 | run_file('images.py') 73 | elif choice == '14': 74 | run_file('palindrome.py') 75 | elif choice == '15': 76 | run_file('rps.py') 77 | elif choice == '16': 78 | run_file('speed.py') 79 | elif choice == '17': 80 | run_file('tictactoe.py') 81 | elif choice == '18': 82 | run_file('todo.py') 83 | elif choice == '19': 84 | run_file('validate.py') 85 | elif choice == '20': 86 | run_file('wordcount.py') 87 | elif choice == '21': 88 | print("Exiting the program. Later Duder!") 89 | break 90 | else: 91 | print("Invalid Option. Please selecte from 1-21.") 92 | 93 | 94 | 95 | 96 | 97 | # Run the program 98 | main_menu() -------------------------------------------------------------------------------- /tictactoe.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | # Clear the screen 4 | def clear_screen(): 5 | os.system("clear") 6 | 7 | 8 | ''' 9 | 1 | 2 | 3 10 | --+---+-- 11 | 4 | O | 6 12 | --+---+-- 13 | 7 | 8 | 9 14 | 15 | ''' 16 | 17 | # Print the board 18 | def print_board(board): 19 | print(f"{board[0]} | {board[1]} | {board[2]}") 20 | print("--+---+--") 21 | print(f"{board[3]} | {board[4]} | {board[5]}") 22 | print("--+---+--") 23 | print(f"{board[6]} | {board[7]} | {board[8]}") 24 | print() 25 | 26 | # Check for winner 27 | def check_winner(board, current_player): 28 | # Define winning combinations are 29 | win_combinations = [ 30 | [0,1,2], [3,4,5], [6,7,8], # rows 31 | [0,3,6], [1,4,7], [2,5,8], # columns 32 | [0,4,8], [2,4,6], # diagonals 33 | ] 34 | 35 | # Check if any winning combination is met 36 | for combination in win_combinations: 37 | if board[combination[0]] == board[combination[1]] == board[combination[2]] == current_player: 38 | return True 39 | return False 40 | 41 | 42 | 43 | # Check if draw 44 | def check_draw(board): 45 | # ['1', '2', '3', '4', '5', '6', '7', '8', '9'] 46 | return all(spot in ["X", "O"] for spot in board) 47 | 48 | 49 | 50 | 51 | 52 | 53 | # Main function 54 | def play_tic_tac_toe(): 55 | # Initialze the board (empty spots represented by numbers) 56 | # ['1', '2', '3', '4', '5', '6', '7', '8', '9'] 57 | board = [str(i) for i in range(1,10) ] 58 | 59 | # Define our players 60 | current_player = "X" 61 | 62 | # Main game loop 63 | while True: 64 | clear_screen() 65 | print_board(board) 66 | 67 | # Get player move 68 | move = input(f"Player {current_player}, enter your move (1-9)") 69 | 70 | # Validate the move 71 | if not move.isdigit() or int(move) < 1 or int(move) > 9: 72 | print("Invalid Input. Please enter a number between 1 and 9.") 73 | continue 74 | 75 | # Convert move number to index number by subtracting 1 76 | move = int(move) - 1 77 | 78 | # Check if the spot is already taken 79 | if board[move] in ["X", "O"]: 80 | print("That spot is already taken. Try again") 81 | continue 82 | 83 | # Update the board 84 | # ['X', '2', '3', '4', '5', '6', '7', '8', '9'] 85 | board[move] = current_player 86 | 87 | # Check if the current player has won 88 | if check_winner(board, current_player): 89 | clear_screen() 90 | # Redraw the updated board 91 | print_board(board) 92 | print(f'Player {current_player} wins!') 93 | break 94 | 95 | # Check if game is draw 96 | if check_draw(board): 97 | clear_screen() 98 | print_board(board) 99 | print("It's a Draw!") 100 | break 101 | 102 | 103 | 104 | # Switch players 105 | current_player = 'O' if current_player == "X" else "X" 106 | 107 | 108 | 109 | # Play the game 110 | play_tic_tac_toe() -------------------------------------------------------------------------------- /todo.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | #clear the screen 5 | os.system("clear") 6 | 7 | # Our list will be in this format: 8 | ''' 9 | tasks = [i 10 | {"task": "Walk the dog", "completed": False}, 11 | {"task": "Take a nap", "completed": True}, 12 | {"task": "Wash the car", "completed": False} 13 | ] 14 | 15 | ''' 16 | 17 | # Add a task to the list 18 | def add_task(tasks, task): 19 | # append the new task onto our tasks list 20 | tasks.append({"task": task, "completed": False}) 21 | print(f'Task "{task}" has been added.') 22 | return tasks 23 | 24 | # View the tasks on the list 25 | def view_tasks(tasks): 26 | if not tasks: 27 | print("No Tasks In The List...") 28 | else: 29 | print("\nTo-Do List:") 30 | for idx, task_info in enumerate(tasks, 1): 31 | status = "Done" if task_info["completed"] else "Not Done" 32 | print(f'{idx}. {task_info["task"]} - {status}') 33 | print() 34 | 35 | 36 | 37 | 38 | 39 | 40 | # Remove a task from the list 41 | def remove_task(tasks, task_index): 42 | if 0 <= task_index < len(tasks): 43 | removed_task = tasks.pop(task_index) 44 | #{"task": "Walk the dog", "completed": False}, 45 | print(f'Removed Task: {removed_task['task']}') 46 | else: 47 | print("Invalid Task Number.") 48 | return tasks 49 | 50 | 51 | 52 | 53 | # Mark a task as complete 54 | def mark_task_completed(tasks, task_index): 55 | if 0 <= task_index < len(tasks): 56 | # Update that item 57 | tasks[task_index]["completed"] = True 58 | # Print some output 59 | print(f'Task "{tasks[task_index]["task"]}" marked as completed.') 60 | else: 61 | print("Invalid Task Number") 62 | 63 | return tasks 64 | 65 | 66 | # Main todo function 67 | def to_do_list_app(): 68 | # Create a python list to keep track of our todo list 69 | tasks = [] 70 | 71 | while True: 72 | # Clear the screen 73 | os.system("clear") 74 | 75 | print("\n--- To-Do List Menu ---") 76 | print("1. Add Task") 77 | print("2. View Tasks") 78 | print("3. Remove Task") 79 | print("4. Mark Task as Completed") 80 | print("5. Quit") 81 | 82 | choice = input("Choose An Option: ") 83 | 84 | # Add Task 85 | if choice == '1': 86 | task = input("Enter the Task: ") 87 | tasks = add_task(tasks, task) 88 | # tell the user to hit enter 89 | input("\nPress Enter to Continue...") # pause before clearing the screen 90 | 91 | # View Tasks 92 | elif choice == '2': 93 | view_tasks(tasks) 94 | input("\nPress Enter to Continue...") # pause before clearing the screen 95 | 96 | # Remove tasks 97 | elif choice == '3': 98 | # Check to make sure there are tasks 99 | if tasks: 100 | view_tasks(tasks) # show the list before prompting the user to remove one 101 | task_index = int(input("Enter the task number to remove: ")) - 1 102 | # Call the remove task function and pass in the list and item to remove 103 | tasks = remove_task(tasks, task_index) 104 | else: 105 | print("There are no tasks to remove...") 106 | input("\nPress Enter to Continue...") # pause before clearing the screen 107 | 108 | # Mark Task as completed 109 | elif choice == '4': 110 | # Check to make sure there are tasks 111 | if tasks: 112 | # view the list 113 | view_tasks(tasks) # show the list before prompting the user to remove one 114 | task_index = int(input("Enter the task number to mark as completed: ")) - 1 115 | # Call the markt_task_completed function and pass in the list and item to update 116 | tasks = mark_task_completed(tasks, task_index) 117 | else: 118 | print("There are no tasks to mark as completed...") 119 | input("\nPress Enter to Continue...") # pause before clearing the screen 120 | 121 | # Quit 122 | elif choice == '5': 123 | print("Exiting To-Do List. Goodbye!") 124 | break 125 | 126 | else: 127 | print("Invalid option. Please Try Again") 128 | input("\nPress Enter to Continue...") # pause before clearing the screen 129 | 130 | 131 | 132 | 133 | # Run the app 134 | to_do_list_app() 135 | -------------------------------------------------------------------------------- /validate.py: -------------------------------------------------------------------------------- 1 | import string 2 | import os 3 | 4 | 5 | # Clear the screen 6 | os.system("clear") 7 | 8 | 9 | # Actually validate the password: 10 | def validate_password(password): 11 | # Check our password rules 12 | if len(password) < 8: 13 | return False, "Password must be at least 8 character long." 14 | # Check for digits 15 | if not any(char.isdigit() for char in password): 16 | return False, "Password must contain at least one digit." 17 | # Check for lowercase 18 | if not any(char.islower() for char in password): 19 | return False, "Password must contain at least one lowercase letter." 20 | # Check for uppercase 21 | if not any(char.isupper() for char in password): 22 | return False, "Password must contain at least one uppercase letter." 23 | # Check for special characters 24 | if not any(char in string.punctuation for char in password): 25 | return False, "Password must contain at least one special character." 26 | 27 | # Return true if all the rules were true 28 | return True, "Password is strong!!" 29 | 30 | 31 | # Print out the password rules 32 | def show_password_rules(): 33 | print("Password Rules:") 34 | print("1. Must be at least 8 characters long.") 35 | print("2. Must contain at least one digit (0-9).") 36 | print("3. Must contain at least one lowercase letter (a-z).") 37 | print("4. Must contain at least one uppercase letter (A-Z).") 38 | print("5. Must contain at least one special character (!, @, #, $, etc.).") 39 | print() 40 | 41 | 42 | def password_validator(): 43 | # Show the password rules 44 | show_password_rules() 45 | 46 | # Prompt the user for their password 47 | password = input("Please enter your password: ") 48 | 49 | # Validate the password 50 | bob, message = validate_password(password) 51 | 52 | # Return the result 53 | if bob: 54 | print("Success: ", message) 55 | else: 56 | print("Validation Failed: ", message) 57 | 58 | 59 | # run the program 60 | password_validator() -------------------------------------------------------------------------------- /wordcount.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | # Clear the screen 4 | os.system("clear") 5 | 6 | 7 | # Function to count the number of words in a sentence 8 | def count_words(sentence): 9 | # split our sentence into a python list 10 | words = sentence.split() 11 | 12 | # john elder is cool 13 | # words = ["john", "elder", "is", "cool"] 14 | 15 | # Get the length of the list with len() 16 | return len(words) 17 | 18 | # Function to count the number of characters including spaces 19 | def count_characters_with_spaces(sentence): 20 | # use the len 21 | return len(sentence) 22 | 23 | 24 | # Function to count the number of characters excluding spaces 25 | def count_characters_without_spaces(sentence): 26 | # Remove the spaces from our sentence 27 | return len(sentence.replace(" ", "")) # .replace('thing to replace', 'thing to replace it with') 28 | 29 | 30 | 31 | 32 | # Main function 33 | def word_count_program(): 34 | # Prompt the user 35 | sentence = input("Enter a sentence: ") 36 | 37 | if sentence: 38 | # Get word count and character counts 39 | word_count = count_words(sentence) 40 | char_count_with_spaces = count_characters_with_spaces(sentence) 41 | char_count_without_spaces = count_characters_without_spaces(sentence) 42 | 43 | else: 44 | print("That's not a sentence") 45 | 46 | # Print the results 47 | print(f'Word Count: {word_count}') 48 | print(f'Character Count (with spaces): {char_count_with_spaces} ') 49 | print(f'Character Count (without spaces): {char_count_without_spaces} ') 50 | 51 | # Run the program 52 | word_count_program() 53 | 54 | 55 | --------------------------------------------------------------------------------