Python 中的randint()函數

在本教程中,我們將學習 Python 中的「randint()」函數。

「randint()」是 Python 中random模塊的內置函數。random模塊用於訪問各種函數,如使用 randint()函數生成隨機數。

首先,我們必須導入 Python 中的random模塊來使用 randint()函數。這個函數基本上用於創建偽隨機性。

語法:


randint(start_range, end_range)

參數:

(start_range,end_range): 兩個參數都必須是整型值。

參數:

它將返回範圍[start_range,end_range]內的隨機整數,包括開始和結束數字。

錯誤和異常:

值錯誤:當用戶將浮點作為參數傳遞時,返回一個值錯誤。

類型錯誤:當用戶將整數值以外的任何東西作為參數傳遞時,返回類型錯誤。

例 1:

獲取兩個正數、兩個負數、一個正數和一個負數之間的隨機數。


import random as rnd
# First, we will generate the random number between any positive number range
random_1 = rnd.randint(55, 75)
print ("The any random number between 55 and 75 is % s" % (random_1))

# Then, we will generate the random number between two given negative number range
random_2 = rnd.randint(-40, -20)
print ("The any random number between -40 and -20 is % s" % (random_2))

# We will now, generate the random number between a positive number and a negative number range
random_3 = rnd.randint(-20, 20)
print ("The any random number between -20 and 20 is % s" % (random_3))

輸出:

1#

The any random number between 55 and 75 is 74
The any random number between -40 and -20 is -40
The any random number between -20 and 20 is -12

2#

The any random number between 55 and 75 is 74
The any random number between -40 and -20 is -29
The any random number between -20 and 20 is -2

例 2:

在這個例子中,我們將看到用戶如何在 Python 程序中使用 randint()函數獲得 ValueError。


# First, we will import the random module
import random as rnd

# If the user passes any floating point values as the parameters in the randint() # function.

random_1 = rnd.randint(2.543, 12.786)
print (random_1)

輸出:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
 in <module>4 # If the user passes any floating point values as the parameters in the randint() function.
      5 
----> 6 random_1 = rnd.randint(2.543, 12.786)
      7 print(random_1)

c:\users\User Name\appdata\local\programs\python\python39\lib\random.py in randint(self, a, b)
    336         """
    337 
--> 338         return self.randrange(a, b+1)
    339 
    340 

c:\users\user name\appdata\local\programs\python\python39\lib\random.py in randrange(self, start, stop, step)
    300         istart = int(start)
    301         if istart != start:
--> 302             raise ValueError("non-integer arg 1 for randrange()")
    303         if stop is None:
    304             if istart > 0:

ValueError: non-integer arg 1 for randrange()</module> 

例 3:

在這個例子中,我們將看到用戶如何在 Python 中使用 randint()函數獲得 TypeError。


# First, we will import the random module
import random as rnd

# If the user passes any string or character value as the parameters in the 
# randint() function

random_2 = rnd.randint('String', 'Character')
print (random_2)

輸出:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in <module>4 # If the user passes any string or character value as the parameters in the randint() function
      5 
----> 6 random_2 = rnd.randint('String', 'Character')
      7 print (random_2)

c:\users\user name\appdata\local\programs\python\python39\lib\random.py in randint(self, a, b)
    336         """
    337 
--> 338         return self.randrange(a, b+1)
    339 
    340 

TypeError: can only concatenate str (not "int") to str</module> 

應用:

用戶可以使用 randint()函數來模擬抽獎遊戲。

假設我們參加了一個抽獎遊戲,比如「賭場遊戲」。玩家將有三次機會猜測 1 到 36 之間的數字。如果我們猜對了數字,我們就會贏,否則我們就會輸。

示例:應用代碼


# First, we will import the randint function
# from the random module in Python
from random import randint as rdt

# We will create a function which can generate a new 
# random number everytime the code will execute
def generator_1():
    return rdt(1, 36)

# Now, we will create a function which takes the input from the user and returns
# true or false depending whether the
# user has guessed the correct number and wins the lucky draw or not. 
def random_guess():

    # The calls generator_1() which returns a
    # random integer between 1 and 36
    random_number_1 = generator_1()

    # here, we will define the number of
    # guesses the user will get
    guess_left_1 = 3

    # now, we will set the flag variable for checking
    # the win-condition for the user
    flag_1 = 0

    # Then, we will loop the number of times
    # the user will get the chances
    while guess_left_1 > 0:

        # Here, we will take a input from the user.
        guess_1 = int (input ("Please select your number to "
                      "enter the lucky draw game \n"))

        # then, we will check whether the guess of the user 
        # matched the generated win-condition or not.
        if guess_1 == random_number_1:

            # Then, we will set the flag as 1 if the user have guessed
            # the correct number and then loop will broke
            flag_1 = 1
            break

        else:

            # If the guess of the user does not matched
            # the win-condition then it will print
            print ("You have guessed Wrong Number!!")

        # then, we will decrease the number of 
        # guesses left by 1 
        guess_left_1 -= 1

    # If the condition of winning is satisfied then,
    # the function random_guess will return "True"
    if flag_1 == 1:
        return True

    # Otherwise, the function will return "False"
    else:
        return False

# Driver code
if __name__ == '__main__':
    if random_guess() == True:
        print ("Congratulation!! You have Won the game.")
    else :
        print ("Sorry, You have Lost the game!")

輸出:

1#

Please select your number to enter the lucky draw game 
 3
You have guessed Wrong Number!!
Please select your number to enter the lucky draw game 
 2
You have guessed Wrong Number!!
Please select your number to enter the lucky draw game 
 34
You have guessed Wrong Number!!
Sorry, you have Lost the game!

2#

Please select your number to enter the lucky draw game 
 14
You have guessed Wrong Number!!
Please select your number to enter the lucky draw game 
 12
You have guessed Wrong Number!!
Please select your number to enter the lucky draw game 
 3
Congratulation!! You have Won the game.

結論

在本教程中,我們討論了 Python random模塊的 randint()函數。我們已經展示了用戶在使用 randint()函數時可能遇到的錯誤類型。我們還討論了 randint()函數如何用於創建抽獎遊戲的應用。


原創文章,作者:EDHRZ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/317530.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
EDHRZ的頭像EDHRZ
上一篇 2025-01-11 16:27
下一篇 2025-01-11 16:27

相關推薦

  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智慧、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • 蝴蝶優化演算法Python版

    蝴蝶優化演算法是一種基於仿生學的優化演算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化演算法Python版…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29

發表回復

登錄後才能評論