2014-09-28 214 views
-1

好的,所以我剛開始學習python,我有一個任務是要求我創建一個測驗。我已經想出瞭如何區分大小寫,但我在用戶輸入的答案中遇到了問題。當我嘗試運行程序來驗證它是正確的答案時,它只是告訴我輸入的答案沒有被定義。Python:如何將用戶輸入與不區分大小寫的答案進行匹配?

這裏是我當前的代碼示例(不要判斷愚蠢的問題,我有一個大作家塊:P):

q1= "1. What is the name of the organelle found in a plant cell that produces chlorophyll?" 
plantcell=input(q1) 
ans1= "chloroplast" 
if plantcell.lower()==ans1.lower(): 
    print("Correct!") 
else: 
    print("Incorrect!") 

我使用python 3和榮IDE 101.任何建議?

+0

請發佈確切的錯誤 – User 2014-09-28 03:24:54

+0

請更好地解釋你的問題你確實要做什麼,錯誤究竟是什麼(如果你遇到異常,將異常追溯粘貼到你的問題中,不要只描述它)。當我在Python 3.4中運行這個代碼時,它確實聽起來像你想要的。 – abarnert 2014-09-28 03:24:55

+0

請修改您的帖子以包含完整的回溯 – inspectorG4dget 2014-09-28 03:24:56

回答

1

我敢打賭,你真正的問題是,你不使用Python 3

例如,也許你是在Mac上,你沒有意識到,你已經有 Python 2.7安裝。所以你安裝了Python 3.4,然後安裝了一個IDE,並且假設它必須使用3.4,因爲這就是所有這些,但實際上它默認爲2.7。驗證此

一種方式是import sysprint sys.version

在Python 2.7,input是Python 3的eval(input(…))等效。因此,如果用戶鍵入chloroplast,Python是要嘗試評估chloroplast作爲一個Python表達式,這將提高NameError: 'chloroplast' is not defined

解決的辦法是找出你配置你的IDE默認的Python版本,並將其配置爲Python 3

0

我也認爲這個問題是你不小心使用Python 2.一種方法讓你在Python的兩個版本代碼的運行將是要麼使用類似plantcell = str(input(q1))甚至更​​好(更安全)使用raw_input(相當於到Python 3的input下面是一個例子:

import sys 

q1 = "1. What is the name of the organelle found in a plant cell that produces chlorophyll?" 

if sys.version_info[0] == 3: 
    plantcell = input(q1) 
else: 
    plantcell = raw_input(q1) 

ans1 = "chloroplast" 
if plantcell.lower() == ans1.lower(): 
    print("Correct!") 
else: 
    print("Incorrect!") 
相關問題