1

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
smci
  • 32,567
  • 20
  • 113
  • 146
Gilgamesh1401
  • 49
  • 2
  • 2
  • 9
  • 2
    Amont other things, you have to prompt the user *inside* the loop – Olivier Melançon May 23 '18 at 22:52
  • 1
    You are calling `lower()`, so when would the input be in `("A", "N")`?? – OneCricketeer May 23 '18 at 23:01
  • Also, there are no object oriented concepts here – OneCricketeer May 23 '18 at 23:02
  • `if name in ("A")` is wrong, it's testing if the entire string `name` occurs in the tuple `("A")`. So even if Name="Andy" it would fail `if name in ("A")`. You want `if name.startswith('A')`. You could also write `if name[0]=='A'` but that's not quite equivalent, it will throw IndexError if name is empty. – smci May 24 '18 at 10:58
  • 1
    You shouldn't name variables uppercase, so `name` not `Name`. This is Python PEP-8 standard. Only class names can have capitals e.g. `WidgetFactory` or constants e.g. `LUXURY_YACHT = 666` – smci May 24 '18 at 11:00

1 Answers1

3

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")
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • If name doesn't match either if-clause and doesn't break, then you know it's not N or A. Hence you could remove the else-clause and `except ValueError: pass`, and move `print("Sorry, my only purpose is to talk to N and A")` to the bottom, so it gets executed at the end of every loop. – smci May 24 '18 at 10:52