Web development and Tech news Blog site. WEBISFREE.com

# [Python] Creating random numbers, using random

Last Modified : 05 Mar, 2023 / Created : 05 Mar, 2023
672
View Count

## # Python obtain a random number

To obtain a random number in Python, you can use the random module which allows you to generate a random number.

import random

The random module has a random() method that can generate random numbers. By using this method, you can easily obtain a random number.
import random
myNum = random.random()
print(myNum)

The output result is as follows.
0.16104757064319608

If you check the type, it will be output as float.
<class 'float'>

Now, let's create a simple example below and try to execute it.

### ! Getting a random number within a specific range from 1.

If you want to get a random value between 1 and 10, what do you do? You can multiply the desired value and add 1 to get a random number between 1 and that value. If you want to get a random value between 1 and e, you can use the formula below.
int(random.random() * e) + 1

In order to obtain an integer at this point, int() was used, and since the value should start from 1 instead of 0, 1 was added.

### ! Get a random number from start to end.

If we want to find any number between s and e in the above example, we can modify the formula slightly and create the following function.
def rangeNum(s, e):
return int(random.random() * (e - s + 1)) + s

The rangeNum() function receives a starting value s and an ending value e as arguments. Let's execute the code once to see if the results are displayed correctly.
rangeNum(1, 5)
rangeNum(10, 15)
rangeNum(100, 200)
rangeNum(10, 5)

The result is as follows.
rangeNum(1, 5)
// 3

rangeNum(10, 15)
//  13

rangeNum(100, 200)
// 125

rangeNum(10, 5)
// 11 Error occurreed

All values were output correctly except for the last execution value. In cases where the starting and ending values are reversed, the desired value could not be obtained. In this case, changing the order of the numbers would solve the problem. I tried modifying the code as follows.
def rangeNum(s, e):
if s > e:
prevS = s;
s = e;
e = prevS;

return int(random.random() * (e - s + 1)) + s

Now let's run the code again.
rangeNum(10, 5)
// 6, 7, 8, 10, 9

The above result was obtained when it was executed five times. It seems to be working well.