|
| 1 | +# Calculate a restaurant rating |
| 2 | + |
| 3 | +# define |
| 4 | +REDON = "\033[31m" # Red text. |
| 5 | +ORANGEON = "\033[38;2;255;165;0m" |
| 6 | +YELLOWON = "\033[38;2;255;255;0m" |
| 7 | +GREENON = "\033[32m" # Green text. |
| 8 | +COLOUROFF = "\033[0m" #Reset special formatting (such as colour). |
| 9 | + |
| 10 | +# Custom Errors |
| 11 | +class OutOfRange( ValueError ): |
| 12 | + pass |
| 13 | + |
| 14 | +class OutOfRangeLow (OutOfRange): |
| 15 | + pass |
| 16 | + |
| 17 | +class OutOfRangeHigh (OutOfRange): |
| 18 | + pass |
| 19 | + |
| 20 | +def average(lst): |
| 21 | + return sum(lst) / len(lst) |
| 22 | + |
| 23 | +def percentage(numitems, ttlitems): |
| 24 | + return (numitems / ttlitems) * 100 |
| 25 | + |
| 26 | +def get_colour(i_val): |
| 27 | + if i_val < 1.5: |
| 28 | + s_colour = REDON |
| 29 | + elif i_val < 3: |
| 30 | + s_colour = ORANGEON |
| 31 | + elif i_val < 4: |
| 32 | + s_colour = YELLOWON |
| 33 | + else: |
| 34 | + s_colour = GREENON |
| 35 | + return s_colour |
| 36 | + |
| 37 | +l_votes=[[], 0, 0, 0, 0, 0] |
| 38 | +i_val="" |
| 39 | +# get input |
| 40 | +while True: |
| 41 | + try: |
| 42 | + s_val = input ("Please enter your rating [1 (lowest) - 5 (highest)] (-1 to exit) :") |
| 43 | + i_val = int( s_val ) |
| 44 | + |
| 45 | + if i_val == -1: |
| 46 | + break |
| 47 | + elif i_val < 1: |
| 48 | + raise OutOfRangeLow |
| 49 | + elif i_val > 5: |
| 50 | + raise OutOfRangeHigh |
| 51 | + else: |
| 52 | + l_votes[0].append(i_val) |
| 53 | + l_votes[i_val] += 1 |
| 54 | + |
| 55 | + except OutOfRange as err: |
| 56 | + if isinstance(err,OutOfRangeLow): |
| 57 | + print ("If you think the vote is that low, please contact the Councils Public health or Trading standards as appropriate.") |
| 58 | + print ("1 is the lowest you can record here, please try again.") |
| 59 | + elif isinstance(err,OutOfRangeHigh): |
| 60 | + print ("We're happy you think the restaurant is that good.") |
| 61 | + print ("Please contact the restaurant and let them know.") |
| 62 | + print ("5 is the highest you can record here, please try again.") |
| 63 | + i_val="" |
| 64 | + except ValueError as err: |
| 65 | + print (f'Invalid value entered [{s_val}], ensure you enter an integer between 1 and 5') |
| 66 | + i_val="" |
| 67 | + |
| 68 | +if (len(l_votes[0]) == 0): |
| 69 | + print ( "No ratings were entered :(") |
| 70 | +else: |
| 71 | + i_votes=len(l_votes[0]) |
| 72 | + print (f"There were {i_votes} ratings entered") |
| 73 | + for i in range (1, 6): |
| 74 | + s_colour=get_colour(i) |
| 75 | + print (f"{s_colour}{'*' * i:>6}{COLOUROFF}: {l_votes[i]:>4} [{percentage(l_votes[i],i_votes):6.2f}%]") |
| 76 | + |
| 77 | + i_avg=average(l_votes[0]) |
| 78 | + s_colour=get_colour(i_avg) |
| 79 | + |
| 80 | + print( f'The overall rating is {s_colour} {i_avg:.1f} {COLOUROFF}') |
0 commit comments