randint()是Python3中隨機模塊的內置函數。隨機模塊提供對各種有用功能的訪問,其中一個功能可以生成隨機數,即randint()。句法:
randint(start, end)
參數:
(start, end): Both of them must be integer type values.
返回值:
A random integer within the given range as parameters.
錯誤和異常:
ValueError:Returns a ValueError when floating
point values are passed as parameters.
TypeError:Returns a TypeError when anything other than
numeric values are passed as parameters.
代碼1:
# Python3 program explaining work
# of randint() function
# imports random module
import random
# Generates a random number between
# a given positive range
r1 = (0, 10)
print("Random number between 0 and 10 is % s" % (r1))
# Generates a random number between
# two given negative range
r2 = (-10, -1)
print("Random number between -10 and -1 is % d" % (r2))
# Generates a random number between
# a positive and a negative range
r3 = (-5, 5)
print("Random number between -5 and 5 is % d" % (r3))
輸出:
Random number between 0 and 10 is 5
Random number between -10 and -1 is -7
Random number between -5 and 5 is 2
代碼2:程序演示ValueError。
# imports random module
import random
'''If we pass floating point values as
parameters in the randint() function'''
r1 = (1.23, 9.34)
print(r1)
輸出:
Traceback (most recent call last):
File "/home/", line 6, in
r1=(1.23, 9.34)
File "/usr/lib/python3.5/", line 218, in randint
return (a, b+1)
File "/usr/lib/python3.5/", line 182, in randrange
raise ValueError("non-integer arg 1 for randrange()")
ValueError:non-integer arg 1 for randrange()
代碼3:程序演示TypeError。
# imports random
import random
'''If we pass string or character literals as
parameters in the randint() function'''
r2 = ('a', 'z')
print(r2)
輸出:
Traceback (most recent call last):
File "/home/", line 5, in
r2=('a', 'z')
File "/usr/lib/python3.5/", line 218, in randint
return (a, b+1)
TypeError:Can't convert 'int' object to str implicitly
應用範圍:
randint()函數可用於模擬幸運抽獎情況。
假設用戶參加了幸運抽獎比賽。用戶有3次機會猜測1到10之間的數字。如果猜測正確,則用戶獲勝,否則將輸掉比賽。
# importing randint function
# from random module
from random import randint
# Function which generates a new
# random number everytime it executes
def generator():
return randint(1, 10)
# Function takes user input and returns
# true or false depending whether the
# user wins the lucky draw!
def rand_guess():
# calls generator() which returns a
# random integer between 1 and 10
random_number = generator()
# defining the number of
# guesses the user gets
guess_left = 3
# Setting a flag variable to check
# the win-condition for user
flag = 0
# looping the number of times
# the user gets chances
while guess_left > 0:
# Taking a input from the user
guess = int(input("Pick your number to "
"enter the lucky draw\n"))
# checking whether user's guess
# matches the generated win-condition
if guess == random_number:
# setting flag as 1 if user guessses
# correctly and then loop is broken
flag = 1
break
else:
# If user's choice doesn't match
# win-condition then it is printed
print("Wrong Guess!!")
# Decrementing number of
# guesses left by 1
guess_left -= 1
# If win-condition is satisfied then,
# the function rand_guess returns True
if flag is 1:
return True
# Else the function returns False
else:
return False
# Driver code
if __name__ == '__main__':
if rand_guess() is True:
print("Congrats!! You Win.")
else :
print("Sorry, You Lost!")
輸出:
Pick your number to enter the lucky draw
8
Wrong Guess!!
Pick your number to enter the lucky draw
9
Wrong Guess!!
Pick your number to enter the lucky draw
0
Congrats!! You Win.