Recommended Posts

Made my first program using KJDElectronics' video tutorials of Python! This is the edited and cleaned up version i made after reading some advice about splitting up functions so that they can become more usable. Really happy with it and I'm still waiting on some more constructive criticism and ways to improve it! Here it is!


"""Calculator"""

# Modules:

import time     # used as an illusion of loading for effects
import random   # used for random numbers in random_operation function
import sys      # used to exit program when needed


# Operations:

def add(num1, num2):
    #   Defines addition
    return num1 + num2


def sub(num1, num2):
    # Defines subtraction
    return num1 - num2


def mul(num1, num2):
    # Defines multiplication
    return num1 * num2


def div(num1,num2):
    # Defines division
    try:
        return num1 / num2
    except ZeroDivisionError:
        # Handles division by zero
        print("Division by zero cannot be done. Returning zero...")
        return 0


def exp(num1, num2):
    # Defines exponentiation
    return num1 ** num2


# Run operation function:

def run_operation(operation, num1, num2):
    # Determine operation
    if operation == int("1"):
        print("Adding...")
        time.sleep(1)
        print(num1, "+", num2, "=", add(num1, num2))
    elif operation == int("2"):
        print("Subtracting...")
        time.sleep(1)
        print(num1, "-", num2, "=", sub(num1, num2))
    elif operation == int("3"):
        print("Multiplying...")
        time.sleep(1)
        print(num1, "*", num2, "=", mul(num1, num2))
    elif operation == int("4"):
        print("Dividing...")
        time.sleep(1)
        print(num1, "/", num2, "=", div(num1, num2))
    elif operation == int("5"):
        print("Raising to the power...")
        time.sleep(1)
        print(num1, "^", num2, "=", exp(num1, num2))
    else:
        print("I don't understand")
        time.sleep(1)


# Random operation function

def random_operation(operation):
        for loop in range(4):    # repeats random calculations 4 times
            valid_input = False
            while not valid_input:   # while loop for invalid inputs
                try:
                    operation = (input("What would you like me to do? add, subtract, multiply, divide, or "
                                       "raise to the power?..."))
                    valid_input = True
                except ValueError:
                    print("I don't understand...")
                    time.sleep(1)
                # Defines random calculations
                random_num1 = random.randint(1, 100)
                random_num2 = random.randint(1, 100)
                if operation == str("add"):
                    print("Randomizing")
                    time.sleep(1)
                    print(random_num1, "+", random_num2, "=", add(random_num1, random_num2))
                    time.sleep(1)
                elif operation == str("subtract"):
                    print("Randomizing")
                    time.sleep(1)
                    print(random_num1, "-", random_num2, "=", sub(random_num1, random_num2))
                    time.sleep(1)
                elif operation == str("multiply"):
                    print("Randomizing")
                    time.sleep(1)
                    print(random_num1, "*", random_num2, "=", mul(random_num1, random_num2))
                    time.sleep(1)
                elif operation == str("divide"):
                    print("Randomizing")
                    time.sleep(1)
                    print(random_num1, "/", random_num2, "=", div(random_num1, random_num2))
                    time.sleep(1)
                elif operation == str("raise to the power"):
                    print("Randomizing")
                    time.sleep(1)
                    print(random_num1, "^", random_num2, "=", exp(random_num1, random_num2))
                    time.sleep(1)
                else:
                    print("I don't understand")
                    time.sleep(1)
        print('\nPLEASURE CALCULATING WITH YOU.')
        time.sleep(1)
        print('GOODBYE...')
        time.sleep(1)
        sys.exit()    # Exits program


# Main calculator function:

def main():
    user_continue = True
    while user_continue:          # Loops if user would like to restart program
        valid_input = False
        while not valid_input:      # Loops if user enters an invalid input. Avoids error
            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? 1. Addition, 2. Subtraction, 3. Multiplication, "
                                      "4. Division, 5. Exponentiation... Choose a number..."))
                valid_input = True
            except ValueError:      # Handles any value errors
                print("invalid input, please try again...")
                time.sleep(1)
        run_operation(operation, num1, num2)
        time.sleep(1)
        # Ask if user wants to do random calculations or exit:
        restart_random = (str(input("Would you like to make more calculations? (y) for yes, anything else for no..."
                                    "\n OR would you like a random calculation?...(r) for random calculations then "
                                    "exit...anything else for no...")))

        if restart_random != "y" and restart_random != "r":
            print("PLEASURE CALCULATING WITH YOU!")
            time.sleep(1)
            print("\nGOODBYE!")
            time.sleep(1)
            user_continue = False
        elif restart_random == "r":
            time.sleep(1)
            random_operation(operation)

# intro-like sequence
print('\n\n       Calculator\n\n')
time.sleep(1)
print('     ---LOADING---\n')
time.sleep(1)
print('HI. I AM YOUR PERSONAL CALCULATOR BEEP BOOP. \n WHAT WOULD YOU LIKE ME TO CALCULATE?..\n')
time.sleep(1)

# call main function to start program
main()

# Turns my program into a module capable of being imported:
if __name__ == '__calculator__':
    main()

calculator.py

Edited by Apollo
Updated to use codebolck

Share this post


Link to post
Share on other sites

Looks great! Your calculator() function is a bit lengthy. Think about different ways you can break up the code into smaller functional components. The smaller you make functions (by small I mean functions that do a single well defined thing) then the more you can reuse those functions. 

Great work!

Share this post


Link to post
Share on other sites

@Kevin I've done what you'd advised me to do for my program! This is the edited version... I believe that the program is now sufficiently tidy and reusable. I've followed all of the PEP8 guidelines but if there is anything that i can do to improve my code, please let me know! Thank you!

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...