Latest web development tutorials

Python3 choice () function

Python3 digital Python3 digital


description

choice () method returns a random list of items, tuple or string.


grammar

The following is the syntax choice () method:

import random

random.choice( seq  )

Note: choice () is not directly accessible, you need to import the random module, and then call the method by random static objects.


parameter

  • seq - may be a list, tuple or string.

return value

Returns a random item.

Examples

The following shows an example of the use of choice () method:

#!/usr/bin/python3
import random

print ("从 range(100) 返回一个随机数 : ",random.choice(range(100)))
print ("从列表中 [1, 2, 3, 5, 9]) 返回一个随机元素 : ", random.choice([1, 2, 3, 5, 9]))
print ("从字符串中 'w3big' 返回一个随机字符 : ", random.choice('w3big'))

After running the above example output is:

从 range(100) 返回一个随机数 :  68
从列表中 [1, 2, 3, 5, 9]) 返回一个随机元素 :  2
从字符串中 'w3big' 返回一个随机字符 :  u

Python3 digital Python3 digital