0

I was just playing around testing if strings were immutable because I was a bit tired :D and made this

def x(string = "a", y = 0):
    if y == 5:
        return
    else:
        string += "x"
        print(string)
        x(string, y = y + 1)
        print(string)
x()

and I am simply wondering why this works but

def x(string = "a", y = 0):
    if y == 5:
        return
    else:
        string += "x"
        print(string)
        x(string, y += 1)
        print(string)
x()

Does not work (The difference in the y variable assignment in the recursive call). Why is it a syntax error, theyre simply doing the same thing?

3
  • syntax error means python cannot accept this input in its grammar. Commented Feb 19, 2017 at 8:50
  • That's a lot of code to produce a syntax error. Try to produce the same error with as little code as possible, forget about recursion and strings. Commented Feb 19, 2017 at 9:15
  • Try printing y after the recursive call to x() and you will find it hasn't changed. You are using the keyword arg y not assignment to y in your x() function call. Commented Feb 19, 2017 at 9:34

1 Answer 1

2

In the first version, you tell the function that your parameter y takes the value of your variable y, +1. If your parameter was called z, you'd have x(string, z=y+1).

As you see, y+=1 doesn't work, there you're attempting to modify your variable, not to give the function a named parameter. But += doesn't return anything, so the syntax is indeed incorrect.

Sign up to request clarification or add additional context in comments.

2 Comments

but y = y + 1 doesn't return anything either
y in this case is a parameter name, like my_param=y+1, it's not an assignment but passing a named parameter to a function ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.