Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 457
An hero Avatar asked Dec 23 '10 21:12

An hero


People also ask

How do you generate a random integer in Python?

Random integer values can be generated with the randint() function. This function takes two arguments: the start and the end of the range for the generated integer values. Random integers are generated within and including the start and end of range values, specifically in the interval [start, end].

How do you generate a random number between 1 and 6 in Python?

The randint() method to generates a whole number (integer). You can use randint(0,50) to generate a random number between 0 and 50. To generate random integers between 0 and 9, you can use the function randrange(min,max) . Change the parameters of randint() to generate a number between 1 and 10.


2 Answers

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

In [67]: import random
In [69]: random.randrange(1,10)
Out[69]: 8
like image 168
unutbu Avatar answered Nov 13 '22 04:11

unutbu


You can use random module:

import random

# Random integer >= 5 and < 10
random.randrange(5, 10)
like image 24
Polipizio Avatar answered Nov 13 '22 05:11

Polipizio