[英]Python program gives wrong output when use break statement inside while loop
I am using break statement inside while loop to exit from while loop. 我在while循环中使用break语句从while循环退出。 But it gives wrong output. 但是它给出了错误的输出。 I don't know why this occurs. 我不知道为什么会这样。 Here is the code I have used: 这是我使用的代码:
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"
Update: 更新:
When I put Yes it should give : 当我说“ 是”时,它应该给出:
You have entered yes , but control goes to break statement. 您输入了yes ,但是控制进入了break语句。 Why? 为什么?
You should not use t = 'y' or 'Y' ...
in your code because when you use or
it checks the validity. 您不应在代码中使用t = 'y' or 'Y' ...
,因为当您使用or
它会检查有效性。 Try this code and I am pretty sure it will work. 试试这个代码,我很确定它会起作用。
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"
Change 更改
if t=='r':
to 至
if t==r:
Is that what you want? 那是你要的吗?
First, you're checking if t
is equal to the string literal 'r'
and not the variable r
, so in theory what you want is if t==r
首先,您要检查t
是否等于字符串文字'r'
而不是变量r
,因此从理论上讲, if t==r
需要的是
However, this won't work. 但是,这不起作用。 What you're looking for is a list, like the following: 您正在寻找的是一个列表,如下所示:
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变量进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.