Python 在 while 循环中使用 break 语句时程序给出错误的输出

Python program gives wrong output when use break statement inside while loop

我在 while 循环中使用 break 语句退出 while 循环。但它给出了错误的输出。我不知道为什么会这样。这是我使用的代码:

def func():
    print "You have entered yes"
t='yes' or 'Y' or 'y' or 'Yes' or 'YES'
while True:
    r=raw_input("Enter any number:")
    if t=='r':
        func()
    else:
        break
print "Program End"   

更新:

当我输入 Yes 时,它应该给出:
您输入了 yes ,但控制转到 break陈述。为什么?

改变

if t=='r':

if t==r:

这是你想要的吗?

首先,您要检查 t 是否等于字符串文字 'r' 而不是变量 r,因此理论上您想要的是 if t==r

但是,这是行不通的。您要查找的是一个列表,如下所示:

def func():
    print "You have entered yes"
t= ['yes','Y','y','Yes','YES']
while True:
    r=raw_input("Enter any number:")
    if r in t:
        func()
    else:
        break
print "Program End" 

您不应在代码中使用 t = 'y' or 'Y' ...,因为当您使用 or 时,它会检查有效性。试试这个代码,我很确定它会起作用。

 def func():
     print "You have entered yes"
 t=('yes', 'Y', 'y', 'Yes', 'YES')
 while True:
     r=raw_input("Enter any number:")
     if r in t:
         func()
     else:
         break
 print "Program End"   

执行时 t=='r' 您正在将变量与 string r(仅这个确切的一个字符)进行比较,而不是 r 变量。