如何在 python 中使用 `or` 运算符在两个字符串之间随机 select?
How do I randomly select between two strings with the `or` operator in python?
我对 or 运算符有疑问。我刚开始 Python。我应该在文本框中打印 A 或 B。不能。问题是,只有 A. B 不打印。我能怎么做?谢谢
A = f"{name} {''.join(word2)} {inhabitants} inhabitants on an area of {surface}"
B = f"Che sale a"
text.insert(tk.END, A or B)
您似乎想随机 select 显示 A
或 B
。您可以使用预安装的 random
模块来执行此操作。 random.choice
接受一个列表并从该列表中随机 returns 一个元素,这是所需的行为。
import random
A = f"{name} {''.join(word2)} {inhabitants} inhabitants on an area of {surface}"
B = f"Che sale a"
text.insert(tk.END, random.choice([A, B]))
如果您想使用更安全的 random.choice
版本,您可以使用预安装的 secrets
module
import secrets
A = f"{name} {''.join(word2)} {inhabitants} inhabitants on an area of {surface}"
B = f"Che sale a"
text.insert(tk.END, secrets.choice([A, B]))
您需要创建一个 if
语句来决定在什么条件下打印 A 或 B。
Or 实际上与布尔值一起使用。如果其中一个布尔值为真,or
将 return 为真。
我对 or 运算符有疑问。我刚开始 Python。我应该在文本框中打印 A 或 B。不能。问题是,只有 A. B 不打印。我能怎么做?谢谢
A = f"{name} {''.join(word2)} {inhabitants} inhabitants on an area of {surface}"
B = f"Che sale a"
text.insert(tk.END, A or B)
您似乎想随机 select 显示 A
或 B
。您可以使用预安装的 random
模块来执行此操作。 random.choice
接受一个列表并从该列表中随机 returns 一个元素,这是所需的行为。
import random
A = f"{name} {''.join(word2)} {inhabitants} inhabitants on an area of {surface}"
B = f"Che sale a"
text.insert(tk.END, random.choice([A, B]))
如果您想使用更安全的 random.choice
版本,您可以使用预安装的 secrets
module
import secrets
A = f"{name} {''.join(word2)} {inhabitants} inhabitants on an area of {surface}"
B = f"Che sale a"
text.insert(tk.END, secrets.choice([A, B]))
您需要创建一个 if
语句来决定在什么条件下打印 A 或 B。
Or 实际上与布尔值一起使用。如果其中一个布尔值为真,or
将 return 为真。