2
2

More than 3 years have passed since last update.

【初学者向け】Python基礎を総まとめ~アプリも紹介~

Last updated at Posted at 2021-02-28

この記事はこれからPythonを学んでいこうという人のための記事になります。
AIや解析などで注目が上がるpythonの基本をまとめてみました。
言葉の説明は細かくはしていませんので、わからないことは都度都度でググればより理解が深まると思います。
内容に合わせて「寄り道編」を用意しています。
読み進めると文字当てゲームや電卓、パスワード解析などのアプリ紹介もしているので手を動かしてやってみたい人は参考にしてみてください。

この記事を読むことで学習できる内容は以下の通り。
① 5つの基本操作 [ 文字 / 描画 / 数字 / 計算 / インプット ]
② 基本その2:[リスト型 / タプル型 / 辞書型 / 関数 / 条件分岐 / 応用 ]
③ 基本その3:[ while / for / ネスト処理 / 変換 ]
④ 基本その4:[ バリデーション / ファイル操作 ]
⑤ 基本その5:[ クラスとオブジェクト ]

実行環境

・python 3.9
・VSCode
・MacOS 10.15.7

5つの基本操作:[ 文字 / 描画 / 数字 / 計算 / インプット ]

### 1 文字出力
print("Hello World") # Hello World



### 2 線を描画 (例)鳥居
print("_ _ _ _ _ _")
print("_|_ _|_ _|_")
print(" |       | ")
print(" |       | ")
print(" |       | ")
# _ _ _ _ _ _
# _|_ _|_ _|_
#  |       | 
#  |       | 
#  |       | 



### 3 変数:文字の代入
char_name = "SU-NE-O"
char_age = "11"
print("His name is " + char_name) # His name is SU-NE-O
print("He is " + char_age + " years old") # He is 11 years old



### 4 String[文字]の挙動
print("This is\nPython")
# This is 
# Python ←\nで改行
print("This is\"Python") # This is"Python ←\以下の"が文字認識

text = "Sample Text"
print(text.lower())  # sample text ←小文字変換
print(text.upper())  # SAMPLE TEXT ←大文字変換
print(text.isupper())  # False ←大文字をTrue or Falseで返す
print(text.upper().isupper())  # True ←先にupper()で変換されるのでTrue
print(text[0])  # S ←文字の一番最初を返す。2番目は1で、最後は-1
print(text.replace("Sample", "Python"))  # Python Text に置き換わる



### 5 Number[数字]の挙動
print(2)  # 2
print(3.4)  # 3.4
print(8 + 3)  # 11.3 足し算
print(8 - 3)  # 5 引き算
print(8 * 3)  # 24 掛け算
print(8 / 3)  # 2.6666666666666665 割り算
print(8 % 3)  # 2 あまり
print(8 * (3 + 2))  # 40 四則演算



# 6 数字のいろんな変換
num = -5
print(str(num) + " is my number")  # -5 is my number ←number型はstringに変えないとエラー
print(abs(num))  # 5 絶対値
print(pow(5, 3))  # 125 累乗の計算 5の3乗
print(max(6, 4))  # 6 数が多い方を出力
print(min(6, 4))  # 4 数が少ない方を出力
print(round(3.3))  # 3 四捨五入。 3.7の場合4
  # 以下はmathが必要
  from math import *
  print(floor(3.7))  # 3 引数の整数
  print(ceil(3.7))  # 4 引数の数の繰り上げ整数
  print(sqrt(36))  # 6.0 ルート(平方根)計算



# 7 ユーザーからの入力 ←commandでの操作を反映させるinput()
name = input("Enter your name: ")  # Enter your name: [任意の名前]
age = input("Enter your age: ")  # Enter your name: [任意の年齢]
print("Hello " + name + "! You are " + age)
# Hello [任意の名前]! You are [任意の年齢]

ちょっと寄り道 ~ 足し算の電卓をcommandで

### 8 ユーザーが入力した値で計算
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = float(num1) + float(num2) # ユーザーから入力された値はデフォルトで文字なので、数字をfloat()で囲む
print("足し算の結果は " + str(result) + " だよ") 

# Enter a number: 2.5
# Enter another number: 3.7
# 足し算の結果は 6.2 だよ

基本その2:[リスト型 / タプル型 / 辞書型 / 関数 / 条件分岐 / 応用 ]

リスト型:

