- 此问题在此处已有答案**:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?(8个答案)
三年前关闭了。
在python3.6中,我试图让字符串在字符之间有延迟,并且在句子末尾的标点符号有更长的延迟,以伪模拟英语口语。这是我的代码。我的问题是我得到了字符之间的延迟,但是我没有得到句子之间更长的延迟。
import time
import sys
def delay_print(s):
for c in s:
if c != "!" or "." or "?":
sys.stdout.write(c)
# If I comment out this flush, I get each line to print
# with the longer delay, but I don't get a char-by char
# delay
# for the rest of the sentence.
sys.stdout.flush()
time.sleep(0.05)
elif c == "!" or "." or "?":
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(3)
delay_print( """
Hello.
I want this to have an added delay after sentence-ending
punctuation?
But I also want it to have a shorter delay after each character
that isn't one of those chars.
This is supposed to mimic speech patterns. Like if you've ever
played SNES Zelda: A Link to the Past.
Why isn't this code doing what I want it to?.
What I've written is broken and I don't know why!
""")
3条答案
按热度按时间kfgdxczn1#
你的
or
子句没有做你认为它在做的事情。第一个子句检查以下三个条件中是否有一个为True:character != "!"
bool(".")
bool("?")
请注意,2和3始终为真。
If语句短路求值。如果字符输入是
.
,它将检查条件1并发现它为false。然后它将在求值False or "."
中包含条件2。由于"."
始终为true,因此它短路并返回求值为true的"."
。自己尝试一下,在解释器中键入False or "."
,你会发现它会返回"."
。就我个人而言,我会使用如下的set实现来完成此操作:
vc9ivgsu2#
无论
c
的值是多少,您测试的两个条件都将始终计算为True
:正如另一位用户所建议的,将测试更改为以下内容可能更有意义:
此外,在一个更文体的说明,我会考虑使用随机延迟之间的字母,使它更有机的感觉。
hmae6n7t3#
给予看!你的第一个if语句需要用“and”代替“or”,因为它总是True。