0
0

More than 1 year has passed since last update.

Python基本文法3(関数 編)

Last updated at Posted at 2023-02-15

概要

MySQL勉強まとめ2の続きです。
個人的な勉強のまとめなので、もし修正があればご指摘いただけるとありがたいです。

目次

  • 関数
  • 引数
  • 引数の初期値
  • 複数の要素を受け取れるようなコード
  • 戻り値

関数

ターミナル
# 関数 print_hand を定義
def print_hand():

# 実行する処理
  print('グーを出しました')

# 関数の呼び出し  
print_hand()

処理の順番

  1. 関数print_handが定義される
  2. 関数print_handが呼び出される
  3. 処理を実行する
ターミナルの結果
グーを出しました

引数

ターミナル
# 引数を受け取る
def print_hand(hand):
    # 「 ◯◯を出しました 」と出力されるように、引数と文字列を書く
    print(hand + 'を出しました')

# 引数に文字列「 グー 」を入れる
print_hand('グー')

# 引数を文字列「 パー 」を入れる
print_hand('パー')

処理の順番

  1. 関数print_handが定義されて、引数handを持つ
  2. 関数print_handに引数が入れられる
  3. 関数print_handに引数が返される
  4. 引数handに代入された文字列(上記で言うとprint_hand('グー')のグー)や数字を処理の際に表示する
ターミナルの結果
グーを出しました
パーを出しました

引数は複数も可能!

ターミナル
# 引数を受け取る
def print_hand(hand,result):
    # 「 ◯◯を出しました 」と出力されるように、引数と文字列を書く
    print(hand + 'を出しました。あなたの' + result)

# 引数に文字列「グー」、「負け」を入れる
print_hand('グー','負け')

# 引数を文字列「パー,'勝ち'」を入れる
print_hand('パー','勝ち')
ターミナルの結果
グーを出しましたあなたの負け
パーを出しましたあなたの勝ち

引数の初期値

ターミナル
# messageの引数を'こんにちは'に設定する
def hello(name,message = 'こんにちは'):
    print(name + 'さん' + message)

hello('田中','こんばんは')

# 引数messageに何も入れない
hello('鈴木')

処理の順番

  1. 関数helloが定義される
  2. 関数helloが引数handと引数messageを持つ
  3. その際、引数messageには、「こんにちは」という初期値が設定される
  4. 引数name、引数messageに代入された文字列や数字を処理の際に表示する
  5. hello('田中','こんばんは')であれば「name=田中、message=こんばんは」が代入されている
  6. 手順5の場合は「田中さんこんばんは」と処理する
  7. hello('鈴木')であれば「name=田中」が代入されているが引数messageには何も代入されていない
  8. 手順7の場合はmessageが空白なので、messageの初期値「こんにちは」が使用され、「鈴木さんこんにちは」と処理する
ターミナルの結果
田中さんこんばんは
# ↓messageの引数に何も入れない場合は、初期値が反映される
鈴木さんこんにちは

複数の要素を受け取れるようなコード

ターミナル
def print_hand(hand, name='ゲスト'):
    # 変数 hands に、複数の文字列を要素に持つリストを代入してください
    hands = ['グー','チョキ','パー']
    
    # リスト hands を用いて、選択した手が出力されるように書き換えましょう
    print(name + '' + hands[hand] + 'を出しました')

print('じゃんけんをはじめます')
player_name = input('名前を入力してください:')
# 「 何を出しますか?(0: グー, 1: チョキ, 2: パー) 」と出力してください
print('何を出しますか?(0: グー, 1: チョキ, 2: パー)')

# input を用いて入力を受け取り、数値に型変換してから変数 player_hand に代入してください
player_hand = int(input('数字で入力してください:'))

if player_name == '':
    # 第1引数を変数 player_hand に書き換えてください
    print_hand(player_hand)
else:
    # 第1引数を変数 player_hand に書き換えてください
    print_hand(player_hand, player_name)

