Home > Enterprise >  Assigning value to variable when IF statement is false causes error in Python
Assigning value to variable when IF statement is false causes error in Python

Time:07-17

I'm writing a function in Python that should search a string for a substring, then assign the index of the substring to a variable. And if the substring isn't found, I'd like to assign -1 to the variable to be used as a stop code elsewhere. But I get an error that I don't understand. Here is a simplified version of the code:

test = "abc"
search_str = "z"
index_search_str = test.index(search_str) if search_str in test else index_search_str = -1

If I run this code, the value of index_search_str should be -1, but instead I get this error (using PyCharm):

 index_search_str = test.index(search_str) if search_str in test else index_search_str = -1
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

But if I change = -1 to := -1, it still gives an error. What am I missing?

CodePudding user response:

I think, in using ternary operator, value should be returned.

test = "azbc"
search_str = "z"
index_search_str = test.index(search_str) if search_str in test else -1

print(index_search_str)    # print value maybe  "1"

CodePudding user response:

You cannot assig variable in one-line statement

test = "abc"
search_str = "z"
index_search_str = test.index(search_str) if search_str in test else -1

CodePudding user response:

Try

index_search_str = test.index(search_str) if search_str in test else -1

CodePudding user response:

Your code have syntax errors.

I think you need something like this:

test = "abc"
search_str = "z"
if search_str in test:
    print("match")
    index_search_str = test.index(search_str)
    print(index_search_str)
else :
    print("not match")
    index_search_str = -1
    print(index_search_str)

not match

test = "abc"
search_str = "c"
if search_str in test:
    print("match")
    index_search_str = test.index(search_str)
    print(index_search_str)
else :
    print("not match")
    index_search_str = -1
    print(index_search_str)

match
2

  • Related