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

if statement with two conditions in Python(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 的元素列表,然后使用 in 运算符,检查 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 创建 sets语法 {}

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)