Input prompt within a while-true loop [duplicate]

五迷三道 提交于 2019-12-13 02:14:32

问题


I want to create a program that prompts for input and based on this input provides with a tailored reply.

As the code is, it works perfectly, with the exception that it is not looping at all. (After running the script in CMD or Powershell it terminates and dies.)

I want the program to return to the input prompt following every run. I think I need the return function but I have no idea what kind of argument to give it.

Also, the ValueError argument is kind of pointless, there is an issue there.

Name = input ("What is your name ? ").strip().lower()

while True:

    try:
        if Name in ("A"):
            print("message for A")
            break       
        else:
            if Name in ("N"):
                print("message for N")
                break
    except ValueError:
        print ("Sorry, my only purpose is to talk to N and A")

    else:
        print("dammit")
        break

回答1:


You want to repeat try-except... And the thing you want to try is input(), so you need to put basically all the code within the loop.

And remove the lower(), or convert to "a" and "n"

while True:
    try:
        name = input ("What is your name ? ").strip()
        if name.startswith("A"):
            print("message for A")
            break       
        elif name.startswith("N"):
            print("message for N")
            break
        else:
            print("Sorry, my only purpose is to talk to N and A")
    except ValueError:
        print ("Sorry, my only purpose is to talk to N and A")


来源:https://stackoverflow.com/questions/50498557/input-prompt-within-a-while-true-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!