Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python while true循环中的输入提示_Python_Python 3.x_While Loop - Fatal编程技术网

Python while true循环中的输入提示

Python while true循环中的输入提示,python,python-3.x,while-loop,Python,Python 3.x,While Loop,我想创建一个程序,提示输入,并根据此输入提供定制的回复 正如代码所示,它工作得非常完美,唯一的例外是它根本没有循环。(在CMD或Powershell中运行脚本后,脚本终止并终止。) 我希望程序在每次运行后返回到输入提示符。我想我需要返回函数,但我不知道应该给出什么样的参数 另外,ValueError参数是没有意义的,这是一个问题 Name = input ("What is your name ? ").strip().lower() while True: try:

我想创建一个程序,提示输入,并根据此输入提供定制的回复

正如代码所示,它工作得非常完美,唯一的例外是它根本没有循环。(在CMD或Powershell中运行脚本后,脚本终止并终止。)

我希望程序在每次运行后返回到输入提示符。我想我需要返回函数,但我不知道应该给出什么样的参数

另外,ValueError参数是没有意义的,这是一个问题

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

您想重复
尝试,除了
。。。您想尝试的是
输入()
,因此您需要将基本上所有的代码放在循环中

并移除
下部()
,或转换为
“a”
“n”


除此之外,您必须在正在调用的
lower()
循环中提示用户,因此输入何时会在
(“A”,“N”)
?此外,这里没有面向对象的概念
,如果(“A”)
中的名称错误,它将测试整个字符串
名称是否出现在元组
(“A”)
中。因此,即使Name=“Andy”,如果Name在(“A”)
中,它也会失败。您需要
如果name.startswith('A')
。如果名称[0]=='A'
也可以编写
,但这并不完全等效,如果名称为空,它将抛出indexer。您不应该将变量命名为大写,因此
name
不是
name
。这是Python PEP-8标准。只有类名可以有大写字母,例如
WidgetFactory
,或者常量,例如
LUXURY\u YACHT=666
,如果名称与If子句或If子句不匹配并且没有中断,那么您就知道它不是N或A。因此,您可以删除else子句和
除了值错误:pass
,然后移动
打印(“对不起,我的唯一目的是在底部与N和A进行对话,因此它会在每个循环结束时执行。”。
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")