簡體   English   中英

Python-If語句與input()在def()函數內部不起作用

[英]Python - If Statement With input() Not Functioning Inside def() Function

除了def a()def b()都有代碼外,代碼中的所有內容都可以正常運行,並且如果我在運行代碼時檢查並input函數的語句,無論輸入內容如何,​​都會打印出'good for you' 例如,如果我在代碼中鍵入FalseWhatever ,這將導致不同的結果,則兩者均會導致響應'good for you' ,就好像輸入始終是'True''true' 我已經很久沒有編碼了,所以如果這很明顯,請原諒。

    tsil = ['input',]

while True:
  print('Write A Number (Print "done" When Finished)')
  num = input()
  tsil.append(num)
  print()
  if num == 'done':
    break

if True == True:
  print(tsil)

def a():
  print('you like short lists? (True or False)')
  ans = input()
  if ans == 'True' or 'true':
    return '\ngood for you'
  elif ans == 'False' or 'false':
    return '\nstop making short lists then'
  else:
    return '\nstop printing the wrong things loser'


def b():
  print('you like long lists? (True or False)')
  ans = input()
  if ans == 'True' or 'true':
    return '\ngood for you'
  elif ans == 'False' or 'false':
    return '\nstop making short lists then'
  else:
    return '\nstop printing the wrong things loser'

if len(tsil) < 10:
  print('^ short list large gorge')
  print()
  print(a())
else:
  print('^ big boy list')
  print()
  print(b())

您需要將if語句從if ans == 'True' or 'true':更改為if ans == 'True' or ans == 'true':

請參閱以下代碼:

def a():
  print('you like short lists? (True or False)')
  ans = input()
  if ans == 'True' or ans == 'true':   # if ans.lower() == 'true':
    return '\ngood for you'
  elif ans == 'False' or 'false':
    return '\nstop making short lists then'
  else:
    return '\nstop printing the wrong things loser'

推理

如果您檢查ans == 'True' or 'true將始終生成'True' ,這是OR條件下的第一個值。

bool('any value')始終為True

仔細看這行ans == 'True' or 'true'

這將始終返回True

你可以試試

print(bool('False' == 'True' or 'true'))
print(bool(-999 == 'True' or 'true'))
print(bool('Unicorn' == 'True' or 'true'))

看看它的真實價值。

要解決此問題,您可以將ans == 'True' or 'true'替換為

if ans in ['True', 'true']:

要么

if ans.lower() == 'true':

希望這可以幫助。

if ans == 'True' or 'true'

應該

if ans == 'True' or  ans == 'true'

與其他類似情況相同,因為if 'non-empty string'值為True

您的問題是函數中的條件如下:

ans == 'True' or 'true'

python解釋器將其視為:

(ans == 'True') or ('true')

在if語句中使用時,非空字符串的計算結果為true。

更改為此:

ans == 'True' or ans == 'true'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM