簡體   English   中英

Python true / false和in

[英]Python true/false and in

如果有這樣的字母/單詞,我會嘗試打印true,如果沒有,則會打印為false,但是無論我鍵入什么內容,它始終都是真實的。

phr1= raw_input("Enter a phrase or paragraph, and this will check if you have those letters/word in ur paragraph: ")
print "You entered: "+phr1
phr2= raw_input("Check if a word/letter exists in the paragraph: ")
phr2 in phr1
if True:
    print "true"
elif False:
    print "false"
input("Press enter")

當我運行代碼時:

Enter a phrase or paragraph, and this will check if you have those letters/word in ur paragraph:
hello world
You entered: hello world
Check if a word/letter exists in the paragraph: g
true
Press enter

g怎么可能不存在,為什么會這樣呢?

檢查if True是否總是會通過,因為要評估的布爾表達式只是True 將整個if / else更改為僅print (phr2 in phr1)

如果第二個短語位於第一個短語中,則會打印“ True”,否則顯示“ False”。 為了使其小寫(無論出於何種原因),您可以使用.lower()如下面的注釋中所述。

如果您想使用原始的if / else檢查(優點是您可以對輸出消息進行更多的創意,而不僅僅是“ True” /“ False”),則必須修改如下代碼:

if phr2 in phr1:
    print "true"
else:
    print "false"
input("Press enter")
if <something>

表示其含義:如果<something>為true,它將執行代碼。 上一行代碼是完全無關的。

phr2 in phr1

這意味着“檢查phr2是否在phr1 ,然后完全忽略結果”(因為您不對其進行任何操作)。

if True:

這表示“如果True為true:”。

如果要測試phr2是否存在phr1 ,那么這就是您要讓Python執行的操作: if phr2 in phr1:

嘗試這個:

phr1= raw_input("Enter a phrase or paragraph, and this will check if you have those letters/word in ur paragraph: ")
print "You entered: "+phr1
phr2= raw_input("Check if a word/letter exists in the paragraph: ")
if phr2 in phr1:
    print "true"
else:
    print "false"
input("Press enter")
phr1 = raw_input("Enter a phrase or paragraph, and this will check if you have those letters/word in ur paragraph: ")
print "You entered: "+phr1
phr2 = raw_input("Check if a word/letter exists in the paragraph: ")
if phr2 in phr1:
    print "true"
else:
    print "false"
raw_input("Press enter")

暫無
暫無

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

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