这是一个用作算术计算器的小程序。我在这里阅读了以前的问题,但仍有疑问。在我的代码中,我在我的 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)")
请您参考如下方法:
is 比较对象标识。但是有许多不同的字符串对象,它们具有值 'y'。因此,如果您想比较值,请始终使用 == 进行比较。
or 是对两个表达式的 bool 运算,而不是词法或。
所以条件必须是:
while ask == 'y' or ask == 'Y':
...
或更紧凑:
while ask in ['y', 'Y']:
...
或者在lower方法的帮助下:
while ask.lower() == 'y':
...
