在 while-true 循环中输入提示 [英] Input prompt within a while-true loop

查看:40
本文介绍了在 while-true 循环中输入提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

正如代码一样,它运行得很好,除了它根本没有循环.(在 CMD 或 Powershell 中运行脚本后,它会终止并死亡.)

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.

此外,ValueError 参数有点无意义,那里有问题.

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

推荐答案

你想重复try-except...而你想要try的东西是input(),所以你需要把基本上所有的代码都放在循环中.

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.

并去掉lower(),或者转换为"a""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")

这篇关于在 while-true 循环中输入提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