Issue
I have a very simple problem that I never thought I'd encounter with the or operator and an f-string. The problem is that one of the phrase_1_random random variables is always printed. While phrase_2_random is NEVER printed. What am I doing wrong?
I DON'T HAVE TO PRINT THEM BOTH AT THE SAME TIME
I would like to print phrase_1_random or phrase_2_random, but X, Y or Z are never printed
import random
text_1 = ("A", "B", "C")
text_2 = ("X", "Y", "Z")
phrase_1_random = random.choice(text_1)
phrase_2_random = random.choice(text_2)
result= f"{phrase_1_random}" or "{phrase_2_random}"
#or f"{phrase_1_random}" or f"{phrase_2_random}"
print(result)
Solution
It sounds like you're hoping that the or
operator will perform some sort of random selection of phrase_1_random
or phrase_2_random
, but that isn't what the or
operator does.
What the or
operator does
When the or
operator is used in the syntax you've provided above, it will evaluate the values to the right of the assignment operator (=
) from left to right. The first value that is "truthy" (in this case, the first value that is a non-empty string) will be used for assignment.
Example:
a = ""
b = "B"
thing = a or b # thing will be "B"
x = "X"
y = "Y"
thing2 = x or y # thing2 will be "X"
What you probably want
If you'd like some sort of random selection from either phrase_1_random
or phrase_2_random
, you could use the random
library for that as well:
result= random.choice([phrase_1_random, phrase_2_random])
Answered By - captnsupremo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.