在下面的代码中,if循环不采用条件(为true),而是转到elif语句。我正在尝试使用if语句来控制可以进入列表的内容和不能进入的内容:average = []def judge(result): try: float(result) return True except ValueError: return 'please type number'list_in = input('Type in your number,type y when finished.\n')judge_result = judge(list_in)if judge_result: aver_trac = aver_trac + 1 average.append(list_in) print('success')elif isinstance(judge_result, str): print(judge_result)但是,如果我指定if judge_result == True:那么这个if循环将起作用
1 回答

慕盖茨4494581
TA贡献1850条经验 获得超11个赞
Python将非空字符串评估为True,将空字符串评估为False。
在您的情况下,该judge函数返回True,或者返回非空字符串,该字符串也为True;当您评估收益时,if judge_result:始终为True。
有效的事实if judge_result == True:是python==和ispython之间的区别的一个很好的例子
综上所述,您处理数据输入的方式有点尴尬;您可以改为执行以下操作:
average = []
while True:
list_in = input('Type in your number,type y when finished.\n')
if list_in == 'y':
break
try:
average.append(float(list_in))
except ValueError:
print('please type number')
添加回答
举报
0/150
提交
取消