如果在Python中的elif else语句
问题描述:
我正在写一些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,并提供了一个错误,而打印用户的选择。我尝试同样的代码:
- 用单引号
- 用双引号
- 没有报价
- ,最后我一些混合和/或没有工作报表,但实际上我不会如果可能的话,请参与和/或陈述。
如果代替字母让用户键入数字,代码将完美工作。我错过了什么,我不确定要告诉。
行!我删除了int和所有类型的普通输入和它的作品很好:你的用户输入转换成整数
a=int(input('Choose a product: '))
答
-
a=int(input('Choose a product: '))
然后:的
a=input('Choose a prodcut: ')
代替你正试图检查整数是否等于一个字符 -
if a=='A':
答
嗯,你将输入转换为int
,所以它显然不能是字母“A” - 所以你应该从那里删除int
。另外,还要注意在Python 2.x中,input
试图评估它接收的输入,你可能应该使用raw_input
代替:
a = raw_input('Choose a product: ')
答
这条线:
a=int(input('Choose a product: '))
存储一个整数,它会永远不会等于'A'或'B'。将其更改为
a=input('Choose a product: ')
答
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")
为什么你认为'a'会包含'int'以外的任何东西? –
@ignacio int输入只读取数字。如果我没有弄错,没有int的输入会读取数字和字母。 –