Random Number Generator in Python

Submitted by: 
Language: 
Visitors have accessed this post 260 times.

Introduction:
This tutorial is on how to create a random number generator in Python.

Imports:
Before we begin, we first need to import the random module...

  1. import random

This allows us to use the random modules functions such as 'randrange' and 'randint'.

Random From Zero:
To get a random number from the beginning (zero/0), we can simply call the 'randrange' function from the random module and parse it a final/maximum value as an integer, like so...

  1. print(random.randrange(100))

The above code generates and outputs a random number between 0 and 100.

Random Between:
Or if we need to set a minimum value as well, we can use the 'randint' function. This function generates a random number between parameter 1 (minimum) and parameter 2 (maximum)...

  1. print(random.randint(20, 100))

The above code generates and outputs a random number between 20 and 100.


Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.