0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonメモ

0
Posted at

ツールでよくPython使うので自分用にメモ

Hello World

hello.py
print("Hello, World")
実行
python hello.py

基本

#pythonメモ

# 文字列出力(シングルクォートでもいい)
print("Hello, Python")
print("""Hello, Python""")

# 文字列結合
print("Hello " + "Python") # Hello Python
print("Hello " * 3) # Hello Hello Hello 
print(f"1 - 2 = {1 - 2}") # 1 - 2 = -1

# 数値出力・演算
print(10) # 数値
print(10 + 5) # 足し算
print(5 - 2) # 引き算
print(10 * 2) # 掛け算
print(10 ** 2) # 自乗
print(10 / 2) # 割り算
print(10 // 2) # 割り算(切り捨て)
print(10 % 5) # 余り
print((20 - 5) // 3) # 括弧

# 型変換(キャスト)
print("Hello" + str(24)) # Hello24
print(int("100") + 50) # 150

# リスト型
array = ["Hello", "Python"]
array.append("test")
print(array, array[0])

# 辞書型
dictionary = {"head": "Hello", "body": "Python"}
dictionary["test"] = "test"
print(dictionary, dictionary["test"])

#変数は大文字小文字を区分する。「定数は大文字、変数は小文字」が一般的
x = 10
X = 20
print(x)  # 出力: 10
print(X)  # 出力: 20

#入力待ち
name = input()
print(name)

# 条件式
score = 90
if score > 80:
    print("Great!")
elif score > 60:
    print("Good!")
else:
    print("So So!")

## for 
for i in range(0, 10):
    print(i)
else:
    print("Finish!")

for d in [20, 40, 60, 88]:
    print(d)
else:
    print("Finish!")

continue # 1回スキップ
break # 処理を終了

# 関数
## 定義
def say_hello(name = "satoshi", age = "24"): #これはデフォルト値。(name, age)でもいい。
    print(f"Hi! {name} age({age})") # ""の直前にfを付与すると文字列の中で変数に対応する。

## 呼び出し
say_hello("tom", 20) #デフォルト値より優先される。

## 引数を指摘すれば順番は自由
say_hello(age = 18, name = "john")

## 返り値
def say_hello(name, age):
    return f"Hi! {name} age({age})"
print(say_hello("mint", 28))

# 予約語
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

備忘

main()の前にifがあったりするのは他モジュールからimportとして呼び出されたときにmain()を実行させないため

if __name__ == "__main__":
    main()

\nは改行してから出力したいときに使う。

print("\nコピー完了!")

\rは同じ行に上書きしたいときに使う。
先頭に戻るという意味。
通常print()の最後に改行されるが、end=""で改行無効にする。

print(f"\r進捗: {i}/{len(file_paths)} 件 完了", end="") #同じ行に出力

値の前にrを付与でエスケープが不要になる。通常は\みたいに必要

path = r"C:\Users\Name\Documents\file.txt"
folder = "Users"
print(rf"C:\{folder}\Name")  # C:\Users\Name
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?