Differences between revisions 1 and 2
Revision 1 as of 2018-10-14 23:28:15
Size: 3585
Comment:
Revision 2 as of 2018-10-14 23:38:33
Size: 842
Comment:
Deletions are marked like this. Additions are marked like this.
Line 26: Line 26:

{{{#!highlight python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==============================================================================
# * Copyright (c) 2018 IIJIMA, Tadashi
# * (IIJIMA Laboratory, Dept. of Science and Technology, Keio University).
# ==============================================================================
# ソフトウェア工学[02] 拡張課題[02]-(000a) EP_02_000a_.py
# EP(Extended Problem) 02-000a:
# 2018-10-03 飯島 正 (iijima@ae.keio.ac.jp)
# ==============================================================================
# ----- 乱数を取り扱うrandomモジュールをインポートする -----
import random
# ==============================================================================
# ===== 【関数定義】 正解か,正解よりも大きいか,小さいかを判断する関数 =============================
def judge_high_and_low( x, correct_number ):
    if x == correct_number:
        return( "正解です" )
    elif x > correct_number:
        return( "大きすぎます" )
    else:
        return( "小さすぎます" )
# ==============================================================================
# ===== 【メイン・プログラム】  ==========================================================
# ----- オープニングメッセージ ----------------------------------------------------------
print( "数当てゲーム: " )
print( "  秘密にされた100未満の正の整数(乱数で選ばれている)を当てます." )
print( "  回答として正しい数と思うを入力してください." )
print( "  正解なら,その旨を表示して終了します." )
print( "  不正解なら,入力された数が正解よりも大きいか,小さいかを表示して,再度,入力を促します." )
print( "  降参する場合は,\"X\"を入力してください." )
print()

# ----- 正解を選択します ------------------------------------------------------------
answer = random.randint( 1, 99 )

# デバッグ時以外はコメントアウト
print( "正解は:", answer )

# ----- 数当てゲームを始めます --------------------------------------------------------
while True:
    guess = input( "正解と思う100未満の正の整数を入力してください(降参ならX)>>> " )
    if guess == "X":
        print( "降参ですね.正解は", answer, "でした", sep="" )
        break
    judge = judge_high_and_low( int( guess ), answer )
    print( judge )
    if judge == "正解です":
        break
# ==============================================================================

}}}
  • 解答は基本的に,下記 7 行です.

   1 def judge_high_and_low( x, correct_number ):
   2     if x == correct_number:
   3         return( "正解です" )
   4     elif x > correct_number:
   5         return( "大きすぎます" )
   6     else:
   7         return( "小さすぎます" )
  • でも,単純に,正解なら整数の0, 大きすぎるとき正の数,小さすぎるとき負の数を返すと考えれば,単純に引き算で表現できます.

   1 def judge_high_and_low( x, correct_number ):
   2     return( int( x - correct_number ))

SoftEng: Python/Prog/Practice/Extended/02/EP_005a/Digest (last edited 2019-10-16 14:42:15 by TadashiIijima)