Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid syntax cause by += in ternany

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

like image 374
Leka Baper Avatar asked Oct 21 '18 00:10

Leka Baper


Video Answer


1 Answers

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)
like image 106
Willem Van Onsem Avatar answered Oct 17 '22 13:10

Willem Van Onsem