O'Reilly logo
  • Longxiang Lyu thinks this is interesting:

10-11. Favorite Number:


Cover of Python Crash Course


import json

filename = 'number.json'

def get_number(): try: with open(filename, 'r') as fo: number = json.load(fo) except EnvironmentError: return None else: return number

def prompt_number(): number = get_number() if number: print("I know your favorite number! It's " + str(number)) else: while True: s = raw_input("Enter your favorite number: ") try: number = float(s) except ValueError: pass else: break with open(filename, 'w') as fo: json.dump(number, fo)