Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Python choose between two options?

Tags:

python

random

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, hare 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!

like image 705
user3219241 Avatar asked Jan 21 '14 12:01

user3219241


People also ask

How do you give two options to a function in Python?

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.

How do you select between two values in Python?

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.

How do you generate random choices in Python?

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.

How do you select a function in Python?

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.


Video Answer


2 Answers

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)])
like image 152
arocks Avatar answered Sep 27 '22 23:09

arocks


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

like image 22
Simeon Visser Avatar answered Sep 27 '22 22:09

Simeon Visser