python代码随机生成
时间: 2023-10-12 14:58:33 浏览: 37
回答: 在Python中,可以使用random模块中的函数来生成随机数和随机字符串。其中,random.randint()函数可以生成指定范围内的随机整数,例如:
```python
import random
real = random.randint(-10, 10)
imag = random.randint(-10, 10)
z = complex(real, imag)
print(z)
```
这段代码生成了一个指定范围内的随机复数。
相关问题
用python代码随机生成验证码
好的,以下是一个简单的 Python 代码,用于生成随机验证码:
```python
import random
import string
def generate_code(length):
# 生成指定长度的随机字符串
code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))
return code
# 生成 6 位长度的验证码
code = generate_code(6)
print(code)
```
这段代码通过引入 Python 内置的 `random` 和 `string` 模块,使用 `random.choices()` 方法从包含所有大写字母和数字的字符串中随机选取指定长度的字符,生成随机验证码。
python代码随机生成10个小于100的正数
可以使用以下代码生成10个小于100的正整数:
```
import random
numbers = []
for i in range(10):
num = random.randint(1, 99)
numbers.append(num)
print(numbers)
```
输出结果示例:
```
[49, 70, 91, 14, 6, 43, 57, 3, 45, 60]
```