4 examples of 'random choices python' in Python

Every line of 'random choices python' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
84def choice(*args, **kwargs):
85 return _default.choice(*args, **kwargs)
273def choice(self, seq):
274 """Choose a random element from a non-empty sequence."""
275 return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty
67def weighted_choice(choices):
68 total = sum(w for c, w in choices)
69 r = random.uniform(0, total)
70 upto = 0
71 for c, w in choices:
72 if upto + w >= r:
73 return c
74 upto += w
75 assert False, "Shouldn't get here"
20def choice_input(question, choices, default=None):
21 """
22 Ask user for choice in a list, indexed by integer response
23
24 :param default:
25 :param question: The question to ask
26 :param choices: List of possible choices
27 :return: Selected choice by user
28 :rtype: int
29 """
30 print("%s:" % question)
31 for i, choice in enumerate(choices):
32 print("-%s) %s" % (i + 1, choice))
33 result = input("Select an option: ")
34 try:
35 value = int(result)
36 if 0 < value <= len(choices):
37 return value
38 except ValueError:
39 if default:
40 return default
41 else:
42 return choice_input('Please select a valid value', choices, default)

Related snippets