Python3 Func Number Choice
# Python3.x Python3 choice() Function
[ Python3 Numbers](#)
* * *
## Description
The **choice()** method returns a random item from a list, tuple, or string.
* * *
## Syntax
Here is the syntax for the choice() method:
import random random.choice( seq )
**Note:** choice() cannot be accessed directly. You need to import the random module and then call the method through the random static object.
* * *
## Parameters
* seq -- Can be a list, tuple, or string.
* * *
## Return Value
Returns a random item.
* * *
## Example
The following examples demonstrate the use of the choice() method:
## Example
#!/usr/bin/python3
import random
print("Return a random number from range(100): ",random.choice(range(100)))
print("Return a random element from list [1, 2, 3, 5, 9]): ",random.choice([1,2,3,5,9]))
print("Return a random character from string '': ",random.choice(''))
The output of the above example after running is:
Return a random number from range(100): 68Return a random element from list [1, 2, 3, 5, 9]): 2Return a random character from string '': u
Here is a simple implementation of a random password generator:
## Example
import random
import string
def generate_password(length):
# Define the set of available characters for the password
chars =string.ascii_letters + string.digits + string.punctuation
# Randomly select characters to generate the password
password =''.join(random.choice(chars)for _ in range(length))
return password
random_pwd = generate_password(6)# Output length of 6
print(random_pwd)
In the example above, the generate_password() function accepts an integer parameter `length`, which represents the desired length of the password. It then uses the `random` and `string` modules from the Python standard library to generate a random password. **string.ascii_letters** contains all letters (uppercase and lowercase), **string.digits** contains all digits, and **string.punctuation** contains all punctuation symbols.
`random.choice(chars)` randomly selects a character from the character set `chars`, and then the `join()` method concatenates the generated characters together to form the password.
The output of the above example after running is:
R?u|<K
[ Python3 Numbers](#)
YouTip