f-string e Logical Operators OR?

Question:

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)
Asked By: Dragomir Cro

||

Answers:

It’s doing exactly what is supposed to do.
Here’s an exctract form (w3schools):

Python considers empty strings as having a boolean value of the
‘false’ and non-empty strings as having a boolean value of ‘true’. For
the ‘and’ operator if the left value is true, then the right value is
checked and returned. If the left value is false, then it is returned
For the ‘or’ operator if the left value is true, then it is returned,
otherwise, if the left value is false, then the right value is
returned.

since phrase 1 always has a value it will always be printed.

Answered By: Ricardo

Try

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}", f"{phrase_2_random}"]
print(random.choice(result))

Or more compactly

import random

chars = ['A', 'B', 'C', 'X', 'Y', 'Z']
print(random.choice(chars))
Answered By: Přemysl Šťastný

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
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.