简体   繁体   中英

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),

To inflict damage, im doing enemyhp - chardamage, How would I make chardamage a random number from the range(4,7) ?

You can do this using 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.

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,7) will give you 4,5,6

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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