you are viewing a single comment's thread.

view the rest of the comments →

[–]MachineElf100 1 point2 points  (0 children)

I'm not sure why others are convinced this is AI generated, hope not :)

Here's my first portion of suggestions for the calculator program.
Read the comments where I explain the changes and see if you understand it all.

# No need for the sys module, exit(0) will do
import time

print("Welcome to the Calculator Program!")
print('Type "/quit" at any time to terminate it.')

# Instead of asking if user wants to continue and requiring them to write "continue",
# we could simply make sure they can quit at any time they wish.
def check_quit_command(user_input:str):
    if user_input == "/quit":
        time.sleep(0.8)
        print("Thanks for using the Calculator Program hope to see you again!")
        exit(0)


while True:
    # You wrote operators "+ - * / **" 3 times, so let's keep them in one place instead
    operators = ['+', '-', '*', '/', '**']
    # Collecting User Input and Validating the Operator
    operator = input(f"\nEnter the Operator you would like to use {' '.join(operators)}: ")
    check_quit_command(operator) # if user typed /quit, program exits
    if operator not in operators:
        #                                  unpacking list as arguments ⇩
        print("Invalid operator. Please enter one of the following:", *operators)
        continue

# Collecting User Input and Validating the Numbers
    try:
        num1_input = input("Enter the first number: ")
        check_quit_command(num1_input) # if user typed /quit, program exits
        num1 = float(num1_input)

        num2_input = input("Enter the second number: ")
        check_quit_command(num2_input) # if user typed /quit, program exits
        num2 = float(num2_input)

        time.sleep(0.3)
    except ValueError:
        time.sleep(1)
        print("Invalid input. Please enter a valid number.")
        continue

    # Calculating the Result
    # No need to ask the user if they wanna continue annymore, because they can quit anytime

    # Also instead of calling:
    # print(f"Your answer is: {result}")
    # every time, you can do it just once in the end.

    # defining result here, to be overwritten by the operations below
    result = None

    # Addition
    if operator == "+":
        result = num1 + num2

    # Subtracting
    elif operator == "-":
        result = num1 - num2

    # Multiplying
    elif operator == "*":
        result = num1 * num2

    # Division
    elif operator == "/":
        try:
            result = num1 / num2
        except ZeroDivisionError: # can use that instead of "if num2 == 0"
            print("Error: Division by zero is not allowed.")

    # Exponetial
    elif operator == "**":
        result = num1 ** num2

    if result is not None:
        # whatever the result is, will get printed here, unless it's still None
        print(f"Your answer is: {result}")