Python中的"=="和"is"更清晰一些

Aam*_*han 1 python

这是一个小程序,可用作算术计算器.我在这里读过以前的问题,但仍有疑问.在我的代码中,我在while循环中使用了'is'而不是==,但我的循环并没有停止.这有点出乎意料,因为如果用户在被要求输入时按'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)")
Run Code Online (Sandbox Code Playgroud)

Dan*_*iel 5

is比较对象身份.但是有许多不同的字符串对象,它们具有价值'y'.因此,==如果您想比较值,请始终进行比较.

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

所以情况必须是:

while ask == 'y' or ask == 'Y':
    ...
Run Code Online (Sandbox Code Playgroud)

或更紧凑:

while ask in ['y', 'Y']:
    ...
Run Code Online (Sandbox Code Playgroud)

或借助lower方法:

while ask.lower() == 'y':
    ...
Run Code Online (Sandbox Code Playgroud)