Random.randint(a, b) generates random integers containing a and b, random.randrange(a, b, step) generates random integers starting from a, not including b, and can be set step size; 2. random.random() generates random floating point numbers between [0.0, 1.0), random.uniform(a, b) generates random floating point numbers in the interval [a, b]; 3. random.choice(seq) randomly selects an element from the sequence, random.choices(seq, k=n) can repeatedly select n, random.sample(seq, k=n) does not repeat; 4. random.shuffle(list) directly disrupts the order of the list and does not return the new list; 5. random.seed(n) sets a random seed so that subsequent random results can be reproduced. It is suitable for debugging and testing. All operations are implemented based on the random module. You need to import the module first. When using it, you need to pay attention to the boundary inclusion situation and whether the sampling is repeated. The above method covers the main common scenarios of random number generation in Python and can meet most daily programming needs.
Generating random numbers is a very common operation in Python, mainly using the random
module. Below are some commonly used examples covering common scenarios such as integers, floating point numbers, interval selection, etc.

1. Generate random integers ( randint
and randrange
)
import random # Generate random integers between 1 and 10 (including 1 and 10) num = random.randint(1, 10) print(num) # Generate random integers between 0 and 9 (not including 10) num2 = random.randrange(0, 10) print(num2)
randint(a, b)
: both a and b contain
randrange(a, b)
: contains a, not b, you can also add step size, such asrandrange(0, 10, 2)
only generates even numbers
2. Generate random floating point numbers
# Generate random floating point number between 0.0 and 1.0 f = random.random() print(f) # Generate floating point numbers in the specified range, such as between 1.5 and 10.5 f2 = random.uniform(1.5, 10.5) print(f2)
-
random()
: Returns the number between [0.0, 1.0) -
uniform(a, b)
: Returns the floating point number in the interval [a, b]
3. Randomly select elements from the list
colors = ['red', 'blue', 'green', 'yellow'] # Choose a random choice = random.choice(colors) print(choice) # Randomly select multiple (repeatable) choices = random.choices(colors, k=3) print(choices) # Select multiple randomly (no duplicate) sample = random.sample(colors, k=2) print(sample)
-
choice()
: choose one -
choices()
: Repeatable sampling -
sample()
: No repeated sampling, k cannot be greater than the list length
4. Disrupt the order of lists (shuffle)
numbers = [1, 2, 3, 4, 5] random.shuffle(numbers) # Scramble in place and do not return the new list print(numbers)
Note: shuffle
directly modifys the original list and does not return the new list.

5. Set random seeds (for reproducible results)
random.seed(42) # Set seed print(random.randint(1, 100)) # The result is the same for each run
In debugging or experimenting, setting seed
can make random numbers "predictable" and facilitate testing.
Basically these common operations. The random
module is simple and practical, suitable for most daily needs. Not complicated but it is easy to ignore details, such as whether the boundary is contained, whether it is repeatable, etc.

The above is the detailed content of python random number example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Lazy loading only queries when accessing associations can easily lead to N 1 problems, which is suitable for scenarios where the associated data is not determined whether it is needed; 2. Emergency loading uses with() to load associated data in advance to avoid N 1 queries, which is suitable for batch processing scenarios; 3. Emergency loading should be used to optimize performance, and N 1 problems can be detected through tools such as LaravelDebugbar, and the $with attribute of the model is carefully used to avoid unnecessary performance overhead.

Laravel supports the use of native SQL queries, but parameter binding should be preferred to ensure safety; 1. Use DB::select() to execute SELECT queries with parameter binding to prevent SQL injection; 2. Use DB::update() to perform UPDATE operations and return the number of rows affected; 3. Use DB::insert() to insert data; 4. Use DB::delete() to delete data; 5. Use DB::statement() to execute SQL statements without result sets such as CREATE, ALTER, etc.; 6. It is recommended to use whereRaw, selectRaw and other methods in QueryBuilder to combine native expressions to improve security

Go generics are supported since 1.18 and are used to write generic code for type-safe. 1. The generic function PrintSlice[Tany](s[]T) can print slices of any type, such as []int or []string. 2. Through type constraint Number limits T to numeric types such as int and float, Sum[TNumber](slice[]T)T safe summation is realized. 3. The generic structure typeBox[Tany]struct{ValueT} can encapsulate any type value and be used with the NewBox[Tany](vT)*Box[T] constructor. 4. Add Set(vT) and Get()T methods to Box[T] without

JWT is an open standard for safe transmission of information. In Java, authentication and authorization can be achieved through the JJWT library. 1. Add JJWT API, Impl and Jackson dependencies; 2. Create JwtUtil tool class to generate, parse and verify tokens; 3. Write JwtFilter intercepts requests and verify BearerTokens in Authorization header; 4. Register Filter in SpringBoot to protect the specified path; 5. Provide a login interface to return JWT after verifying the user; 6. The protected interface obtains user identity and roles through parsing the token for access control, and ultimately realizes a stateless and extensible security mechanism, suitable for distributed systems.

Use datetime.strptime() to convert date strings into datetime object. 1. Basic usage: parse "2023-10-05" as datetime object through "%Y-%m-%d"; 2. Supports multiple formats such as "%m/%d/%Y" to parse American dates, "%d/%m/%Y" to parse British dates, "%b%d,%Y%I:%M%p" to parse time with AM/PM; 3. Use dateutil.parser.parse() to automatically infer unknown formats; 4. Use .d

json.loads() is used to parse JSON strings into Python data structures. 1. The input must be a string wrapped in double quotes and the boolean value is true/false; 2. Supports automatic conversion of null→None, object→dict, array→list, etc.; 3. It is often used to process JSON strings returned by API. For example, response_string can be directly accessed after parsing by json.loads(). When using it, you must ensure that the JSON format is correct, otherwise an exception will be thrown.

Use regular expression capture group in Notepad to effectively reorganize text. First, you need to open the replacement dialog box (Ctrl H), select "Search Mode" as "regular expression", 1. Use () to define the capture group, such as (\w ) to capture words; 2. Use \1 and \2 to reference the corresponding group in the replacement box; 3. Example: Exchange the name "JohnDoe" as "Doe, John", find (\w )\s (\w ), replace it with \2,\1; 4. Date format conversion 2023-12-25 to 25/12/2023, find (\d{4})-(\d{2})-(\d{2}), replace it with \3/\2/\1; 5. Log reordering can extract time, level, ID and other information

Python's ternary operator is used to concisely implement if-else judgment, and its syntax is "value_if_trueif conditionelsevalue_if_false"; 1. It can be used for simple assignment, such as returning the corresponding string based on positive and negative values; 2. It can avoid division errors, such as determining that the denominator is non-zero and then division; 3. It can select content according to conditions in string format; 4. It can assign labels to different elements in list derivation formula; it should be noted that this operator is only suitable for binary branches and should not be nested multiple layers. Complex logic should use the traditional if-elif-else structure to ensure readability.
