Necrex
Necrex

Reputation: 1

Why do I get a syntax error when trying to test for correct user input?

print ("Hello, and welcome to TEXT RPG!")
name = input("Would you be so kind as to tell us your name?")
print (""+Name+" Is it? What a stupid, stupid name!")
print ("And you, "+Name+" are a stupid, stupid child.!")
print ("However. There is hope for your worthless being yet!")
print ("I will train you and make you less of a worthless being.")

accept1 = input("Do you accept?")

while accept1 = "Yes" "No" "no" "yes" "n" "y":
    print ("Alright then! Let us begin!")
else:
    print ("That's not an answer you insolent brat!")
    accept1 = input("Do you accept?")

For some reason I get a syntax error with no red bar. Can anyone help? I'm using Python 3.5

Upvotes: 0

Views: 358

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124758

There are three errors with

while accept1 = "Yes" "No" "no" "yes" "n" "y":
  1. You cannot use assignment in a while statement, you need to use ==, not = there. This is the source of your syntax error:

    >>> while accept1 = "Yes" "No" "no" "yes" "n" "y":
      File "<stdin>", line 1
        while accept1 = "Yes" "No" "no" "yes" "n" "y":
                      ^
    SyntaxError: invalid syntax
    
  2. You created a test for the string "YesNonoyesny", as Python automatically concatenates consecutive strings. If you wanted to test for multiple possible values, use a containment test.

  3. while creates an endless loop, since if the test is true, you never change accept1 in the loop and the condition will be forever true. Use if here instead.

This works:

if accept1 in {"Yes", "No", "no", "yes", "n", "y"}:

because that creates a set of strings to test again, and the accept1 in ... test is true if the value of accept1 is a member of the set.

You could make the test a little more compact and flexible by using str.lower():

if accept1.lower() in {"yes", "no", "n", "y"}:

If you still need a loop, include asking the question in the loop. Just make it endless and use break to end it instead:

while True:
    accept1 = input("Do you accept?")
    if accept1.lower() in {"yes", "no", "n", "y"}:
        break        
    print ("That's not an answer you insolent brat!")

print ("Alright then! Let us begin!")

Upvotes: 5

Prune
Prune

Reputation: 77900

You have two different variables: "name" and "Name".

Also, your while loop has incorrect logic. Instead, think in terms of "loop until I get acceptable input". What you have will be an infinite loop on any of the expected inputs.

while accept1 not in ["Yes", "No", "no", "yes", "n", "y"]:
    print ("That's not an answer, you insolent brat!")
    accept1 = input("Do you accept?")

Upvotes: 1

Related Questions