为什么此代码无效

时间:2015-04-24 22:43:30

标签: python

我想要做的是让用户输入一个名字,然后必须编程获取该名称并测试“if”语句

name = input("Enter name here: ")
if name is "Bill":
  print("Hello" + name)
else:
  print("Hello")

每当我输入Bill作为名称时,它就会立即说明程序结束而没有实际打印我的第二个命令。

2 个答案:

答案 0 :(得分:4)

尝试JavaVMOption *options = new JavaVMOption[1]; options[0].optionString = "-Djava.class.path=C:\\JavaCode;C:\\Lib\\sextante.jar;C:\\Lib\\sextante_gui.jar"; 而不是if name == "Bill":

我的理解是is比较身份而不是价值平等。

答案 1 :(得分:2)

这是一个可以帮助您理解Python identities的小例子:

>>> name='Bill'
>>> name1='Bill'
>>> if name is name1:
    print 'yes'            

yes                   #Prints "yes"

>>> id(name)       \
45197024            | #Because the ids are the same for both 'name' and 'name1'
>>> id(name1)       |
45197024           /

>>> name1=input()
Bill

>>> if name is name1:
    print 'yes'
                       #Does NOT print "yes"
>>> id(name)        \
45197024             | #Because the ids are NOT the same for both 'name' and 'name1'
>>> id(name1)        |
43847648            /

来自is运营商的文档:

  

运算符是和不是对象标识的测试:x是y是真的   当且仅当x和y是同一个对象时。

由于您的两个对象不相同,因此您的if语句不起作用。