gpt4 book ai didi

python - 嵌套的 if/elif 语句产生奇怪的结果

转载 作者:行者123 更新时间:2023-12-01 01:44:30 26 4
gpt4 key购买 nike

我想创建一个代码片段,通过给我随机的英语提示来帮助我练习动词变位。我使用三个列表(人称代词、时间、动词)中的随机项目和嵌套的 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

我想要的输出:与上面类似,但带有“你正在阅读”、“我们正在写作”等。

肯定存在一些我不知道的循环问题(并且一个循环被忽略),但我不知道是什么或为什么 - 有人可以指出我正确的方向吗?

提前非常感谢。 :)

最佳答案

更改为这些行:

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":

无法正常工作。它不是一起检查'He'或'She'。它的工作原理类似于 if(r_pers_pro == "He") 或 ("She"):
这将始终评估为 true,这就是跳过下一个循环的原因。

关于python - 嵌套的 if/elif 语句产生奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51532462/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com