基本形は[ ]。設定されたリスト内の値は操作可能。

### 9 リストの基本操作
friends = ["Yuta", "Kana", "Tatsuya", "Jim", "Maria"]

print(friends)  # ['Yuta', 'Kana', 'Tatsuya', 'Jim', 'Maria']
print(friends[0])  # Yuta
print(friends.index("Kana"))  # 1 値のインデックス番号取得
print(friends[1:])  # ['Kana', 'Tatsuya', 'Jim', 'Maria'] インデックス番号が 1以上のものを出力
print(friends[1:3])  # ['Kana', 'Tatsuya'] インデックス番号が 1以上3未満を出力
friends[1] = "Abe" # インデックス1をAbeで代入 ↓
print(friends) # ['Yuta', 'Abe', 'Tatsuya', 'Jim', 'Maria']




### 10 そのほかのリスト操作
numbers = [4, 5, 10, 23, 36, 42]
friends = ["Yuta", "Kana", "Tatsuya", "Jim", "Maria"]

friends.extend(numbers)  # リストをつなげる
print(friends)
# ['Yuta', 'Kana', 'Tatsuya', 'Jim', 'Maria', 4, 5, 10, 23, 36, 42]

friends.append("Baiden")  # リストの最後に追加する
print(friends) #['Yuta', 'Kana', 'Tatsuya', 'Jim', 'Maria', 'Baiden']

friends.insert(1, "Trump") # insert(index番号,値)で特定の場所に挿入
print(friends) # ['Yuta', 'Trump', 'Kana', 'Tatsuya', 'Jim', 'Maria']

friends.remove("Jim")  # remove(値)で値をリストから削除
print(friends)  # ['Yuta', 'Kana', 'Tatsuya', 'Maria']

friends.clear()  # clear()でリスト内を全削除
print(friends)  # []

friends.pop()  # リスト最後の値を削除
print(friends)  # ['Yuta', 'Kana', 'Tatsuya', 'Jim']

print(friends.count("Tatsuya")) # 1 count(値)でリスト内の値の数を出力

friends.sort() # アルファベット順(数字なら小さい順)に並び替える
print(friends) # ['Jim', 'Kana', 'Maria', 'Tatsuya', 'Yuta']

friends.reverse() # 元のリストの逆で並び替え
print(friends) # ['Maria', 'Jim', 'Tatsuya', 'Kana', 'Yuta']

friends2 = friends.copy()  # リストをコピー
print(friends2)  # ['Yuta', 'Kana', 'Tatsuya', 'Jim', 'Maria']

タプル型:

基本形は( )。タプルは変更や削除ができないなどリストと比較して限定的。
使うとコードの保守性が高くなる。定数リストとも言われている。

### 11 タプルは操作が限定的。

color = ("red", "blue")
print(color) # ('red', 'blue') アクセスはできる。

color = ("red", "blue")
print(color)  # ('red', 'blue')

color[0] = "black"
print(color) # TypeError: 'tuple' object does not support item assignment

print(color.index("red")) # 0 
print(color.count("blue")) # 1 
# タプルでできる他のメソッドは以下の記事を参考に。
# https://blog.codecamp.jp/python-tuple

辞書型:

基本形は{ key:value }。keyとvalueの組み合わせが含まれているデータ型。
特定の要素を検索、追加、削除でき、リストと違って順番がないので要素を取り出す場合はkeyを指定する。

### 12 辞書型の基本 "key": "value"

months = {
    "Jan": "January",
    "Feb": "February",
    "Mar": "March"
}
print(months["Jan"])  # January  valueが出力される
print(months.get("Mar"))  # March  存在するkeyを取得。なければNoneを返す
print(months.get("Lux", "Not a valid key")) # Not a valid key  keyがない時の定型文を指定できる



### 13 keyが数字の場合と検索 / 追加 / 削除

weights = {
    0: "big",
    1: "small",
    2: "normal"
}

print(weights[1])  # small
print(0 in weights.keys())  # True  .keys()でkeyの存在判定ができる
print("small" in weights.values())  # True  .values()でvalueの存在判定ができる

weights[3] = "can not judge"  # 要素の追加
print(weights)  # {0: 'big', 1: 'small', 2: 'normal', 3: 'can not judge'}

weights.setdefault(5, "so big")  # setdefault()でも追加できる
print(weights) # {0: 'big', 1: 'small', 2: 'normal', 3: 'can not judge', 5: 'so big'}

