2014-11-02 50 views
2

我正在嘗試創建一個簡單的腳本,它會詢問用戶將輸入答案的問題(或者出現可選答案的提示?),程序會根據輸入輸出響應。(初學者Python)依賴用戶輸入創建if/else語句?

例如,如果我說

prompt1=input('Can I make this stupid thing work?') 

我會沿着我可能會對此錯誤的方式的

if prompt1='yes': 
    print('Hooray, I can!') 

else prompt1='No': 
    print('Well I did anyway!') 

elif prompt1=#an answer that wouldn't be yes or no 
    #repeat prompt1 

行的東西。請儘可能描述性,因爲這是我的學習練習。提前致謝!

+0

使用'=='比較相等性,並使用'else'語句。 – Christian 2014-11-02 03:14:06

回答

1

你很近。讀一個很好的教程:)

#!python3 
while True: 
    prompt1=input('Can I make this stupid thing work?').lower() 

    if prompt1 == 'yes': 
     print('Hooray, I can!') 
    elif prompt1 == 'no': 
     print('Well I did anyway!') 
    else: 
     print('Huh?') #an answer that wouldn't be yes or no 
  • while True將循環程序,直到永遠。
  • 使用==來測試是否相等。
  • 使用.lower()可以更容易地測試答案,無論大小寫。
  • if/elif/elif/.../else是測試的正確順序。

下面是一個Python版本2:

#!python2 
while True: 
    prompt1=raw_input('Can I make this stupid thing work?').lower() 

    if prompt1 == 'yes': 
     print 'Hooray, I can!' 
    elif prompt1 == 'no': 
     print 'Well I did anyway!' 
    else: 
     print 'Huh?' #an answer that wouldn't be yes or no 
  • raw_input代替input。 Python 2中的input將嘗試將輸入解釋爲Python代碼。
  • print是一個聲明,而不是一個函數。不要使用()
+0

我複製/粘貼到我的PyCharm中,當我嘗試輸入答案時出現此錯誤。 (是或否) – 2014-11-02 03:25:47

+0

回溯(最近呼叫最後一次): 文件「C:/ Users/Shawn/PycharmProjects/helloworld/Test Prograsm.py」,第3行,在 prompt1 = input('我可以讓這個愚蠢的')。lower() 文件「」,第1行,在 NameError:名稱'yes'未定義 – 2014-11-02 03:27:16

+1

您必須改爲使用Python 2.x。 'print()'是Python 3中的一個函數,所以我認爲你正在使用Python 3.在Python 2中使用'raw_input'。更新你的問題標籤以表明你的Python版本。 – 2014-11-02 03:29:17

1

另一個例子,這次是作爲一個函數。

def prompt1(): 
    answer = raw_input("Can I make this stupid thing work?").lower() 
    if answer == 'yes' or answer == 'y': 
     print "Hooray, I can!" 
    elif answer == 'no' or answer == 'n': 
     print "Well I did anyway!" 
    else: 
     print "You didn't pick yes or no, try again." 
     prompt1() 

prompt1()