在本教程中,我們將學習 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-hant/n/317530.html