weights.pop(1)  # 要素の削除(keyを指定)
print(weights)  # {0: 'big', 2: 'normal', 3: 'can not judge', 5: 'so big'}

weights.clear()  # 要素の全削除
print(weights)  # {}

関数:

基本形は def 関数名 ( ):


### 14 関数の基本
def say_hello():
    return "Hello User" # say_halloを呼び出すと Hello User を返す

print(say_hello()) # Hello User



### 15 引数指定
def say_hello(name, age):
    return "Hello " + name + " ! your age is " + str(age) + " !"

print(say_hello("Mike", 22))  # Hello Mike ! your age is 22 !



### 16 関数で計算 (例)立方体の体積
def cube(num):
    return num*num*num

print(cube(4))  # 64 

条件分岐:

### 17 if文で条件分岐
is_male = True

if (is_male):
    print("you are a male")
else:
    print("you are not a male")

# you are a male ←is_maleがTrue
# you are not a male ←is_maleがFalse



### 18 条件が2つ以上
is_male = True
is_tall = True

# AまたはBの場合
if is_male or is_tall:
    print("you are a male or tall or both")
else:
    print("you neither male nor tall")
# you are a male or tall or both ←is_maleがTrue または is_tallがTrue
# you are not a male ←is_maleがFalse ←is_male と is_tallどちらもFalse


# AかつBの場合
if is_male and is_tall:
    print("you are a male and tall")
else:
    print("you are not a male or tall or both")
# you are a male and tall ←is_maleとis_tallがTrue
# you are not a male or tall or both ←is_maleまたはis_tallまたはどちらもFalse


# さらに条件分岐したいときは elif
if is_male and is_tall:
    print("you are a male and tall")
elif is_male and not(is_tall):
    print("you are a male but not tall")
elif is_tall and not(is_male):
    print("you are not a male but tall")
else:
    print("you are not a male and tall")

# you are a male and tall ←is_maleとis_tallがTrue
# you are a male but not tall ←is_maleがTrueでis_tallがFalse
# you are not a male but tall ←is_maleがFalseでis_tallがTrue
# you are not a male and tall  ←is_maleとis_tallがFalse

応用: 条件式で遊んでみる

### 19 最大値の出力
def max_num(num1, num2, num3):
    if num1 >= num2 and num1 >= num3:
        return num1
    elif num2 >= num1 and num2 >= num3:
        return num2
    else:
        return num3

print(max_num(3, 40, 8)) # 40
print(max_num(300, 40, 8)) # 300




### 20 文字の判断
def judge(kinds, name):
    if kinds == 'dog' and name == 'Hachi':
        return 'The dog is Hachi'
    elif kinds != 'dog' and name == 'Hachi':
        return 'Hachi. but not dog'
    else:
        return 'can not judge'


print(judge("cat", "Hachi")) # Hachi. but not dog

寄り道 ~ 計算機を関数で作ってみよう

### 21 2つの数字をcommand上で操作

num1 = float(input("Enter first number: "))
op = input("Enter operator( +, -, /, *, % ): ")
num2 = float(input("Enter second number: "))

if op == "+":
    print(num1 + num2)
elif op == "-":
    print(num1 - num2)
elif op == "/":
    print(num1 / num2)
elif op == "*":
    print(num1 * num2)
elif op == "%":
    print(num1 % num2)
else:
    print("Invalid operator")
# 実行後、オペレーションに応じて計算可

基本その3:[ while / for / ネスト処理 / 変換 ]

While文:

ループ処理の鉄板。

### 22 While文のループ

i = 1
while i <= 5:
    print(i)
    i += 1
print("Done with Loop")

# 1
# 2
# 3
# 4
# 5
# Done with Loop
## Whileが完了されるまでは次に行かないのでこれを応用すると推理ゲームが作れる




### 23 whileを使った簡易推理ゲーム

secret_word = "otakara"  # 正解の言葉
guess = ""  # ユーザーが入力した言葉
guess_count = 0 #ユーザーが推理した数
guess_limit = 5 # 推理の上限
out_of_guesses = False # 上限以上ならTrueでWhileから外れる

while guess != secret_word and not(out_of_guesses):
    if guess_count < guess_limit:
        guess = input("Enter guess: ")
        guess_count += 1
    else:
        out_of_guesses = True

if out_of_guesses:
    print("You LOSE!")
else:
    print("You Win!")

