简体   繁体   English

从一系列数字中随机选择数字 - Python

[英]Choose number at random from a range of numbers - Python

I'm making a game and I would like make my char's damage range(4,7),我正在制作游戏,我想让我的角色的伤害范围(4,7),

To inflict damage, im doing enemyhp - chardamage, How would I make chardamage a random number from the range(4,7) ?为了造成伤害,我在做enemyhp - chardamage,我如何让chardamage 成为range(4,7)中的随机数?

You can do this using random.randrange :您可以使用random.randrange执行此操作:

random.randrange(4, 8)

You need to use 8 because in Python, the range is inclusive of the lower bound and exclusive of the upper bound.您需要使用 8 因为在 Python 中,范围包括下限且不包括上限。

import random
print random.randint(4,7)

.... ……

if you want floats then如果你想要浮动然后

print random.uniform(4,7)
import random

damage = random.randint(4, 7) # To get random num from {4,5,6,7}

You need range(4,8) because the upper bound is always -1.您需要range(4,8) ,因为上限始终为 -1。 range(4,7) will give you 4,5,6 range(4,7)会给你4,5,6

from random import choice
choice(range(4,8))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM