Skip to content

Commit 11bf1c1

Browse files
[Edit] Python: .randint() (#7038)
* [Edit] SQL: DATEDIFF() * Update datediff.md * [Edit] Python: .randint() * Update content/python/concepts/random-module/terms/randint/randint.md * Update content/python/concepts/random-module/terms/randint/randint.md * Update content/python/concepts/random-module/terms/randint/randint.md ---------
1 parent c750d87 commit 11bf1c1

File tree

1 file changed

+186
-11
lines changed
  • content/python/concepts/random-module/terms/randint

1 file changed

+186
-11
lines changed
Lines changed: 186 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,219 @@
11
---
2-
Title: .randint()
3-
Description: 'Returns a random integer that exists between two values.'
2+
Title: '.randint()'
3+
Description: 'Generates a random integer within a specified range including both endpoints.'
44
Subjects:
55
- 'Computer Science'
66
- 'Data Science'
77
Tags:
88
- 'Functions'
99
- 'Methods'
10+
- 'Numbers'
1011
- 'Random'
1112
CatalogContent:
1213
- 'learn-python-3'
1314
- 'paths/computer-science'
1415
---
1516

16-
The `.randint()` method returns a random integer that exists between two `int` values, `int_a` and `int_b` (inclusive), passed as arguments.
17+
The **`.randint()`** method of Python's random module generates a random integer within a specified range. This method returns a single random integer value between two given endpoints, including both the start and end values in the possible results. The `.randint()` method provides an easy and efficient way to simulate random events, create unpredictable outcomes, and add randomness to Python applications.
18+
19+
The `.randint()` method is widely used in gaming applications, simulations, statistical sampling, testing scenarios, and any situation where you need to generate random integer values. Common use cases include dice rolling simulators, lottery number generators, password creation, random selection processes, and mathematical simulations where random data points are required.
1720

1821
## Syntax
1922

2023
```pseudo
21-
random.randint(int_a, int_b)
24+
random.randint(start, end)
2225
```
2326

24-
Another way of writing this would be `random.randrange(int_a, int_b + 1)`.
27+
**Parameters:**
28+
29+
- `start`: The lowest integer value that can be returned (inclusive). Must be an integer type.
30+
- `end`: The highest integer value that can be returned (inclusive). Must be an integer type.
31+
32+
**Return value:**
33+
34+
A random integer N where `start <= N <= end` (both endpoints included).
2535

26-
## Example
36+
## Example 1: Basic Random Integer Generation
2737

28-
In the example below, `.randint()` is used to return a random number between `0` and `50`:
38+
This example demonstrates the basic usage of `.randint()` to generate a single random integer within a specified range:
2939

3040
```py
3141
import random
3242

33-
print(random.randint(0, 50))
43+
# Generate a random integer between 1 and 10 (inclusive)
44+
random_number = random.randint(1, 10)
45+
print(f"Random number between 1 and 10: {random_number}")
46+
47+
# Generate a random integer between 50 and 100
48+
random_score = random.randint(50, 100)
49+
print(f"Random score: {random_score}")
50+
51+
# Generate multiple random numbers
52+
print("Five random numbers between 1 and 6:")
53+
for i in range(5):
54+
dice_roll = random.randint(1, 6)
55+
print(f"Roll {i+1}: {dice_roll}")
3456
```
3557

36-
## Codebyte Example
58+
The output of this code is:
3759

38-
The `.randint()` method can also be applied to negative `int` values, as shown in the example below:
60+
```shell
61+
Random number between 1 and 10: 7
62+
Random score: 83
63+
Five random numbers between 1 and 6:
64+
Roll 1: 4
65+
Roll 2: 2
66+
Roll 3: 6
67+
Roll 4: 1
68+
Roll 5: 3
69+
```
70+
71+
This example shows how to generate random integers for different ranges. Each call to `.randint()` produces a new random value within the specified bounds. The method can handle both small and large integer ranges effectively.
72+
73+
## Example 2: Dice Rolling Simulator
74+
75+
This example demonstrates a practical application of `.randint()` by creating a dice rolling simulator that mimics real-world gaming scenarios:
76+
77+
```py
78+
import random
79+
80+
def roll_dice(num_dice=1, sides=6):
81+
"""Simulate rolling dice and return the results."""
82+
rolls = []
83+
for i in range(num_dice):
84+
roll = random.randint(1, sides)
85+
rolls.append(roll)
86+
return rolls
87+
88+
def dice_game():
89+
"""Interactive dice rolling game."""
90+
print("Welcome to the Dice Rolling Simulator!")
91+
92+
while True:
93+
try:
94+
num_dice = int(input("How many dice would you like to roll? (1-5): "))
95+
if 1 <= num_dice <= 5:
96+
break
97+
else:
98+
print("Please enter a number between 1 and 5.")
99+
except ValueError:
100+
print("Please enter a valid number.")
101+
102+
print(f"\nRolling {num_dice} dice...")
103+
results = roll_dice(num_dice)
104+
105+
print("Results:")
106+
for i, roll in enumerate(results, 1):
107+
print(f"Die {i}: {roll}")
108+
109+
total = sum(results)
110+
print(f"Total: {total}")
111+
112+
# Check for special combinations
113+
if num_dice == 2:
114+
if results[0] == results[1]:
115+
print("Doubles! You rolled the same number on both dice!")
116+
if total == 7:
117+
print("Lucky seven!")
118+
119+
# Run the dice game
120+
dice_game()
121+
```
122+
123+
The output of this code is:
124+
125+
```shell
126+
Welcome to the Dice Rolling Simulator!
127+
How many dice would you like to roll? (1-5): 2
128+
129+
Rolling 2 dice...
130+
Results:
131+
Die 1: 4
132+
Die 2: 3
133+
Total: 7
134+
Lucky seven!
135+
```
136+
137+
This example creates an interactive dice rolling simulator that demonstrates practical usage of `.randint()`. The program validates user input, generates random dice rolls, calculates totals, and identifies special combinations. This type of application is commonly used in board games, casino simulations, and probability demonstrations.
138+
139+
## Codebyte Example: Random Password Generator
140+
141+
This example shows how `.randint()` can be used to create a secure random password generator by selecting random characters from different character sets:
39142

40143
```codebyte/python
41144
import random
145+
import string
146+
147+
def generate_password(length=12):
148+
"""Generate a random password using randint() for character selection."""
149+
# Define character sets
150+
lowercase = string.ascii_lowercase
151+
uppercase = string.ascii_uppercase
152+
digits = string.digits
153+
special_chars = "!@#$%^&*"
154+
155+
# Combine all character sets
156+
all_chars = lowercase + uppercase + digits + special_chars
157+
158+
password = []
159+
160+
# Ensure at least one character from each category
161+
password.append(random.choice(lowercase))
162+
password.append(random.choice(uppercase))
163+
password.append(random.choice(digits))
164+
password.append(random.choice(special_chars))
165+
166+
# Fill remaining positions with random characters
167+
for i in range(length - 4):
168+
# Use randint to select a random index from all_chars
169+
random_index = random.randint(0, len(all_chars) - 1)
170+
password.append(all_chars[random_index])
171+
172+
# Shuffle the password to randomize character positions
173+
random.shuffle(password)
174+
175+
return ''.join(password)
176+
177+
def password_generator():
178+
"""Interactive password generator."""
179+
print("Random Password Generator")
42180
43-
print(random.randint(-25, 25))
181+
try:
182+
length = 12
183+
if 8 <= length <= 20:
184+
password = generate_password(length)
185+
print(f"Generated password: {password}")
186+
187+
# Generate multiple passwords for options
188+
print("\nAlternative passwords:")
189+
for i in range(3):
190+
alt_password = generate_password(length)
191+
print(f"Option {i+1}: {alt_password}")
192+
else:
193+
print("Please enter a length between 8 and 20.")
194+
except ValueError:
195+
print("Please enter a valid number.")
196+
197+
# Run the password generator
198+
password_generator()
44199
```
200+
201+
This example demonstrates how `.randint()` can be used for security-related applications. The function generates random indices to select characters from different character sets, ensuring password complexity and unpredictability. This approach is useful for creating secure passwords, generating test data, and implementing security features.
202+
203+
## Frequently Asked Questions
204+
205+
### 1. What happens if the start parameter is greater than the end parameter?
206+
207+
If you pass a start value that is greater than the end value, `.randint()` raises a `ValueError` with the message "empty range for randrange()". Always ensure that `start <= end`.
208+
209+
### 2. Can `.randint()` generate floating-point numbers?
210+
211+
No, `.randint()` only generates integer values. If you need random floating-point numbers, use `random.uniform()` or `random.random()` instead.
212+
213+
### 3. Can I use `.randint()` with negative numbers?
214+
215+
Yes, `.randint()` works with negative integers. For example, `random.randint(-10, -1)` will generate random integers between -10 and -1 inclusive.
216+
217+
### 4. How does `.randint()` compare to `randrange()`?
218+
219+
`.randint(a, b)` is equivalent to `randrange(a, b+1)`. The key difference is that `.randint()` includes both endpoints, while `randrange()` excludes the stop value.

0 commit comments

Comments
 (0)