So, I've been writing a code in Python lately and it's been working perfectly until I wanted to have Python choose between two different outcomes. The part of the code that doesn't seem to work looks like this:
line = ( (random.choice(str_a) + \
random.choice(str_b) + \
random.choice(str_c) + \
random.choice(str_d) + \
random.choice(str_e) + \
random.choice(str_f)) or \
((str_g) + (random.choice(str_h)) )
str_a, b, c, d, e, f, g, h
are all lists that contain several words.
Now I want Python to randomly choose between either the combination of a-f
OR the combination of f,g
.
For some reason I do not get any errors, but Python just keeps choosing for the first option.
Thanks in advance!
Using split() method : This function helps in getting multiple inputs from users. It breaks the given input by the specified separator. If a separator is not provided then any white space is a separator.
You can use the choices function in python to achieve this. If you want values to be chosen to be only -40 or 40, the second argument is the probability/weights. OP wants either -40 or 40, not a value between -40 and 40.
Use the random. sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.
Python Random choice() Method The choice() method returns a randomly selected element from the specified sequence. The sequence can be a string, a range, a list, a tuple or any other kind of sequence.
Why not use choice again?
line = random.choice([random.choice(str_a) + random.choice(str_b) + random.choice(str_c) + random.choice(str_d) + random.choice(str_e) + random.choice(str_f)), (str_g) + (random.choice(str_h)])
Try the following:
if random.choice((True, False)):
line = random.choice(str_a) + random.choice(str_b) + random.choice(str_c) + random.choice(str_d) + random.choice(str_e) + random.choice(str_f)
else:
line = str_g + random.choice(str_h)
This randomly gives you either one of each of the elements in str_a
, str_b
, str_c
, str_d
, str_e
, str_f
or it gives you str_g + random.choice(str_h)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With