在本教程中,我们将学习 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()
函数如何用于创建抽奖游戏的应用。