Lan*_*ame 1 python syntax if-statement conditional-statements
我正在编写一个简单的控制台程序来帮助自己和一些地质学家进行岩石样本分析.我们的讲师为我们提供了一个有助于指定样品特征的流程图.我试图把它变成一个控制台程序.
我的问题是第9行的if语句是否有可能采取两个条件,如果是这样,我是否正确写了?
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'
Run Code Online (Sandbox Code Playgroud)
提前致谢 :-)
您可以构造if条件应该评估为Truthy 的元素列表,然后使用这样的in运算符来检查choice1元素列表中是否有值,如下所示
if choice1 in ['1', 'Coherent']:
...
elif choice1 in ['2', 'Clastic']:
...
Run Code Online (Sandbox Code Playgroud)
您也可以使用元组而不是列表
if choice1 in ('1', 'Coherent'):
...
elif choice1 in ('2', 'Clastic'):
...
Run Code Online (Sandbox Code Playgroud)
如果要检查的项目列表很大,那么您可以构建一个这样的集合
if choice1 in {'1', 'Coherent'}:
...
elif choice1 in {'2', 'Clastic'}:
...
Run Code Online (Sandbox Code Playgroud)
set提供比列表或元组更快的查找.您可以set使用set literal语法创建s{}
| 归档时间: |
|
| 查看次数: |
3147 次 |
| 最近记录: |