如何生成一个随机的 4 位数字并将其作为变量存储在 python 中?

Jac*_*ack 1 python random

我试图用 Python 猜数字游戏,但我遇到了麻烦。这是我到目前为止所拥有的:

import random
number = random.randit(1111,9999)
print(number)
Run Code Online (Sandbox Code Playgroud)

但出于某种原因,我得到了error一个关于random cannot be assigned to randit.

请问有什么帮助吗?

Bha*_*rel 9

你有一个错字。它是random.randint()

  • 谢谢,感觉自己好傻 (3认同)

Moy*_*ote 7

import random
number = random.randint(1000,9999)
print(number)
Run Code Online (Sandbox Code Playgroud)


Moh*_*med 6

尝试这个:

import string
from random import choice
chars = string.digits
random =  ''.join(choice(chars) for _ in range(4))
Run Code Online (Sandbox Code Playgroud)

每次运行时都会生成不同的 4 位数字。如果你想输入更多数字,只需更改范围即可。