2018年1月31日水曜日

開発環境

Teach Your Kids to Code: A Parent-Friendly Guide to Python Programming (Bryson Payne(著)、No Starch Press)のChapter 5.(Conditions (What If?))、PROGRAMMING CHALLENGES、#2: USER-DEFINED KEYSを取り組んでみる。

#2: USER-DEFINED KEYS

コード(Emacs)

Python 3

#!/usr/bin/env python3
import sys

ed = input('encode or decode (e or d): ')
if ed == 'e':
    message = input('Enter a message to encode: ')
elif ed == 'd':
    message = input('Enter a message to decode: ')
else:
    sys.exit(1)

n = int(input('Enter a key value(from 1 to 25): '))

output = ''
for letter in message:
    if letter.isupper():
        if ed == 'e':
            value = ord(letter) + n
            letter = chr(value)
        else:
            value = ord(letter) - n
            letter = chr(value)
        if not letter.isupper():
            value -= 26
            letter = chr(value)
    output += letter

print(f'Output message: {output}')

入出力結果(Terminal, Jupyter(IPython))

$ ./sample2.py
encode or decode (e or d): e
Enter a message to encode: ABCDE
Enter a key value(from 1 to 25): 5
Output message: FGHIJ
$ ./sample2.py
encode or decode (e or d): d
Enter a message to decode: FGHIJ
Enter a key value(from 1 to 25): 5
Output message: ABCDE
$

0 コメント:

コメントを投稿

関連コンテンツ