if statement with two conditions in Python(Python中带有两个条件的if语句)
问题描述
我正在编写一个简单的控制台程序来帮助自己和一些地质学同学进行岩石样本分析.我们的讲师为我们提供了一个流程图,帮助我们确定样本的特征.我正试图把它变成一个控制台程序.
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语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python中带有两个条件的if语句


基础教程推荐
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01