Python 小游戲?qū)WPython

先上代碼:

# 小游戲 猜數(shù)字游戲
# 關(guān)鍵點1: 隨機生成 0 ~ 100的隨機數(shù)
# 使用random 函數(shù) 需要導(dǎo)入 random包 random.randInt(a, b) ab為數(shù)字 最后的隨機值 a <= 隨機值 >= b
# 關(guān)鍵點2: 使用方法判斷用戶輸入的是否為數(shù)字
# 關(guān)鍵點3: 需要使用到 while 循環(huán)
# not 取反操作


def is_number(target_str):
    try:
        float(target_str)
        return True
    except Exception:
        pass
    if target_str.isnumeric():
        return True
    return False


target = random.randint(0, 100)
user_input = 0
is_ok = True
while is_ok:
    user_input = input('請輸入一個數(shù)字:')
    if not is_number(user_input):
        print('輸入錯誤!')
    else:
        user_input = int(user_input)
        if user_input == target:
            user_input = input('恭喜您猜對了!正確數(shù)字為:' + str(target) + '繼續(xù)游戲請輸入1,其他字符退出游戲')
            if user_input == '1':
                target = random.randint(0, 100)
            else:
                print("游戲結(jié)束")
                is_ok = False
        elif user_input > target:
            print("大了")
        else:
            print("小了")

此游戲知識點:

  1. if else 使用
  2. while 使用
  3. random的學(xué)習(xí)使用
  4. input使用
  5. str轉(zhuǎn)int類型
  6. 方法的定義
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容