2016-02-13 38 views
2

我一直在學習python代碼,我想出了一個好主意的程序。依據是以下幾點:你如何使連續的if語句?

if input() == 'unnamed variable': 
    print('this') 
if input() == 'another unnamed variable' 
    print('this other response') 

我如果不首先滿足第一if語句輸入另一不願透露姓名的變量

我希望我的程序打印一些不同的用戶讀取基於輸入

如何使用連續的if語句?我試過elif和其他。我能夠說80如果聲明背靠背嗎?

任何幫助,將不勝感激,提前

+0

這取決於你想要做什麼,但你可以使用一個循環,並把你的條件語句'continue'語句。 –

回答

2

謝謝如果你想要做的根據用戶輸入不同的東西,那麼首先,你應該只要求用戶輸入一次的事情。所以,你應該只調用input()一次,並保存到一個變量的響應:

response = input() 

然後,您可以使用ifelifelse檢查多個不同的條件,每次做不同的事情:

if response == 'some input': 
    print('User entered some input') 
elif response == 'some other input': 
    print('User entered some input') 
elif response == 'some even more different input': 
    print('User entered some even more different input') 
else: 
    print('User entered something I do not recognize') 

因此,您只需要詢問用戶一次並存儲響應,然後將響應與多個不同值進行比較:如果其中一個條件爲真,則會執行該部分,並跳過其餘的條件檢查。

+0

感謝,更聰明的寫作方式,它符合我的目的。謝謝你的提示。我正在查找如何繼續代碼,而不是在打印後結束 – dayTOpython

0

可以更換嵌套如果-elif - elif的,否則由 '或'

if cond1 or cond2 or cond3 

可以代替嵌套的if-IF-如果 '和'

if cond1 and cond2 and cond3 

它可以幫助你在重新設計大型if-else鏈條時

0

您可以定義輸入,然後檢查相等性。

userInput = input(" > ") 
aNumber = 5 
if userInput == 'y' or userInput == 'yes': 
    print("You said yes!") 
elif userInput == 'no': 
    print("You said no.") 
elif userInput == 'maybe' and aNumber == 5: 
    print("you said maybe, and aNumber is equal to 5!") 
else: 
    print("I can't understand you.")