Friday, February 08, 2019

Exercises for Programmers: 57 Challenges to Develop Your Coding Skills - Chapter 1 Part f

Version f...I think that's also 6. Break it out into functions. Some of that was already done, but I finished the job. I guess, if I was being a good programmer, I might have it ask whether the tip should be rounded up or not. And yeah, there's some weird code in a few spots, but fast and functional was my goal, not elegant.
 
import math

#Version 1: basic
#Version 2: round up
#Version 3: next, ONLY enter numbers
#Version 4: ask again for a number - already done!
#Version 5: no negative numbers
#Version 6: use some functions

def inputNumber(message):
  while True:
    try:
       returnValue = float(raw_input(message))
       if returnValue < 0:
           raise ValueError
       else:
           return returnValue
    except ValueError:
       return inputNumber("Not a non-negative value! Try again.")

def grandTotal(tip, bill):
    return str(y + (y * x/100))

def grandTotalRounded(tip, bill):
    return str(y + math.ceil((y * x/100)*100)/100)
    
def tipPrint(tip):
    return str((y * x/100)*100)

def tipRoundedPrint(tip):
    return str(math.ceil((y * x/100)*100))


#print("Enter a tip:")
x = inputNumber("Enter a tip:")
print("Tip is: " + str(x))
#print("Enter a bill/total: ")
y = inputNumber("Enter a bill/total: ")
print("Bill is: " + str(y))

#this won't work because I need a precision factor (cents) in my ceil()
#so use full ints?
print("Tip is: " + tipPrint(x) + " cents") #cents
print("Tip rounded up is: " + tipRoundedPrint(x) + " cents")  #what do I expect?
print("Total is: " + grandTotal(x,y))

#with 3% and 1.85 should be 1.91
print("Total rounded up is: " + grandTotalRounded(y,x))

Sigh...mismatched function name.  If I had a dime for every time...

Enter a tip:3
Tip is: 3.0
Enter a bill/total: 82.55
Bill is: 82.55
Tip is: 247.65 cents
Tip rounded up is: 248.0 cents

Traceback (most recent call last):
  File "C:/Python27/TipCalculator.py", line 45, in 
    print("Total is: " + grandTotal(x,y))
NameError: name 'grandTotal' is not defined
>>> ================================ RESTART ================================
>>> 
Enter a tip:3
Tip is: 3.0
Enter a bill/total: 82.55
Bill is: 82.55
Tip is: 247.65 cents
Tip rounded up is: 248.0 cents
Total is: 85.0265
Total rounded up is: 85.03
>>> ================================ RESTART ================================
>>> 
Enter a tip:-2
Not a non-negative value! Try again.1.8
Tip is: 1.8
Enter a bill/total: 77.25
Bill is: 77.25
Tip is: 139.05 cents
Tip rounded up is: 140.0 cents
Total is: 78.6405
Total rounded up is: 78.65

No comments: