Home > OS >  How would I fix the "Invalid syntax" error?
How would I fix the "Invalid syntax" error?

Time:08-05

I'm trying to create a script that when you type in something, it adds it to a table then prints the table. Then, it asks if you want to continue adding something to the table. If you say "yes", then the function starts again. If you don't say yes, nothing happends. Why isn't this working? (sorry it's probably a noob mistake)

List = []
def e():
    print("Say something")
    colorList.append(input())
    print(colorList)
    print("Continue?")
    input()
    answer = input()
    if answer = "yes": 
        e()
  

e()

CodePudding user response:

There are a couple mistakes in your code.

1st: you append the input to colorList, but you define your list as List

2nd: you have answer = input(), but call input() again up top. It's not necessary to call it twice (only use answer = input() so you can save it)

3rd: when checking if the answer is equal to yes, use == instead of =, = is the assignment operator

Some other things could be added like making the input lowercase so "Yes" would work, and printing out code in the input instead of using print and input

Here is the working code:

colorList = []
def e():
    colorList.append(input("Say something\n"))
    print(colorList)
    answer = input("Continue?\n")
    if answer == "yes": 
        e()
  

e()

Use answer = input("Continue?\n").lower() to make it not case sensitive

CodePudding user response:

You're supposed to use == not = to compare values, your mistake is on line 9.

CodePudding user response:

When I run this in Mu, I get the following error:

  File "c:\...\color_list.py", line 9
    if answer = "yes":
              ^
SyntaxError: invalid syntax
>>> 

Notice there is much more here than just "invalid syntax" as you claimed. Be sure that you read and understand the entire error message. For example, this tells you the exact line of code that is causing the problem. That is the place to start. And as someone else already answers, you need to replace = with == to fix the error.

  • Related