じゃんけんのifの仕組みをしっかり理解したい。
じゃんけんを作るコードを練習として書いていました。それが以下です。
import random hand_dict = { '1': 'グー', '2': 'チョキ', '3': 'パー' } print('手を入力してください') print('1:グー 2:チョキ 3:パー') player_input = input() list = [1, 2, 3] if int(player_input) not in list: print('入力が正しくありません。') exit() else: player = hand_dict[player_input] print('入力した手: ' + player) com_input = random.choice(['1', '2', '3']) com = hand_dict[com_input] print('コンピューターの手: ' + com) print(player, 'VS', com,sep='') if player == 'グー': if com == 'チョキ': print('あなたの勝ち') if com == 'パー': print('コンピューターの勝ち') if com == player: print('あいこ') if player == 'チョキ': if com == 'パー': print('あなたの勝ち') if com == 'グー': print('コンピューターの勝ち') if com == player: print('あいこ') if player == 'パー': if com == 'グー': print('あなたの勝ち') if com == 'チョキ': print('コンピューターの勝ち') if com == player: print('あいこ')
結果はなぜか正常に扱われました。
プレイヤーがだしてきたグーショキパーに対してcomの対応を決める際に、単純にifですべてつないでしまったのですが、本を見たらifを2つ以上つなげる時はelifを用いるとなっていました。ただし、入れ子ならばifのインデントの中に連続してifを入れることができるらしいです。
今回のコードでは並列してifを3つも使っているので、なぜ正しくコードが出力されたのかわかりません。
お分かりになられた方がいたら、ご教授お願いします。
一応、elifとelseをつかって書き直したのが以下で正しく動きました。
import random hand_dict = { '1': 'グー', '2': 'チョキ', '3': 'パー' } print('手を入力してください') print('1:グー 2:チョキ 3:パー') player_input = input() list = [1, 2, 3] if int(player_input) not in list: print('入力が正しくありません。') exit() else: player = hand_dict[player_input] print('入力した手: ' + player) com_input = random.choice(['1', '2', '3']) com = hand_dict[com_input] print('コンピューターの手: ' + com) print(player, 'VS', com,sep='') if player == 'グー': if com == 'チョキ': print('あなたの勝ち') elif com == 'パー': print('コンピューターの勝ち') else: print('あいこ') elif player == 'チョキ': if com == 'パー': print('あなたの勝ち') elif com == 'グー': print('コンピューターの勝ち') else: print('あいこ') else: if com == 'グー': print('あなたの勝ち') elif com == 'チョキ': print('コンピューターの勝ち') else: print('あいこ')
ifとelifの使い分け
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/01/23 13:39
2019/01/23 14:00