mercredi 24 mars 2021

Python: print input in reverse order (conditions: only words (at least 4 words))

I need to print input from the user in reverse order using a function. As a condition, just words (no floats/ int) should be allowed & at least four words need to be entered. e.g.: How can I help you --> you help I can How

It should'nt be possible to input: "4 5 6 7" or "There are 2 dogs" Here's my current code, however I didn't integrate that only strings are allowed so far:

def phrase():
    while True:
        user_input = input("Please insert a phrase: ")
        words = user_input.split(" ")
        n = len(words)
        if n >= 4:
            words = words[-1::-1]
            phrase_reverse = " ".join(words)
            print(phrase_reverse)
        else:
            print("Please only insert words and at least 4 ")
            continue
        break


phrase()

I tried with if n<4 and words == str:, if n<4 and words != string etc.. However, that didn't work. Could you please help me solving this issue? Maybe my code is wrong in general.

Aucun commentaire:

Enregistrer un commentaire