我是編碼的新手,我正在嘗試了解一些基礎知識,我想我在下面的代碼中犯了一個錯誤,對于第二個 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 陳述句作業正常,所以我猜我在第一個代碼中使用了錯誤的措辭。
uj5u.com熱心網友回復:
[question.startswith('y'), 'sure', 'ok',]始終為真,因為非空串列為真(https://docs.python.org/3/library/stdtypes.html#truth)。正因為如此,你的else部分永遠不會到達。
你可能想要:
if question.startswith('y') or question in ('sure', 'ok'):
uj5u.com熱心網友回復:
正如 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,你實際上將來會經常使用它來檢查資料是否為空
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/364845.html
