Keep receiving syntax errors in series of conditionals, beginner Python

I’m attempting to solve a palindromic puzzle with Python that requires me to have the following conditionals

  1. The number is 6 digits long
  2. The last 4 digits are palindromic
  3. One mile later last 5 digits are palindromic
  4. One mile later middle 4 digits are palindromic
  5. One mile later all 6 digits are palindromic If all these conditionals are fulfilled the puzzle is solved The full problem is found here if you need more context

I want to solve this problem using only a while loop, slicing, and if statements, I haven’t learned about def statements yet.

Right now I have:

winner = False
while x < 1000000 and winner: 
    if x_str = str(x) :
       x_str[2:6] == x[5:1:-1] 
    if x1_str = str(x+1) :
       x1_str[1:6] == x1[-1:0:-1]  
    if x2_str = str(x+2) :
       x2_str[1:5] == x2[-2:-6:-1] 
    if x3_str = str(x+3) : 
       x3_str[0:6] == x3[-1:-7:-1] 
    if winner(True):
       print ("Great! The answer is", x) 

But I get a syntax error on my first conditional. If I change the assignment operator to == instead, then I get undefined error for all my variables. I’m not sure what to do here? I’ve only been coding for two weeks so it might be a very simple error.

Thanks so much

A conditional must contain a condition (a value that is True or False, or can be converted to one of those). An assignment is no condition, so you get a syntax error.

You always need to assign a variable before you can use it. A variable that hasn’t been assigned doesn’t exist, that’s why you get an error saying it’s undefined.

I’m not sure why you’re trying to do an assignment in the if condition here, it looks the thing you put in the body of the conditional is what you actually want to be the condition. If you want to assign x_str and then compare its slices, do this:

    x_str = str(x)
    if x_str[2:6] == x_str[5:1:-1]:
        # Do what should happen if the condition is True

I’m seeing a few more issues here:

  1. The loop body will never be executed, because winner is False right from the start.
  2. x is undefined. I assume you want to check all possible x within a certain range, so you’ll either have to initialize it with a small value and increment it in the loop, or (much simpler) use a for loop with a range() expression.

Finally, if you use a for loop (and thus don’t have to increment anything in your code), you can just skip to the next number using a continue statement as soon as one of the checks fails. break (explained in the same section) might be useful to stop when you find a winning number.

1 Like