如果使用正常的话,它可以正常工作
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中的+=
不起作用
因为这是一个if-then-else语句。它是一个ternary operator expression (or conditional expression),这是一个表达式。这是表达部分:
^{pr2}$var += ...
是不是一个表达式,它是语句。但这不是问题,我们可以写下:Python将其解释为:
所以这基本上就是你想要的。在
使用^{}
也就是说,我认为通过使用
.get(..)
,你可以让生活更轻松:这是一种更“自我解释”的方法,每次迭代都要在
vocab
dict中获得与char
相对应的值,如果找不到该键,则返回到char
。在我们甚至可以在这里使用
''.join(..)
:相关问题 更多 >
编程相关推荐