先上代碼:
# 小游戲 猜數(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("小了")
此游戲知識點:
- if else 使用
- while 使用
- random的學(xué)習(xí)使用
- input使用
- str轉(zhuǎn)int類型
- 方法的定義