def main():
sum=0.0
count=0
moredata="yes"
while moredata[0]=="y" or "Y":
x=eval(input("Enter a number >>"))
sum=sum+x
count=count+1
moredata=input("Do you have more numbers(yes or no)?")
print("\nThe average of the numbers is ",sum/count)
main()
第二个表达式中的布尔表达式,为什么会被while判读为永远为真,因为:
bool 类型仅仅是一个特殊的整数,可以通过计算表达式 True + True的值来测试一下
对于系列类型来说,一个空系列解释为假,任何一个非空系列解释为真
所以,while response[0] == "y" or "Y",加上括号好理解些
while (response[0] == "y" )or ("Y"),因为("Y")属于非空系列,所以会被bool判断永远为真,所以,只要有输入任何字符,while语句都会不断的去执行下去。
while response[0] == "y" or response[0]=="Y":
while response[0] == "y" or "Y"
思考上面两条代表码有何区别
第二个表达式“Y”, 它是一个非空的字符串,所以Python会永远把它解释为真
输出如下:
nter a number >>40
Do you have more numbers(yes or no)?Y
Enter a number >>90
Do you have more numbers(yes or no)?y
Enter a number >>90
Do you have more numbers(yes or no)?y
Enter a number >>88
Do you have more numbers(yes or no)?9
Enter a number >>0
Do you have more numbers(yes or no)?N
Enter a number >>0
Do you have more numbers(yes or no)?1
Enter a number >>0
Do you have more numbers(yes or no)?
所以你永远也求不到平均数,要注意布尔表达式的真假取值情况。
该博客讨论了一个Python代码片段,其中while循环的条件判断由于布尔表达式错误导致无限循环。问题在于`while response[0]==yorY`,因为空字符串`Y`总是被解释为真,使得循环无法正常结束。正确的写法应该是`while response[0]==y or response[0]==Y`。博客强调了理解布尔表达式和避免此类陷阱的重要性。

被折叠的 条评论
为什么被折叠?



