无效语法由+ =引起

时间:2018-10-21 00:04:19

标签: python python-3.x

如果不使用普通按钮,则可以正常工作

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)

错误:

$ 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

我想知道为什么if中的+=起作用,而其他情况中的+=却不起作用

1 个答案:

答案 0 :(得分:5)

因为这不是if-then-else语句,所以不是。它是ternary operator expression (or conditional expression),这是一个表达式。这是表达部分:

char if char not in vocab else vocab[char]

var += ...不是表达式,它是 statement 。但是,这不是问题,我们可以编写:

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

Python将此解释为:

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

所以这基本上可以满足您的要求。

使用dict.get(..)

话虽如此,我认为通过使用.get(..),您可以使生活更轻松:

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

这是更多的“自我解释”,您希望在每次迭代中获得与char字典中的vocab对应的值,如果找不到该密钥,您将退回到{{ 1}}。

我们甚至可以在这里使用char

''.join(..)