Python Tutorial

# Random Numbers in Python

In Python, generating random numbers can be achieved using the random module. This module offers various functions to generate different types of random numbers. Below are examples illustrating the process:

## Generating Random Integers

The randint() function generates random integers within a specified range.

import random random_integer = random.randint(1, 100) # Generates a random integer between 1 and 100 (inclusive) print("Random Integer:", random_integer)

## Generating Random Floating-Point Numbers

The uniform() function generates random floating-point numbers within a specified range.

import random random_float = random.uniform(0.0, 1.0) # Generates a random float between 0.0 and 1.0 print("Random Float:", random_float)

## Selecting Random Elements from a List

The choice() function selects a random element from a given list.

import random fruits = ["apple", "banana", "cherry", "date", "elderberry"] random_fruit = random.choice(fruits) # Selects a random fruit from the list print("Random Fruit:", random_fruit)

## Shuffling a List

The shuffle() function rearranges the elements of a list randomly.

import random numbers = [1, 2, 3, 4, 5] random.shuffle(numbers) # Shuffles the elements in the list print("Shuffled Numbers:", numbers)

## Generating Random Decimals

The random() function generates random decimal numbers between 0 and 1.

import random random_decimal = random.random() # Generates a random decimal between 0 and 1 print("Random Decimal:", random_decimal)

## seed() function

You can also use the seed() function to control the randomness of the numbers generated by the random() and randint() functions. The seed() function takes an integer as its argument, and it will generate the same sequence of random numbers for any given seed value. This can be useful if you want to reproduce the same results from your code in different executions.

import random random.seed(12345) print(random.random()) print(random.randint(1, 100))

This code will always print the same two random numbers, regardless of how many times it is executed. The first number will be 0.789234, and the second number will be 5.

### Conclusion

Generating random numbers in Python is facilitated by the random module, offering functions like randint() for integers, uniform() for floating-point numbers, and choice() for selecting elements from a list randomly. Shuffling lists using shuffle() and generating random decimals using random() further enhance its capabilities, catering to diverse applications from gaming to simulations.