Skip to main content
 首页 » 编程设计

python之Python 中有两个条件的 if 语句

2025年05月04日15jillzhang

我正在编写一个简单的控制台程序来帮助我自己和一些地质学同学进行岩石样本分析。我们的讲师为我们提供了一个流程图,有助于指定样本的特征。我正试图将它变成一个控制台程序。

我的问题是第 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' 

提前致谢:-)

请您参考如下方法:

您可以构建 if 条件应评估为 Truthy 的元素列表,然后像这样使用 in 运算符来检查 choice1 的值在那个元素列表中,像这样

if choice1 in ['1', 'Coherent']: 
... 
elif choice1 in ['2', 'Clastic']: 
... 

除了列表,你也可以使用元组

if choice1 in ('1', 'Coherent'): 
... 
elif choice1 in ('2', 'Clastic'): 
... 

如果要检查的项目列表很大,那么你可以这样构造一个集合

if choice1 in {'1', 'Coherent'}: 
... 
elif choice1 in {'2', 'Clastic'}: 
... 

set 提供比列表或元组更快的查找。您可以使用 set literal syntax {} 创建 set