Python中具有两个条件的if语句

Python中具有两个条件的if语句

本文介绍了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的元素列表,然后在这样的$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']:
...

也可以使用元组

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 提供的搜索速度比列表快或元组。您可以使用

sets offer faster lookup than lists or tuples. You can create sets with set literal syntax {}

这篇关于Python中具有两个条件的if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 21:21