LoginSignup
0
1

More than 5 years have passed since last update.

何度も調べてしまうのでサンプルプログラムを作っておく①(Pythonのコメントアウト、リスト操作、例外処理)

Posted at

コメントアウト

01_Commnet_Out_Test.py(サンプル)
#! /usr/bin/python
# coding: UTF-8

def Comment_Out_Test():

    #コメントアウトと1  
    #print("コメントアウト")
    print("1")

    '''
    コメントアウト2
    print("コメントアウト")
    '''
    print("2")

#main function
if __name__ == "__main__":
    Comment_Out_Test()
01_Commnet_Out_Test.py(実行結果)
1
2

List操作

02_List_Test.py(サンプル)
#! /usr/bin/python
# coding: UTF-8

def List_Test():
    a = list(range(10))

    print("a = " + str(a))

    b = list(range(3,4))
    print("b = " + str(b))

    c = a+b
    print("c = " + str(c))

    e = c[1:5]
    print("e = " + str(e))

    f = e[:-1]
    print("f = " + str(f))

    g = f[::-1]
    print("g = " + str(g))

    h = g[-1]
    print("h = " + str(h))


#main function
if __name__ == "__main__":
    List_Test()
02_List_Test.py(実行結果)
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [3]
c = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 3]
e = [1, 2, 3, 4]
f = [1, 2, 3]
g = [3, 2, 1]
h = 1

例外処理

04_try_exception.py(サンプル)
#! /usr/bin/python
# coding: UTF-8

import sys

def Try_Except():
    try:#エラーがおきるかもしれない処理
        file = open ('log.txt','a') 
        print("File opened")
        file.write("OK\n")
        print("OK")
    except Exception as e:     #エラーが起きた時
        print("Error:"+str(e))
    finally:    #エラーの有無に関わらず必ず実行
        file.close()
        print("File closed")

#main function
if __name__ == "__main__":
    Try_Except()
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1