Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## V3 Add-Subtract-Average-Total with Abstraction and Numeric checks ##
- ## Finished Add, Subtract, Average and Total Functions. ##
- ## Used Abstraction to exploit Functions thus simplifying the base logic ##
- ## Further refined by insisting that numeric values must be entered for all function input ##
- ## There still remains the problem of ending the numbers input into the Total function ##
- ## Currently the number 0 is used to end the input whereas I'd prefer either "End" or "end" ##
- # Function to ensure input is numeric
- def inputNumber(message):
- while True:
- try:
- userInput = int(input(message))
- except ValueError:
- print("Not an integer! Try again.")
- continue
- else:
- return userInput
- break
- # Function used for the Add and Subtract operations
- def do_calculation():
- print("lets " + command + " some numbers")
- userInput = inputNumber("Number 1> ")
- number1 = userInput
- userInput = inputNumber("Number 2> ")
- number2 = userInput
- if command == "add":
- result = number1 + number2
- operator = " + "
- elif command == "subtract":
- result = number1 - number2
- operator = " - "
- output = str(result)
- print(str(number1) + operator + str(number2) + " = " + output)
- # Function used for the Average operation
- def do_average():
- numbers = []
- userInput = inputNumber("how many numbers would you like to find the average for? ")
- how_many = userInput
- for item_number in range(how_many):
- display_number = item_number + 1
- item = inputNumber("what is your number " + str(display_number) + "? ")
- numbers.append(item)
- count = 0
- for item in numbers:
- count = count + item
- result = count / how_many
- print("No. of items entered : " + str(len(numbers)))
- print("The average of your " + str(len(numbers)) + " items is " + str(result))
- # Function which implements the Total operation
- def do_total():
- item = int(1)
- item_number = int(0)
- total = int(0)
- while item != 0:
- display_number = item_number + 1
- item = inputNumber("what is your number " + str(display_number) + "? or type the number 0 to end ")
- if item != 0:
- total = total + int(item)
- item_number = item_number + 1
- print("The total of the " + str(item_number) + " numbers you entered is " + str(total))
- print("Would you like to add or subtract two numbers or find the average or total of multiple numbers?")
- command = input("Enter 'add', 'subtract', 'average' or 'total' > ")
- if command == "add":
- do_calculation()
- elif command == "subtract":
- do_calculation()
- elif command == "average":
- do_average()
- elif command == "total":
- do_total()
- else:
- print("Try again and enter 'add', 'subtract', 'average' or 'total' ")
- print("Bye")
Advertisement
Add Comment
Please, Sign In to add comment