# Enter guess: msvps
# Enter guess: skmsp
# Enter guess:  spv
# Enter guess: dmvpsd
# Enter guess: otakara
# You Win!

For文:

ループ処理の鉄板。rangeを使って範囲を指定することもできる。

### 24 言葉を分解するforのループ
for letter in "soccer":  # soccerのアルファベットが分解される
    print(letter)
# s
# o
# c
# c
# e
# r




### 25 配列を使ったforのループ
frinds = ["jim", "kevin", "mike", "karen"]
for friend in frinds:
    print(friend)
# jim
# kevin
# mike
# karen




### 26 range()でより応用が効くループに
for index in range(len(frinds)):
    print(frinds[index])

# jim
# kevin
# mike
# karen




### 27 rangeで決められた範囲だけで処理する場合
for index in range(5):  # 0 ~ 4が範囲。1 ~ 3にしたい場合はrange(1, 4)
    if index == 0:
        print("index is first")
    else:
        print("index is not first")

# index is first
# index is not first
# index is not first
# index is not first
# index is not first

寄り道 ~ パスワード解析をfor文で ~

forを複数回すことで簡単に総当たりのパスワード解析プログラムを作ることができる。

### 28 forを使って任意の4ケタ(1~9の数字)の数字を当てる。

import time
from getpass import getpass # 入力文字が非表示
password = getpass("Enter your password: ")

start_guess = input("Do you start ? (yes / no): ")
start = time.time()
if (start_guess == "yes"):
    for a in range(0, 10):
        for b in range(0, 10):
            for c in range(0, 10):
                for d in range(0, 10):
                    guess_password = str(a) + str(b) + str(c) + str(d)
                    print(guess_password)
                    if(password == guess_password):
                        print("you are password is ----> " + guess_password)
                        break
                    else:
                        continue
                    break
                else:
                    continue
                break
            else:
                continue
            break
        else:
            continue
        break
    finish = time.time() - start
    print(finish, ' sec')
else:
    print("stopped...")


# Enter your password: 
# Do you start ? (yes / no):  

# 0000
# 0001
# 0002
#  ↓
# 1465
# 1466
# 1467
# you are password is ----> 1467
# 0.019086122512817383  sec


# 範囲指定を工夫すればabcやABC、記号なども設定できる。

ネスト処理と変換

### 29 for文を使ってネストリストへのアクセス
number_grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
    [0]
]

print(number_grid[0][1]) # index番号は0から始まる
# 2

for row in number_grid:
    for col in row:
        print(col)

# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 0



### 30 文字の変換(多数のデータを判断→自動入力、などに役立つ)
def translate(phrase):
    translation = ""
    for letter in phrase:
        if letter in "AIUEOaiueo":
            translation = translation + "g"
        else:
            translation = translation + letter
    return translation

print(translate(input("Enter your phrase: ")))

# Enter your phrase: dog cat letter tomato
# dgg cgt lgttgr tgmgtg

基本その4:[ バリデーション / ファイル操作 ]

バリデーション

入力などのユーザー処理をコントロールして予期しないエラーハンドリングする。

### 32 例外処理 try except

try:
    number = int(input("Enter your number: "))
    print(number)
except ZeroDivisionError: # 0による徐算エラーハンドリング
    print("divided by zero")
except ValueError: # 不適切な値のエラーハンドリング
    print("Invalid Input")

# そのほかのエラーハンドリング方法は下記URL記事が有益
# https://note.nkmk.me/python-try-except-else-finally/

ファイル操作

open()を使って、ファイルの読み込みができる。

### 33 ファイル操作
open("./data/sample.txt", "r")
# 第1引数にファイルのパス、第2引数に実行関数のモードを記入
# r ... 読み込み
# w ... 書き込み。 同じファイル名のファイルがあった場合は、そのファイルに上書きされる
# a ... 追記。 同じファイル名のファイルがあった場合は、既存のファイルに追記していく
# r+ ... 既存ファイルの読み込み + 書き込み
# そのほかは以下のURLを参照
# https://chappy88.hatenablog.com/entry/2019/08/27/230934


# 34 ファイルの読み込み
select_file = open("./data/sample.txt", "r")
print(select_file.read())
# 1 - this is 1 sample
# 2 - this is 2 sample
# 3 - this is 3 sample
# 4 - this is 4 sample
# 5 - this is 5 sample


