mercredi 25 juillet 2018

Nested if/ elif statements produce weird result

I want to create a code snippet helping me to practise conjugating verbs by giving me random English prompts. I do this with the combination of random items from three lists (Personal pronouns, time, verb) and nested if/ elif statements. However, the code produces unexpected results and I can't figure out why.

Here is the code:

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

What I get as output:

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

What I want as output: similar to the above but with "You are reading", "We are writing" etc.

There must be some issue I'm unaware of with the loops (and one loop being ignored) but I don't know what or why - can someone point me in the right direction?

Many thanks in advance. :)

Aucun commentaire:

Enregistrer un commentaire