在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]内的随机整数,包括起始和结束数字。
错误和异常:
ValueError: 当用户传递浮点数作为参数时返回ValueError。
TypeError: 当用户传递除整数值以外的任何值作为参数时返回TypeError。
示例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
在这个示例中,我们将看到用户在使用randint()函数时如何在Python程序中获得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
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()
示例3
在这个示例中,我们将看到用户在使用randint()函数时如何在Python中遇到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
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
应用
用户可以使用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()函数来创建一个抽奖游戏应用程序。