invalid syntax cause by += in ternany

  • A+
Category:Languages

it's working fine when using normal if else

vocab = {"a": "4", "i": "1", "u": "5", "e": "3", "o": "0"}  firstchar_name = input("Your name : ") # give fruit suggestion fruitfrom_name = input("First Character of your name is {}, write any fruit that started with {} : ".format(firstchar_name[0], firstchar_name[0])) favorite_number = input("Your favorite one-digit number : ") date_of_born = input("Input your born date (date-month-year) : ")  to_alay = ""  word = list(fruitfrom_name.lower()) for char in word:     to_alay += char if char not in vocab else to_alay += vocab[char]  print(to_alay) 

Error :

$ python3 telemakita_password.py           File "telemakita_password.py", line 12                                                       to_alay += char if char not in vocab else to_alay += vocab[char]                                                                              ^                                   SyntaxError: invalid syntax 

i wondering why += in if is working but not += in else

 


Because this is not an if-then-else statement. It is a ternary operator expression (or conditional expression), this is an expression. This is the expression part:

char if char not in vocab else vocab[char] 

var += ... is not an expression, it is statement. This is however not a problem, we can write:

to_alay += char if char not in vocab else vocab[char] 

Python interprets this as:

to_alay += (char if char not in vocab else vocab[char]) 

so this basically does what you want.

Using dict.get(..)

That being said, I think by using .get(..), you make life easier:

for char in word:     to_alay += vocab.get(char, char) 

This is more "self explaining", each iteration you aim to get the value that corresponds to char in the vocab dict, and if that key can not be found, you fallback to char.

We can even use ''.join(..) here:

to_alay = ''.join(vocab.get(char, char) for char in word) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: