MC均值检验代码alpha输入循环异常问题咨询
问题分析与解决办法
嗨,我看到你遇到的问题了——这段代码的条件判断逻辑出了个小疏漏,导致哪怕输入合法的0.05或0.10,程序还是会陷入循环,咱们来快速修复它。
错误根源
你写的条件判断:
if alpha!=0.05 or alpha!=0.10:
这个逻辑永远为真!因为不管alpha是0.05还是0.10,总有一个不等式成立:
- 当输入0.05时,
alpha!=0.10为True,整个or表达式结果就是True - 当输入0.10时,
alpha!=0.05为True,同样触发or的条件
正确的逻辑应该是:当alpha既不是0.05也不是0.10时,才进入循环提示重新输入,所以需要把or改成and。
修正后的代码
alpha = float(input('For the MC Test for the mean define alpha (0.10 and 0.05 only available at the moment): ')) if alpha != 0.05 and alpha != 0.10: while True: print('Please insert a value equal to 0.05 or 0.10') alpha = float(input('For the MC Test for the mean define alpha (0.10 and 0.05 only available at the moment): ')) # 新增退出循环的条件,避免无限循环 if alpha == 0.05 or alpha == 0.10: break else: print('MC test will control the FWER at exactly {}% (balanced test)'.format(alpha * 100))
额外优化小建议
- 把重复的提示语提取成变量,减少代码冗余:
prompt = 'For the MC Test for the mean define alpha (0.10 and 0.05 only available at the moment): ' alpha = float(input(prompt)) if alpha != 0.05 and alpha != 0.10: while True: print('Please insert a value equal to 0.05 or 0.10') alpha = float(input(prompt)) if alpha in (0.05, 0.10): break print('MC test will control the FWER at exactly {}% (balanced test)'.format(alpha * 100))
- 输出百分比的时候把
alpha乘以100,这样显示的是5%或10%,比0.05/0.10更直观。
内容的提问来源于stack exchange,提问作者Al Ejandro
相关产品推荐
相关产品推荐

