2017年1月6日金曜日

開発環境

Python Crash Course (Eric Matthes (著)、No Starch Press)のPART1(BASICS)、Chapter 10.(FILES AND EXCEPTIONS)のTRY IT YOURSELF 10-11、12、13(No.6007)を取り組んでみる。

TRY IT YOURSELF 10-11、12、13(No.6007)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

print('10-11')

import json

n = input('favorite number: ')

filename = 'favorite_number.json'
with open(filename, 'w') as f:
    json.dump(n, f)

with open(filename) as f:
    m = json.load(f)

print(m)

print('10-12')

filename1 = 'favorite_number1.json'

for _ in range(2):
    try:
        with open(filename1) as f:
            a = json.load(f)
        print(a)
    except Exception as err:
        n = input('favorite number: ')
        with open(filename1, 'w') as f:
            json.dump(n, f)

print('10-13')


def get_stored_username():
    filename = 'username.json'
    try:
        with open(filename) as f:
            username = json.load(f)
    except FileNotFoundError:
        return None
    else:
        return username


def get_new_username():
    username = input('What is your name? ')
    filename = 'username.json'
    with open(filename, 'w') as f:
        json.dump(username, f)
    return username


def greet_user():
    username = get_stored_username()
    if username:
        y = input('{0}: correct username?(y/n)'.format(username))
        if y == 'y':
            print('Welcome back, {0}!'.format(username))
        else:
            get_new_username()
    else:
        username = get_new_username()
        print("We'll remember you when you come back, {0}!".format(username))

for _ in range(4):
    greet_user()

入出力結果(Terminal, IPython)

$ ./sample11.py
10-11
favorite number: 1
1
10-12
favorite number: 2
2
10-13
What is your name? kamimura
We'll remember you when you come back, kamimura!
kamimura: correct username?(y/n)y
Welcome back, kamimura!
kamimura: correct username?(y/n)n
What is your name? python
python: correct username?(y/n)y
Welcome back, python!
$

0 コメント:

コメントを投稿