try-catch文を使った構造がわからないです。
from string import ascii_uppercase ALLOW_CHARS = ' ' + ascii_uppercase def encrypt(value): nums = [] for c in value: n = ALLOW_CHARS.index(c.upper()) nums.append(n) return nums def send_data(nums): with open('send.txt', 'wt', encoding='utf-8') as f: f.write(nums) def input_loop(): while True: value = input('Input sentence[A-Z,Space]:') try: nums = encrypt(value) except: print(value, 'is not letter or space') else: send_data(nums) def main(): input_loop() if __name__ == '__main__': main()
というサンプルコードがありました。
try-catch文の説明で、
try: <1,例外が発生する可能性のある処理> except: <2,例外処理> else: <3,例外が起こらなかった場合に実行したい処理>
という説明が出てきました。
まずこの例外が発生する可能性のある処理と例外が起こらなかった場合に実行したい処理 の違いがわかりません。
try: <1,例外が発生する可能性のある処理>
と
else: <3,例外が起こらなかった場合に実行したい処理>
が両方呼ばれるときは存在するのでしょうか?
また通常のメソッドなら
def test(): return 2
のようにreturn があるはずなのですが、このサンプルコードのtry-catch文ではreturnがなく、それでなにをinput_loopメソッドでは返しているのだろうと思います。
どのようにこのコードを解釈すれば良いのでしょうか?
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。