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


我在 while 循环

中使用中断语句退出 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"   

更新:

当我输入时,它应该给出:
您已输入 是 ,但控制进入中断语句。为什么?

你不应该在代码中使用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"   

更改

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=='r'您正在将变量与字符串 R(仅此确切一个字符(进行比较,而不是与 R 变量进行比较。

最新更新