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 = random.randint(0, 10)

print("Random number between 0 and 10 is % s" % (r1))

# Generates a random number between

# two given negative range

r2 = random.randint(-10, -1)

print("Random number between -10 and -1 is % d" % (r2))

# Generates a random number between

# a positive and a negative range

r3 = random.randint(-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 = random.randint(1.23, 9.34)

print(r1)

输出:

Traceback (most recent call last):

File "/home/f813370b9ea61dd5d55d7dadc8ed5171.py", line 6, in

r1=random.randint(1.23, 9.34)

File "/usr/lib/python3.5/random.py", line 218, in randint

return self.randrange(a, b+1)

File "/usr/lib/python3.5/random.py", 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 = random.randint('a', 'z')

print(r2)

输出:

Traceback (most recent call last):

File "/home/fb805b21fea0e29c6a65f62b99998953.py", line 5, in

r2=random.randint('a', 'z')

File "/usr/lib/python3.5/random.py", line 218, in randint

return self.randrange(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.

pythonrandint用法_Python randint()用法及代码示例相关推荐

  1. python end用法_Python turtle.end_fill方法代码示例

    本文整理汇总了Python中turtle.end_fill方法的典型用法代码示例.如果您正苦于以下问题:Python turtle.end_fill方法的具体用法?Python turtle.end_ ...

  2. python中stringvar的用法_Python tkinter.StringVar方法代码示例

    本文整理汇总了Python中tkinter.StringVar方法的典型用法代码示例.如果您正苦于以下问题:Python tkinter.StringVar方法的具体用法?Python tkinter ...

  3. python中formatter的用法_Python pyplot.FuncFormatter方法代码示例

    本文整理汇总了Python中matplotlib.pyplot.FuncFormatter方法的典型用法代码示例.如果您正苦于以下问题:Python pyplot.FuncFormatter方法的具体 ...

  4. python geometry用法_Python geometry.MultiPolygon方法代码示例

    本文整理汇总了Python中shapely.geometry.MultiPolygon方法的典型用法代码示例.如果您正苦于以下问题:Python geometry.MultiPolygon方法的具体用 ...

  5. python中geometry用法_Python geometry.Point方法代码示例

    本文整理汇总了Python中shapely.geometry.Point方法的典型用法代码示例.如果您正苦于以下问题:Python geometry.Point方法的具体用法?Python geome ...

  6. python中bind的用法_Python socket.bind方法代码示例

    本文整理汇总了Python中socket.bind方法的典型用法代码示例.如果您正苦于以下问题:Python socket.bind方法的具体用法?Python socket.bind怎么用?Pyth ...

  7. python中font的用法_Python font.nametofont方法代码示例

    本文整理汇总了Python中tkinter.font.nametofont方法的典型用法代码示例.如果您正苦于以下问题:Python font.nametofont方法的具体用法?Python fon ...

  8. python中fact用法_Python covariance.EllipticEnvelope方法代码示例

    本文整理汇总了Python中sklearn.covariance.EllipticEnvelope方法的典型用法代码示例.如果您正苦于以下问题:Python covariance.EllipticEn ...

  9. java secretkey用法_Java SecretKeyFactory.generateSecret方法代码示例

    本文整理汇总了Java中javax.crypto.SecretKeyFactory.generateSecret方法的典型用法代码示例.如果您正苦于以下问题:Java SecretKeyFactory ...

最新文章

  1. C++_标准模板库STL概念介绍5-其他库与总结
  2. 从零入门 Serverless | Knative 带来的极致 Serverless 体验
  3. 北斗导航 | 卫星导航基础知识(坐标系)
  4. C语言实现并查集(Disjoint set或者Union-find set)(附完整源码)
  5. Ghost 2.16.3 发布,基于 Markdown 的在线写作平台
  6. 如何安装zabbix_get
  7. 直播开发项目发展下半场,转战AI直播开启全新模式
  8. shell如何控制文件读写不同时_如何定时备份Mysql数据库数据?
  9. 编译GDAL使用最新的HDF库配置文件
  10. python取文件后缀
  11. 机器学习(四)神经网络
  12. Alex Fung魔方解法学习记
  13. Centos7设置开机自动运行脚本
  14. 小米商城app端项目
  15. Zeppelin安装教程
  16. 针对ONION勒索病毒!如何关闭139端口及445端口等危险端口
  17. VMware环境部署vFW虚拟防火墙
  18. 关于DDK中的编译知识
  19. 如何成为优秀的工作者
  20. java元编程_一文读懂元编程

热门文章

  1. 【C++标准库】std::chrono
  2. [统计学知识点]卡方检验
  3. 梦幻西游维护公告里面的可转服务器,7月19日定期维护公告 转服预定调整为30天...
  4. 史上最详细的Kali Linux破解Wifi无线网络教程
  5. 567网盘 飞猫网盘 星耀网盘 kufile expfile rardisk RoseFile 雪球网盘 77file 迅牛网盘 ownfile 1988网盘 520网盘解析演示
  6. 云服务器能干什么用?云服务器使用场景列举
  7. Qt --- QTreeWidget 树形控件实例遇到的问题
  8. docker build过程中出错 no such host
  9. 索尼和微软将在云游戏领域合作
  10. oracle 去摸_oracle摸底考试