PYTHON練習題 二. 使用random中的randint函數隨機生成一個1~100之間的預設整數讓用戶鍵盤輸入所猜的數。


Python 練習

標簽: Python Python練習題 Python知識點


二. 使用random中的randint函數隨機生成一個1~100之間的預設整數讓用戶鍵盤輸入所猜的數,如果大於預設的數,屏幕顯示“太大了,請重新輸入”如果小於預設的數,屏幕顯示“太小了,請重新輸入”如此循環,直到猜中,顯示“恭喜你,猜中了!共猜了N次”N為用戶猜測次數.

答案:

import random


def guess_number():
    true_num = random.randint(1, 100)
    user_num = int(input("請輸入一個整數:"))
    count = 1
    while true_num != user_num:
        if true_num > user_num:
            print("太小了,請重新輸入!")
        elif true_num < user_num:
            print("太大了,請重新輸入!")
        count += 1
        user_num = int(input("請輸入一個整數:"))
    print("恭喜您,您猜對了!您一共猜了%d次" % count)

guess_number()

知識點

1.Python中的random模塊

1.1 random 模塊簡介

Python標准庫中的random函數,可以生成隨機浮點數、整數、字符串,甚至幫助你隨機選擇列表序列中的一個元素,打亂一組數據等。

1.2 random 模塊方法說明
  • random.random(): 函數會生成一個隨機的浮點數,范圍是在0.0~1.0之間
In [2]: import random

In [3]: random.random()
Out[3]: 0.6935051182120364
  • random.uniform(a, b): 函數隨機生成一個處於范圍[a,b]的浮點數
In [26]: random.uniform(0, 100)
Out[26]: 26.977426505683276
  • random.randint(a, b): 隨機生成一個范圍[a, b]內的整數(int類型)
In [28]: random.randint(1,2)
Out[28]: 2

In [29]: random.randint(1,2)
Out[29]: 1

  • random.choice(): 可以從任何序列,比如list列表中,選取一個隨機的元素返回,可以用於字符串、列表、元組等。

參數為列表時:

In [31]: random.choice([1,2,3])
Out[31]: 3

In [32]: random.choice([1,2,3])
Out[32]: 1

參數為字符串時:

In [38]: random.choice("i am a bad boy")
Out[38]: 'y'

In [39]: random.choice("i am a bad boy")
Out[39]: 'b'

參數為元祖時:

In [41]: random.choice((1,3,7,4))
Out[41]: 1

In [42]: random.choice((1,3,7,4))
Out[42]: 7

  • random.shuffle: 如果你想將一個序列(不包括元祖和字符串)中的元素,隨機打亂的話可以用這個函數方法
In [49]: list = [1,2,3,4]

In [50]: random.shuffle(list)

In [51]: list
Out[51]: [4, 2, 1, 3]

  • random.sample(a, b): 從序列a中隨機且獨立的截取指定長度b的片段。

In [58]: b = (9,9,9,1,2)

In [59]: random.sample(b, 2)
Out[59]: [9, 1]

In [60]: random.sample(b, 2)
Out[60]: [1, 9]

In [61]: random.sample(b, 2)
Out[61]: [1, 9]

In [62]: random.sample(b, 2)
Out[62]: [1, 9]

In [63]: random.sample(b, 2)
Out[63]: [2, 9]

In [64]: list = [1,2,3,5,7,94,2]

In [65]: random.sample(list, 3)
Out[65]: [1, 5, 7]

In [66]: random.sample(list, 3)
Out[66]: [2, 2, 5]

In [67]: random.sample("i am a bad boy", 3)
Out[67]: [' ', 'a', 'b']

In [68]: random.sample("i am a bad boy", 3)
Out[68]: ['a', 'y', 'b']

2. python中random模塊的randint與numpy.random模塊的randint的區別

  • random.randint(a, b) # 隨機返回閉區間 [a, b] 范圍內的整數值

  • numpy.random.randint(a, b) # 隨機返回開區間 [a, b) 范圍內的整數值

In [69]: random.randint(0,1)  
Out[69]: 0  

In [70]: random.randint(0,1)  
Out[70]: 1
  
In [71]: numpy.random.randint(0,1)  
Out[71]: 0
  
In [72]: np.random.randint(0,1)  
Out[72]: 0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM