我正在编写一个简单的控制台程序来帮助自己和一些地质学同学进行岩石样本分析.我们的讲师为我们提供了一个流程图,帮助我们确定样本的特征.我正试图把它变成一个控制台程序.
I am writing a simple console program to help myself and some fellow geology students with rock sample analysis. Our lecturer provided us with a flow chart that helps to specify the characteristics of the sample. I am attempting to make this into a console program.
我的问题是第 9 行的 if 语句是否可以采用两个条件,如果可以,我是否写对了?
My question is whether it is possible for the if statement on line 9 to take two conditions and if so have I written it correctly?
def igneous_rock(self):
print "Welcome to IgneousFlowChart"
print "Assuming you are looking at an igneous rock, please choose the "
print "option which best describes the sample:"
print "1. Coherent 2. Clastic"
choice1 = raw_input("> ")
if choice1 = '1', 'Coherent': # this is the line in question!
return 'coherent'
elif choice1 = '2', 'Clastic':
return 'clastic'
else:
print "That is not an option, sorry."
return 'igneous_rock'
提前致谢:-)
您可以构造 if
条件应评估为 Truthy 的元素列表,然后使用 in像这样的 code> 运算符,检查
choice1
的值是否在该元素列表中,像这样
You can construct the list of elements for which the if
condition should evaluate to Truthy, and then use in
operator like this, to check if choice1
's value is in that list of elements, like this
if choice1 in ['1', 'Coherent']:
...
elif choice1 in ['2', 'Clastic']:
...
除了列表,你也可以使用元组
Instead of lists, you can use tuples as well
if choice1 in ('1', 'Coherent'):
...
elif choice1 in ('2', 'Clastic'):
...
如果要检查的项目列表很大,那么你可以像这样构造一个集合
If the list of items to be checked is huge, then you can construct a set like this
if choice1 in {'1', 'Coherent'}:
...
elif choice1 in {'2', 'Clastic'}:
...
set
提供比列表或元组更快的查找.您可以使用 set literal 创建 set
s语法 {}
set
s offer faster lookup than lists or tuples. You can create set
s with set literal syntax {}
这篇关于Python中带有两个条件的if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!