更清晰地说明" =="和"是"在Python中

时间:2016-06-05 17:12:47

标签: python

这是一个用作算术计算器的小程序。我在这里读过以前的问题,但仍有疑问。在我的代码中,我使用了'是'而不是在我的while循环中==,但我的循环不会停止。这有点出乎意料,因为如果用户按下' n'那么变量ask将由新对象分配。当被要求输入时。如果有人可以查看代码并提供帮助,我将不胜感激。

def Add(x,y):
    add = x+y
    print("Answer:",add)

def Sub(x,y):
    sub = x-y
    print("Answer:",sub)

def Mult(x,y):
    product = float(x*y)
    print("Answer:",product)

def Div(x,y):
    if y!=0:
        div=float(x/y)
        print("Answer:",div)
    else:
        print("Invalid input!")


ask='y'
while(ask is 'y' or 'Y'):

    x=float(input("\nEnter x:"))
    y=float(input("Enter y:"))

    print("\nCALCULATOR:")
    print("\nPlease select any of the following options:")
    print("1.Add")
    print("2.Subtract")
    print("3.Multiplication")
    print("4.Division")
    opt=int(input("\nYour option:"))


    if(opt is 1):
        Add(x,y)

    elif(opt is 2):
        Sub(x,y)

    elif(opt is 3):
        Mult(x,y)

    elif(opt is 4):
        Div(x,y)

    else:
        print("Invalid option!")
    ask=input("\nDo you want to continue?(y/n or Y/N)")

2 个答案:

答案 0 :(得分:5)

is比较对象标识。但是有许多不同的字符串对象,其值为'y'。因此,如果您想比较值,请务必与==进行比较。

除了or是对两个表达式的布尔运算,而不是词法或。

所以条件必须是:

while ask == 'y' or ask == 'Y':
    ...

或更紧凑:

while ask in ['y', 'Y']:
    ...

或借助lower方法:

while ask.lower() == 'y':
    ...

答案 1 :(得分:1)

正如丹尼尔在他的出色回答中提到的那样,在Python中,它是为了身份,而不是平等。如果你不知道这意味着什么,我会提供一个简短的解释。

如果两个变量在内存中引用同一个对象,则比较

,而不是它们是否相等。例如

im_a_list = [1,2,3]
im_a_similar_list = [1,2,3]

现在,

im_a_list is im_a_similar_list

将是假的,而

im_a_list == im_a_similar_list

是真的。另一方面,如果你有

im_a_list = im_seriously_the_same_list = [1,2,3]

然后

im_a_list is im_seriously_the_same_list 

将评估为True