我刚开始学习Python。所以我仍然非常困惑条件,如果和其他。特别是,现在赋值要求布尔字符串。我尝试了多种方法,但我只能使用一个代码。此外,如果有多种情况,有多种(超过两种)可能性。我们是否仍然使用诸如outcome = ['a','b','c']之类的字符串来首先定义变量?
subject_age = ['old','young']
change_analysis = True
if subj_age == 'old':
print_analysis = True
else:
print_analysis = False
当主题是“旧”时,代码完美无缺。但是,当我测试主题是'年轻'时,代码仍然不起作用。
# Change subj_age
subj_age = 'young'
# Re-run code and make sure the conditional still works
%run -i ./A1Code/q7_code.py
assert not change_analysis
assert isinstance(change_analysis, bool)
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
~/Downloads/A1Code/q7_code.py in <module>()
6 # Re-run code and make sure the conditional still works
7 get_ipython().run_line_magic('run', '-i ./A1Code/q7_code.py')
----> 8 assert not change_analysis
9 assert isinstance(change_analysis, bool)
AssertionError:
我一直得到断言错误
您的if-statment目前检查值'old'
是否等于您的数组['old', 'young']
(显然它不相同)
要检查数组中是否包含主题,请使用in
if 'old' in subj_age:
#stuff
逆运算符:
if 'old' not in subj_age:
#stuff