无效语法,原因是+=在内部

2024-10-01 09:17:44 发布

您现在位置:Python中文网/ 问答频道 /正文

如果使用正常的话,它可以正常工作

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)

错误:

^{pr2}$

我想知道为什么if中的+=有效,而else中的+=不起作用


Tags: oftonamenumberinputyourdatefavorite
1条回答
网友
1楼 · 发布于 2024-10-01 09:17:44

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

char if char not in vocab else vocab[char]

var += ...不是一个表达式,它是语句。但这不是问题,我们可以写下:

^{pr2}$

Python将其解释为:

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

所以这基本上就是你想要的。在

使用^{}

也就是说,我认为通过使用.get(..),你可以让生活更轻松:

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

这是一种更“自我解释”的方法,每次迭代都要在vocabdict中获得与char相对应的值,如果找不到该键,则返回到char。在

我们甚至可以在这里使用''.join(..)

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

相关问题 更多 >