2016-12-03 255 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")