テーマ
pythonの基本文法
背景
機械学習でよく聞くpythonについて学びたいと考えたため
内容
pythonとは?
- シンプルで読みやすいことが特徴
- データ分析、Webアプリ開発、機械学習など幅広い分野で利用されている
使い方
出力
# コメントは # を使います
print("Hello, World!") # 出力
変数と型
型は自動判別される。
x = 10 # 整数
y = 3.14 # 小数
name = "Taro" # 文字列
is_ok = True # 真偽値
print(type(x)) # <class 'int'>
print(type(name)) # <class 'str'>
条件分岐
インデントに注意。
age = 20
if age >= 18:
print("大人です")
elif age >= 13:
print("ティーンです")
else:
print("子供です")
繰り返し
forとwhileを使う。
# for文(0〜4を出力)
for i in range(5):
print(i)
# while文(条件を満たす間繰り返す)
count = 0
while count < 3:
print("Hello")
count += 1
関数
def greet(name):
return f"Hello, {name}!"
print(greet("Taro")) # Hello, Taro!
リストと辞書
# リスト
fruits = ["apple", "banana", "orange"]
print(fruits[0]) # apple
# 辞書(キーと値の組み合わせ)
person = {"name": "Taro", "age": 20}
print(person["name"]) # Taro
モジュールの利用
importして用いる。
import math
print(math.sqrt(16)) # 4.0
コメント
インデントに注意してコードを書く必要がある。