Why Do I Get A Syntax Error When Trying To Test For Correct User Input?
Solution 1:
There are three errors with
while accept1 = "Yes""No""no""yes""n""y":
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 1while accept1 = "Yes""No""no""yes""n""y": ^ SyntaxError: invalid syntax
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.while
creates an endless loop, since if the test is true, you never changeaccept1
in the loop and the condition will be forever true. Useif
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"}:
breakprint ("That's not an answer you insolent brat!")
print ("Alright then! Let us begin!")
Solution 2:
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 notin ["Yes", "No", "no", "yes", "n", "y"]:
print ("That's not an answer, you insolent brat!")
accept1 = input("Do you accept?")
Post a Comment for "Why Do I Get A Syntax Error When Trying To Test For Correct User Input?"