带有 if/elif 语句的多个条件 [英] Multiple conditions with if/elif statements

查看:31
本文介绍了带有 if/elif 语句的多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让一个 if 语句从多个条件触发,而无需使用不同的触发器多次重写该语句.例如:

I'm trying to get an if statement to trigger from more than one condition without rewriting the statement multiple times with different triggers. e.g.:

if user_input == "look":  
    print description


if user_input == "look around":
    print description

你会如何将这些浓缩成一个语句?

How would you condense those into one statement?

我尝试过使用or",它导致任何 raw_input 触发语句,无论输入是否匹配任一条件.

I've tried using 'or' and it caused any raw_input at all to trigger the statement regardless of whether the input matched either of the conditions.

if user_input == "look" or "look around":  
    print description

推荐答案

你想做的是

if user_input == "look" or user_input == "look around":
    print description

如果你有很多可能性,另一个选择:

Another option if you have a lot of possibilities:

if user_input in ("look", "look around"):
    print description

由于您使用的是 2.7,因此您也可以这样编写(适用于 2.7 或 3+,但不适用于 2.6 或更低版本):

Since you're using 2.7, you could also write it like this (which works in 2.7 or 3+, but not in 2.6 or below):

if user_input in {"look", "look around"}:
    print description

它使您的元素set, 搜索速度稍微快一些(尽管这仅在您检查的元素数量远大于 2 时才重要).

which makes a set of your elements, which is very slightly faster to search over (though that only matters if the number of elements you're checking is much larger than 2).

您的第一次尝试总是通过的原因是这样的.Python 中的大多数事物的计算结果为 True(除了 FalseNone 或空字符串、列表、字典等).or 接受两件事并将它们评估为布尔值.所以 user_input == "look" or "look around" 被当作 (user_input == "look") or "look_around";如果第一个是假的,就像你写了if "look_around":,它会一直通过.

The reason your first attempt always went through is this. Most things in Python evaluate to True (other than False, None, or empty strings, lists, dicts, ...). or takes two things and evaluates them as booleans. So user_input == "look" or "look around" is treated like (user_input == "look") or "look_around"; if the first one is false, it's like you wrote if "look_around":, which will always go through.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