- Consider prompting for input using a function wrapping a loop.
- Don't use input for general user input, use raw_input instead
- Wrap your script execution in a main function so it doesn't execute on import
def ask_positive_integer(prompt, warning="Enter a positive integer, please!"):
while True:
response = raw_input(prompt)
try:
response = int(response)
if response < 0:
print(warning)
else:
return response
except ValueError:
print(warning)
def ask_in_or_out(prompt, warning="In or out, please!"):
'''
returns True if 'in' False if 'out'
'''
while True:
response = raw_input(prompt)
if response.lower() in ('i', 'in'): return True
if response.lower() in ('o', 'ou', 'out'): return False
print warning
def main():
start = ask_positive_integer('How much did you start with?: ')
in_ = ask_in_or_out('Cool! Now have you put money in or taken it out?: ')
if in_:
in_amount = ask_positive_integer('Well done! How much did you put in?: ')
print(start + in_amount)
else:
out_amount = ask_positive_integer('Well done! How much did you take out?: ')
print(start - out_amount)
if __name__ == '__main__':
main()