Python中Random模塊的用法

random     模塊用來生成隨機數   dom

random.random()     用來生成0到1之間的隨機數   spa

random.randint(1,5)     用來生成1到5以內的隨機數   code

random.randrange(1,10)     用來生成1到9之間數字,注意區間包含頭 不包含尾orm

# 導入第三方模塊
import random
# 設定數據範圍
A = int(input('請輸入最小值:'))
B = int(input("請輸入最大值:"))
# 生成A,B之間的隨機整數
number = random.randint(A,B)

while True:
    guess = int(input('請在{}和{}之間猜一個整數:'.format(A,B)))
    if guess > number:
        # 若是猜的偏大,則將猜的數字從新賦值給B,用於限定下輪數據的猜想範圍
        B = guess
        print('猜大了!')
    elif guess < number:
        # 若是猜的偏小,則將猜的數字從新賦值給A,用於限定下輪數據的猜想範圍
        A = guess
        print('猜小了!')
    else:
        print('猜對了!')
        break
相關文章
相關標籤/搜索