2016-12-03 256 views
0

我正在寫一些python,其中用戶從可用產品的列表中讀取幾個選項,並在輸入字段中輸入希望購買的產品的字母。代碼的一部分,我希望有如下不起作用:如果在Python中的elif else語句

a=int(input('Choose a product: ')) 
if a=='A': 
    print('Product A have been chosen') 
elif a=='B': 
    print('Product B have been chosen') 
else: 
    print('Print something else') 

的問題是程序不識別字母A,並提供了一個錯誤,而打印用戶的選擇。我嘗試同樣的代碼:

  1. 用單引號
  2. 用雙引號
  3. 沒有報價
  4. ,最後我一些混合和/或沒有工作報表,但實際上我不會如果可能的話,請參與和/或陳述。

如果代替字母讓用戶鍵入數字,代碼將完美工作。我錯過了什麼,我不確定要告訴。

行!我刪除了int和所有類型的普通輸入和它的作品很好:你的用戶輸入轉換成整數

a=int(input('Choose a product: ')) 
+2

爲什麼你認爲'a'會包含'int'以外的任何東西? –

+0

@ignacio int輸入只讀取數字。如果我沒有弄錯,沒有int的輸入會讀取數字和字母。 –

回答

0

-

a=int(input('Choose a product: ')) 

然後:的

a=input('Choose a prodcut: ') 

代替你正試圖檢查整數是否等於一個字符 -

if a=='A': 
0

嗯,你將輸入轉換爲int,所以它顯然不能是字母「A」 - 所以你應該從那裏刪除int。另外,還要注意在Python 2.x中,input試圖評估它接收的輸入,你可能應該使用raw_input代替:

a = raw_input('Choose a product: ') 
0

這條線:

a=int(input('Choose a product: ')) 

存儲一個整數,它會永遠不會等於'A'或'B'。將其更改爲

a=input('Choose a product: ') 
0

a=int(input("Please Enter a value")) 這意味着你要a舉行的integer和你的輸入轉換爲integer這就是爲什麼

a=int(input(1)) //this works 
a=int(input(2.45))//this will work will only return 2 

a=int(input("a"))//will give you an error since a can not be converted to a number 
//The values inside brackets are just to demonstrate an example of what you may enter as input` 

爲了使這項工作字符和字符串只是使

a=input("please enter value")