Skip to content

Instantly share code, notes, and snippets.

@1328
Created March 4, 2015 16:46
Show Gist options
  • Select an option

  • Save 1328/d29defacb02bbdc94107 to your computer and use it in GitHub Desktop.

Select an option

Save 1328/d29defacb02bbdc94107 to your computer and use it in GitHub Desktop.
x.py
import cmd
from pprint import pprint
class Calculator(cmd.Cmd):
def get_floats(self, line, number = None):
''' get number of floats from line
if number is None, don't worry about the number returned
if cannot float anything in the line it prints help and raises
ValueError
'''
try:
floats = tuple(map(float, line.split()))
if number is not None and len(floats) != number:
raise ValueError('Need more floats!')
return floats
except ValueError as e:
print('Error: {}'.format(e))
print('The correct syntax is')
self.print_help()
raise e
def print_help(self):
''' print the help from the last command run '''
cmd, arg, line = self.parseline(self.lastcmd)
self.onecmd('help {}'.format(cmd))
def do_mpg(self, line):
''' calculate MPG from [miles], [fuel] '''
try:
miles, fuel = self.get_floats(line, 2)
except ValueError:
return
print('\tMPG = {}'.format(miles/fuel))
def do_pay(self, line):
try:
hours, wage = self.get_floats(line, 2)
except ValueError:
return
money = min(hours,40) * wage
money += max(0, hours - 40) * wage * 1.5
print('total pay {} * {} = {}'.format(
hours, wage, money))
def do_EOF(self, line):
''' quit on an empty line '''
return True
if __name__ == '__main__':
Calculator().cmdloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment