Search code examples
pythonpycharmuser-inputcalculator

Multiple inputs are needed for a basic calculator before resetting


My program is almost complete but I can't seem to allow the...

"Would you like to do more calculations? Enter (Y) for yes, or any ""other character for no. "

...output from going through without first entering my selection (e.g. "Y" or any other character") numerous times.

Output

I would really appreciate some help!

"""My First Program!!!"""

# Modules:

import time     # Provides time-related functions


# Delayed text to give it a "Turing" feel

def calculator_print(*args, delay=1):
    print(*args)
    time.sleep(delay)

# Operations:


def add(num1, num2):
    #   Returns the sum of num1 and num2
    return num1 + num2


def sub(num1, num2):
    #   Returns the difference of num1 and num2
    return num1 - num2


def mul(num1, num2):
    #   Returns the product of num1 and num2
    return num1 * num2


def div(num1, num2):
    #   Returns the quotient of num1 and num2
    try:
        return num1 / num2
    except ZeroDivisionError:
        # Handles division by zero
        calculator_print("Division by zero cannot be done. You have broken the universe. Returning zero...")
        return 0


def exp(num1, num2):
    #   Returns the result of num1 being the base and num2 being the exponent
    return num1 ** num2


# Run operational functions:

def run_operation(operation, num1, num2):
    # Determine operation
    if operation == 1:
        calculator_print("Adding...\n")
        calculator_print(num1, "+", num2, "=", add(num1, num2))
    elif operation == 2:
        calculator_print("Subtracting...\n")
        calculator_print(num1, "-", num2, "=", sub(num1, num2))
    elif operation == 3:
        calculator_print("Multiplying...\n")
        calculator_print(num1, "*", num2, "=", mul(num1, num2))
    elif operation == 4:
        calculator_print("Dividing...\n")
        calculator_print(num1, "/", num2, "=", div(num1, num2))
    elif operation == 5:
        calculator_print("Exponentiating...\n")
        calculator_print(num1, "^", num2, "=", exp(num1, num2))
    else:
        calculator_print("I don't understand. Please try again.")


def main():
    # Ask if the user wants to do more calculations or exit:
    def restart(response):
                    # uses "in" to check multiple values,
                    # a replacement for (response == "Y" or response == "y")
                    # which is longer and harder to read.
        if response in ("Y", "y"):
            return True
        else:
            calculator_print("Thank you for calculating with me!")
            calculator_print("BEEP BOOP BEEP!")
            calculator_print("Goodbye.")
            return False

# Main functions:

    #  Title Sequence
    calculator_print('\n\nThe Sonderfox Calculator\n\n')
    calculator_print('     ----LOADING----\n\n')
    calculator_print('Hello. I am your personal calculator. \nBEEP BOOP BEEP. \n\n')
    while True:  # Loops if user would like to restart program
        try:
            # Acquire user input
            num1 = (int(input("What is number 1? ")))
            num2 = (int(input("What is number 2? ")))
            operation = int(input("What would you like to do? \n1. Addition, 2. Subtraction, 3. Multiplication, "
                                  "4. Division, 5. Exponentiation \nPlease choose an operation: "))
        except (NameError, ValueError):  # Handles any value errors
            calculator_print("Invalid input. Please try again.")
            return
        run_operation(operation, num1, num2)
        # Ask if the user wants to do more calculations or exit:
        restart_msg = input("Would you like to do more calculations? Enter (Y) for yes, or any "
                            "other character for no. ")
        if not restart(str(input(restart_msg))):  # uses the function I wrote
            return


main()

Solution

  • If this is really your first program, that's truly impressive!

    So, I've pasted the code we want to focus on below:

    restart_msg = input("Would you like to do more calculations? Enter (Y) for yes, or any other character for no. ")
    if not restart(str(input(restart_msg))):  # uses the function I wrote
        return   # Stop the program
    

    In the first line, the computer prompts for an input with "Would you like to do more calculations?" (and so on). It then stores that first input in the variable restart_msg. Then, in the second line, you call restart(str(input(restart_msg))). Since that contains a call to input() and passes restart_msg as the only parameter, the computer prompts for an input by outputting whatever you just entered. It stores that entry in a string, and passes it to restart().

    It seems like this is your intention in the second line:

    if not restart(str(restart_msg)):
    

    That way, the computer converts the first input you entered to a string by passing it through str(), and passes that through your restart function.

    This is a pretty ambitious project, good luck!