起こっていることの解説

  1. 関数print_handが定義されて、引数hand、引数name(初期値ゲスト)を持つ

  2. 変数handsにリスト['グー','チョキ'.'パー']の複数の要素を持つリストを代入する

  3. print('じゃんけんをはじめます')を表示

  4. player_name = input('名前を入力してください:')で名前をコンソールで入力し、その名前を引数player_nameに代入する

  5. print('何を出しますか?(0: グー, 1: チョキ, 2: パー)')で文字列を表示

  6. player_hand = int(input('数字で入力してください:'))で出す手を手順5の(0: グー, 1: チョキ, 2: パー)から数字で選ばせる。その後入力された数字(文字列)をint(数値)に変換

  7. player_name == '':であれば、print_hand(player_hand)を適用し、引数player_handに手順6で入力した手を代入する。else:(player_name)が入力済みであれば、print_hand(player_hand, player_name)を適用し、引数player_hand,引数player_nameに入力した文字列を代入

  8. 手順7で代入したものがdef print_hand(hand, name='ゲスト'):に返される(名前を代入した「player_name」をnameに代入、出した手を代入したplayer_handをhandに代入)←代入に代入するからややこしい!

  9. print(name + 'は' + hands[hand] + 'を出しました')の処理で、hands[hand]の部分は、handに代入したのが0であれば、hands = ['グー','チョキ','パー']のグー(リストの最初の要素の数字は0)、handに代入したのが1であればチョキ、handに代入したのが2であればパーが代入される

  10. 手順が増えてややこしくなるので、最初のうちは頭の中で整理しながら、自分の言葉で説明できるようにまとめると理解しやすくなる!

戻り値

ターミナル
def validate(hand):
    if hand < 0 or hand > 2:
        return False
    return True

def print_hand(hand, name='ゲスト'):
    hands = ['グー', 'チョキ', 'パー']
    print(name + '' + hands[hand] + 'を出しました')

def judge(player, computer):
    # player と computer の比較結果によって条件を分岐してください
    if player == computer:
      return "引き分け"
    elif player == 0 and computer == 1:
      return "勝ち"
    elif player == 1 and computer == 2:
      return "勝ち"
    elif player == 2 and computer == 0:
      return "勝ち"
    else:
      return "負け"
    

print('じゃんけんをはじめます')
player_name = input('名前を入力してください:')
print('何を出しますか?(0: グー, 1: チョキ, 2: パー)')
player_hand = int(input('数字で入力してください:'))

if validate(player_hand):
    computer_hand = 1
   
    if player_name == '':
        print_hand(player_hand)
    else:
        print_hand(player_hand, player_name)
    
    print_hand(computer_hand, 'コンピューター')
    
    # 変数 result に関数 judge の戻り値を代入してください
    result = judge(player_hand, computer_hand)
    # 変数 result を出力してください
    print("結果は" + result + "でした")
else:
    print('正しい数値を入力してください')

起こっていることの解説

かなり長くなるので、読み飛ばしてもらって大丈夫です。

  1. 関数のvalidate、print_hand、judgeを定義
  2. print('じゃんけんをはじめます')
    player_name = input('名前を入力してください:')
    print('何を出しますか?(0: グー, 1: チョキ, 2: パー)')
    player_hand = int(input('数字で入力してください:'))
    この出力をする
  3. validate(player_hand):で関数validateを呼び出す
    この時、引数のplayer_handに入って、その後、仮引数handに入れられた数値を判断してtrue、falseを判断する
  4. validateがfalseなら、print('正しい数値を入力してください')を出力して終了
  5. validateがtrueなら、computer_hand = 1を行う
  6. player_nameが空("")なら、print_hand(player_hand)を呼び出す。(player_nameはないので、初期値の"ゲスト"が適用される)
  7. player_nameが入力されていたら、print_hand(player_hand, player_name)を呼び出す。
  8. print_hand(computer_hand, 'コンピューター')でコンピュータの手と「コンピュータ」という名前を呼び出す。
  9. result = judge(player_hand, computer_hand)でjudge を呼び出した後に、変数resultに代入
  10. print("結果は" + result + "でした")を出力
    で終了!
    かなり長いけど自分で処理の流れがわかればめちゃくちゃ楽しくなりますよ!

追記

処理の手順を書きましたが、素人意見なので、間違いや非効率な考えがあるかもしれません。
また、自分なりに言葉を並べておりますので、参考にしたいと言う物好きな人には見づらくなっているかもしれません。ご了承ください。
もしご指摘いただければ、即修正させていただきますので、なんでもおっしゃってください。
よろしくお願いいたします。

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