---
# System prepended metadata

title: 互相轉換英文字母和數字
tags: [python]

---

```python=
# 字母表
letters = 'abcdefghijklmnopqrstuvwxyz'

# find number function
def find_letter_to_number(letter):
    print(f'{letter}: {letters.index(letter) + 1}')   # 從字母找對應 index

# find letter function
def find_number_to_letter(number):
    print(f'{number}: {letters[number - 1]}')         # 用 index 找對應字母

while True:
    mode = input('Choose mode (1: letter to number, 2: number to letter, type "8888" to leave): ')
    if mode == '8888':                                  # 離開程式
        print('See you!')
        break
    elif mode == '1':
        while True:
            try:
                enter = input('Type any word to find the number, type "8888" to return: ')      # 輸入字母找數字
                if enter == '8888':                     # 返回用途選擇
                    print('GO back!')
                    break
                for character in enter.lower():         # 轉換小寫
                    find_letter_to_number(character)
            except:
                print('Please type in English.')        # 捕捉錯誤，輸入非英文字母等
                continue
    elif mode == '2':
        while True:
            try:
                enter = int(input('Type a number to find the letter, type "8888" to return: '))  # 輸入數字找字母
                if enter == 8888:                       # 返回用途選擇
                    print('GO back!')
                    break
                elif enter not in range(1, 27):         # 設定範圍
                    print('Please type a number between 1 and 26')
                    continue
                else:
                    find_number_to_letter(enter)
            except:
                print('Please type in integer.')        # 捕捉錯誤，如輸入字母或非整數數字
                continue
    else:
        print('Invalid mode. Please choose 1 or 2.')    # 無效模式，重新輸入
```