无法让次要的 if/else 问题起作用



我对编码是全新的,我正在努力了解一些基础知识,我认为我在下面的代码中犯了一个错误,对于第二个if/else语句(问你确定吗?(,无论输入如何,if语句都会一如既往地为真。

def age_calc():
target_year= input('What future year do you want to know your age?')
born_year = input ('what year were you born?')
target_year = int(target_year)
born_year = int(born_year)
age = target_year - born_year
print('In the year', target_year, 'you will be', age)
question=input('Do you want to know how old you be in a certain year?').lower()
if [question.startswith('y'), 'sure', 'ok',]:
age_calc()
else:
y_or_n =input('Are you sure?').lower()
if [y_or_n.startswith('y'), 'definitely', 'I am']:
print ('ok then')
else:
age_calc()

这有点令人沮丧,因为以前的版本运行良好:

if [question.startswith('y'), 'sure'.lower, 'ok'.lower]:
target_year= input('What future year do you want to know your age?')
born_year = input ('what year were you born?')
target_year = int(target_year)
born_year = int(born_year)
age = target_year - born_year
print('In the year', target_year, 'you will be', age)
else:
print('ok then')

这段代码中的if/else语句工作正常,所以我猜我在第一段代码中使用了错误的措辞。

[question.startswith('y'), 'sure', 'ok',]总是真的,因为非空列表是真的(https://docs.python.org/3/library/stdtypes.html#truth)。正因为如此,您的else部分永远无法到达。

你可能想要:

if question.startswith('y') or question in ('sure', 'ok'):

正如j1 lee所说,您评估的是错误的东西。在您的代码中,if语句只检查列表是否为空,这从来都不是您编写列表的方式

而且你在评估列表中的元素时也会感到困惑

以下是您可以使用的多种方法中的另一种:

#you can pack the affirmations in a list, above the code so you don't write it twice for both if/elses
affirmation_prefixes = ["y","ok", "sure"] # etc, you get the idea
#and then you use it like this
if any( [y_or_n.lower().startswith( x.lower() ) for x in affirmation_prefixes] ):

我的意思是,你可以用它做很多不同的方法,只需记住if [not, empty, list] is True,你实际上会在未来大量使用它来检查数据是否为空

最新更新