如何使用 python 3.2 生成(和标记)一个随机整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4522733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:06:50  来源:igfitidea点击:

How do I generate (and label) a random integer with python 3.2?

pythonpython-3.xrandomintegerlabel

提问by An hero

Okay, so I'm admittedly a newbie to programming, but I can't determine how to get python v3.2 to generate a random positive integer between parameters I've given it. Just so you can understand the context, I'm trying to create a guessing-game where the user inputs parameters (say 1 to 50), and the computer generates a random number between the given numbers. The user would then have to guess the value that the computer has chosen. I've searched long and hard, but all of the solutions I can find only tell one how to get earlier versions of python to generate a random integer. As near as I can tell, v.3.2 changed how to generate and label a random integer. Anyone know how to do this?

好的,所以我承认我是编程的新手,但我无法确定如何让 python v3.2 在我给它的参数之间生成一个随机的正整数。为了让您能够理解上下文,我正在尝试创建一个猜谜游戏,其中用户输入参数(比如 1 到 50),然后计算机在给定数字之间生成一个随机数。然后用户必须猜测计算机选择的值。我已经搜索了很长时间,但我能找到的所有解决方案都只告诉了一个如何让早期版本的 python 生成一个随机整数。据我所知,v.3.2 更改了生成和标记随机整数的方式。有人知道怎么做吗?

回答by unutbu

Use random.randrangeor random.randint(Note the links are to the Python 3k docs).

使用random.randrangerandom.randint(注意链接指向 Python 3k 文档)。

In [67]: import random
In [69]: random.randrange(1,10)
Out[69]: 8

回答by Polipizio

You can use randommodule:

您可以使用random模块:

import random

# Random integer >= 5 and < 10
random.randrange(5, 10)