SoFunction
Updated on 2024-12-19

Python implementation of random numbers and example code

Python3 implementation of random numbers

  • random is used to generate random numbers, we can use it to generate random numbers or select strings.
  • (x) Change the seedseed of the random number generator.
  • You don't usually have to set up seed specifically; Python chooses it automatically.
  • () is used to generate a random floating point number n,0 <= n < 1
  • (a,b) is used to generate a random floating-point number within a specified range of the generated random integer a<=n<=b;
  • (a,b) is used to generate a specified range of integers, a for the lower limit, b for the upper limit, the generated random integer a<=n<=b; if a=b, then n=a; if a>b, the report error
  • ([start], stop [,step]) Get a random number from the set within the specified range [start,stop) incremented by the specified base, the default value of base is 1.
  • (sequence) Get a random element from a sequence, the parameter sequence denotes an ordered type, not a specific type, it refers to lists, tuples, strings, etc.
  • (x[,random]) is used to break up (shuffle) the elements of a list, which will change the original list
  • (sequence,k) retrieves k random elements from a specified sequence and returns them as a fragment, without changing the original sequence.

  However, one thing to note: Python random is a pseudo-random number.

  So, is it possible to borrow python random to realize true random numbers? The answer is No. A true random number is a number that is required to be generated based on an absolutely random event, i.e., it requires a causality-free random event, which then only exists in the field of philosophy ......

  Current random number generation is all statistically random, because the random sources are all natural events, which are sort of chaotic variables at best, and absolute causelessness probably doesn't exist.

  But stat random is basically enough I guess ......

  Better to be honest and use the random module ....

Code Demo

import random
# Random integers
import string

print((0,99))
# Randomly select an even number between 0 and 100
print((0, 101, 2))
# Random floating point numbers
print(())
print((1, 10))
# Random characters
print(('abcdefg&#%^*f'))
# Select a specific number of characters out of multiple characters
print(('abcdefghij',3))
# Select a specific number of characters from multiple characters to form a new string
# print(((['a','b','c','d','e','f','g','h','i','j'], 3)).replace(" ",""))
# Randomly selected strings
print( ( ['apple', 'pear', 'peach', 'orange', 'lemon'] ))
#Shuffle
items = [1, 2, 3, 4, 5, 6]
(items)
print("Shuffle:", items)
#Returns k random elements from a given sequence as a fragment, without changing the original sequence.
list = []
list = (items,2)
print(list)

  in the end

Thanks for reading, I hope this helps, and thanks for supporting this site!