我想创建一个代码段,通过给我随机的英语提示,帮助我练习共轭动词。我使用来自三个列表(人称代词,时间,动词)和嵌套的if / elif语句的随机项的组合来执行此操作。但是,代码会产生意外的结果,我不知道为什么。
代码如下:
import random
personal_pronouns = ["I", "We", "You (M)", "You (F)", "You (Pl)", "He", "She", "They"]
time = ["P. Simpl", "F. Simpl", "P. Cont"]
verbs = ["read", "write"]
# select random list items
for i in range(0,10):
r_pers_pro = random.choice(personal_pronouns)
r_time = random.choice(time)
r_verb = random.choice(verbs)
# adjust output to be grammatically correct
if r_time == "P. Simpl":
if r_pers_pro == "He" or r_pers_pro == "She": print(r_pers_pro + " " + r_verb + "s")
else: print(r_pers_pro + " " + r_verb)
elif r_time == "F. Simpl": print(r_pers_pro + " will " + r_verb)
elif r_time == "P. Cont":
if r_verb[-1] == "e": r_verb = r_verb[0:-1]
if r_pers_pro == "I": print(r_pers_pro + " am " + r_verb + "ing")
elif r_perspro == "He" or "She": print(r_perspro + " is " + r_verb + "ing")
elif r_perspro == "You (M)" or "You (F)" or "You (Pl)" or "We" or "They":
print(r_pers_pro + " is / are " + r_verb + "ing")
else: print("Not defined")
else: print("NOT DEFINED")
我得到的输出是什么
You (Pl) write
I is writing # this is unexpected/ unwanted
I is writing # same
I write
You (M) read
They read
I am reading
I is reading # same
I is reading # same
We write
我想要输出的内容:与上述内容类似,但带有“您正在阅读”,“我们正在写作”等。
循环肯定存在一些我不知道的问题(一个循环被忽略了),但我不知道是什么或为什么-有人可以指出正确的方向吗?
非常感谢。 :)
答案 0 :(得分:2)
更改为以下几行:
elif r_pers_pro == "He" or r_pers_pro == "She": print(r_pers_pro + " is " + r_verb + "ing")
elif r_pers_pro == "You (M)" or r_pers_pro == "You (F)" or r_pers_pro=="You (Pl)" or r_pers_pro=="We" or r_pers_pro== "They":
or
无法正常工作。它不是一起检查'He' or 'She'
。
它的工作方式类似于if(r_pers_pro == "He") or ("She"):
这将始终为true,这就是为什么要跳过下一个循环的原因。