### 35 ファイル読み込みの判定
print(select_file.readable()) # True


### 36 ファイルから1行出力
print(select_file.readline()) # 1 - this is 1 sample


### 37 ファイルから行をリスト化して出力
print(select_file.readlines()) # ['1 - this is 1 sample\n', '2 - this is 2 sample\n', '3 - this is 3 sample\n', '4 - this is 4 sample\n', '5 - this is 5 sample']



### 38 追記のa
select_file = open("./data/sample.txt", "a")
select_file.write("\n6 - this is 6 sample")  # 改行するときは\nをいれる
select_file = open("./data/sample.txt", "r")
print(select_file.read())
# 1 - this is 1 sample
# 2 - this is 2 sample
# 3 - this is 3 sample
# 4 - this is 4 sample
# 5 - this is 5 sample
# 6 - this is 6 sample


### 39 上書きのw
select_file = open("./data/sample.txt", "w")
select_file.write("6 - this is 6 sample")
select_file = open("./data/sample.txt", "r")
print(select_file.read())
# 6 - this is 6 sample


### 40 新規作成
select_file = open("./data/index.html", "w")
select_file.write("<p>Hello World</p>")
select_file = open("./data/index.html", "r")
print(select_file.read())
# ./data/index.htmlがない場合新規作成される

基本その5:[ クラスとオブジェクト ]

クラスとオブジェクト

クラスとは簡単に言うととある処理をまとめたもの(抽象化されたもの)で、オブジェクトはそれぞれの要素。例えば「ヒト」と言うクラスを作った時、「ヒト」の情報には、名前・血液・身長など、おおよその人間に当てはまる情報が抽象化できる。これをクラスとして定義する。pythonはオブジェクトサポート言語なので、今まで登場してきた文字列/数値/リスト/タプルなど、これらは全てクラスから作られたオブジェクトになる。

# 他のファイルで定義されたクラスを呼び出すときは、from ファイル名 import class名 で呼び出す。
### 42 クラスとオブジェクト
from Student import Studentinfo

student1 = Studentinfo("Jim", "Business", 3.1, False)

print(student1.name)
# Jim


# ************************ #
# Student.py  
class Studentinfo:

    def __init__(self, name, major, gpa, is_on_probation):
        self.name = name
        self.major = major
        self.gpa = gpa
        self.is_on_probation = is_on_probation

# __init__は、クラスを「インスタンス化」する際に必要なメソッドで、「インスタンス化」とは、抽象的なクラスという概念に個性を与えて具体化することこと。上の例では、Studentクラスを具体的にするために、引数にnameやmajorを定義することで、情報を与えた側が同じ書式で呼び出せば、一定の情報を返すことができる。

寄り道:クラスを使ってクイズを作ってみる

### 43 クイズゲーム

from Questions import Question
question_prompts = [
    "(第1問)猿も? \n(a) 木から落ちる\n(b) 棒にあたる\n(c) 川流し \n\n",
    "(第2問)2021年2月時点の内閣総理大臣の名前は? \n(a) 安倍 晋三\n(b) 麻生 太郎\n(c) 菅 義偉 \n\n",
    "(第3問)2020年のアメリカ大統領選挙で勝った人は? \n(a) バルデン\n(b) バイデン\n(c) バイトル \n\n",
]
questions = [
    Question(question_prompts[0], "a"),
    Question(question_prompts[1], "c"),
    Question(question_prompts[2], "b"),
]


def run_quiz(questions):
    score = 0
    for question in questions:
        answer = input(question.prompt)
        if answer == question.answer:
            score += 1
    print("あなたは" + str(score) + "/" + str(len(questions)) + " 正解しました。")


run_quiz(questions)

# (第1問)猿も? 
# (a) 木から落ちる
# (b) 棒にあたる
# (c) 川流し 

# (第2問)2021年2月時点の内閣総理大臣の名前は? 
# (a) 安倍 晋三
# (b) 麻生 太郎
# (c) 菅 義偉 

# (第3問)2020年のアメリカ大統領選挙で勝った人は? 
# (a) バルデン
# (b) バイデン
# (c) バイトル 

# あなたは / 3 正解しました。

# ****************************************** #
#Questions.py 

class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer

まとめ

以上、pythonの基本的なことを紹介しました。
外部ライブラリを活用することでさらにできることが増えていくので、次回はライブラリ別に紹介できればと思います。

2
2
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
2
2