LoginSignup
1
1

Pythonの文法

Last updated at Posted at 2022-12-02

Pythonでプログラムを書く機会があったので文法をメモしておく。

コンソールに文字を出力

print('Hollo World!')

定数を宣言

# 定数を宣言
HOLLO_WORLD = 'Hollo World!'

# 定数の内容をコンソールに出力
print(HOLLO_WORLD)

配列を宣言

# 配列を宣言
list = [1, 2, 4, 8]

# 要素0の値をコンソールに表示
print(list[0])

配列の要素を削除

# 配列を宣言
list = ['a', 'b', 'c', 'd']

# 配列の要素を削除
list.remove('b')

# 配列の値をコンソールに表示
print(list)

関数

# 関数を定義
def main():
    print('Hollo World!')

# 関数の呼び出し
main()

配列の要素を数える

# 配列を宣言
list = [1, 2, 4, 8]

# 配列の要素数をコンソールに出力
print(len(list))

if文

if num == 1:
    print('1')
elif num == 2:
    print('2')
else:
    print('3')

while文

while True:
    print('Hollo World!')

例外を発生させる

raise Exception('Error')

try-except(try-catch的なやつ)

try:
    raise Exception('Error')
except:
    print('except')

例外クラスを指定することもできる。

try:
    raise Exception('Error')
except 例外クラス:
    print('except')

ファイルの読み込み

file = open('file.txt', 'r')
text = file.read()
file.close()

コマンドラインで実行された場合のみ処理を継続する

if __name__ == "__main__":
    main()

外部APIを実行(get)

import requests

url = "http://hoge.co.jp"
data = {
    "p1":1,
    "p2":2,
    "text":"test"
}
r = requests.get(url, data=data)

外部APIを実行(post)

import requests

url = "http://hoge.co.jp"
data = {
    "p1":1,
    "p2":2,
    "text":"test"
}
r = requests.post(url, data=data)

外部コマンドを実行

result = subprocess.run(
    [
        'curl',
        '-X',
        'POST',
        '-H',
        'Content-Type: application/json',
        '-d',
        '{"p1":1}',
        'http://hoge.co.jp'
    ]
)

外部コマンドを実行(バックグラウンド)

result = subprocess.Popen(
    [
        'curl',
        '-X',
        'POST',
        '-H',
        'Content-Type: application/json',
        '-d',
        '{"p1":1}',
        'http://hoge.co.jp'
    ]
)

オブジェクトをJSON文字列に変換

data = {
    "p1":1,
    "p2":"test"
}
print(json.dumps(data))

ディレクトリの確認

booleanで返ってくる

import os

os.path.isdir(dir_path)

ディレクトリの作成

import os

os.mkdir('dir_path')

ディレクトリの削除

import os

os.remove('dir_path')

中身ごと削除する場合は以下。

import shutil

shutil.rmtree('dir_path')
1
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
1
1