Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

条件语句

这篇翻译不完整。请帮忙从英语翻译这篇文章

如果程序是个直肠子,仅仅从头到尾地运行,那么它并不能实现太多功能。因此,代码中有一种结构(叫做条件语句)可以用于选择不同的道路。让我们拿起简单计算器,改一改它,让用户能够选择使用的运算符。

a = input("Write the first number: ")
b = input("Write the second number: ")
op = input("Choose the operator (+, -, *, /) ")
if op == '+':
    sum = int(a) + int(b)
    print("Their sum is " + str(sum))
elif op == '-':
    sub = int(a) - int(b)
    print("Their subtraction is " + str(sub))
elif op == '*':
    prod = int(a) * int(b)
    print("Their product is " + str(prod))
elif op == '/':
    quot = int(a) / int(b)
    print("Their quotient is " + str(quot))
else:
    print("Unknown operator")

又是很多代码。让我们精简一下它们。

首先,我们要求用户输入两个运算数和一个运算符,这我们都知道。

然后,我们开始评估各种的可能性,并采取相应的措施。if 关键词引入了一个条件语句,即一段仅当某些条件(或多个条件,我们后面会看到)为真时才得到执行的代码。条件语句的一般结构是:

if [condition]:
    [do something]

condition是任何能被判断为True或False的东西。通常来说,它是一个比较。所以让我们看看比较是如何工作的。

比较

有许多我们能用于比较的运算符。举相等运算符(==)为例,在交互模式中启动解释器,让我们做一些测试。

>>> 5 == 5
True
>>> 5 == 4
False
>>> 5 == 'hello'
False
>>> 'hello' == 'hello'
True
  • 在第一例中,5确实是等于5,所以解释器告诉我们比较为真。
  • 在第二例中,4显然不等于5,所以解释器返回False。
  • 一个数组当然不同于一个字符串,所以结果为False。
  • Finally, two strings containing the exact same characters, and only those characters, are practically the same string, so the comparison yields True.

下面是在Python中可用的比较运算符列表。

==

Operand on the left equals operand on the right

!= Operand on the left does not equal operand on the right
> Operand on the left is greater than operand on the right
>= Operand on the left is greater or equal operand on the right
< Operand on the left is lesser than operand on the right
<=

Operand on the left is lesser or equal operand on the right

回到计算器

现在我们可以回到 if 语句的一般形式了。

if [condition]:
    [do something]

We already explained what the condition part is, so let's go on. After the condition, we put a colon and we go to a newline. At the beginning of the next line we put a certain number of spaces (4, by convention). From there on, everything that is indented by the same number of spaces will be executed if and only if the condition yielded True, up to a line with a lesser number of leading spaces. Let's use a simpler example to clarify.

if 5 == 5:
    print("5 equals 5")
    print("But we already knew it")
print("You learned something today :)")

As silly as it is, this example shows us that the first two prints would have been executed only if the condition (5 == 5) yield True, while the last print would have been executed anyway. Let's see the counter-example.

if 5 != 5:
    print("5 equals 5")
    print("So you won't see these lines")
print("I'll be printed anyway :)")

Only the last line will be printed this time because it's not part of the if statement.

So, back to our simple calculator, if when asked the operator, the user put '+' the condition of the if statement would have been true and the following two lines (the one doing the addition and the one printing the result) would have been executed. Otherwise, they would have been ignored.

Since in this particular case the choices are mutually exclusive (the user couldn't have input both '+' and '-'), we could just get away with a series of ifs. But that wouldn't allow us to consider the alternative where the user didn't chose any of the supported operators. To achieve this, Python provides two statements: elif and else.

elif is used when the condition from the previous if wasn't met but we want to provide another condition. That is, we're not simply saying 'otherwise', we are providing an alternative but with some other constraint. The form of an elif statement is the same as the one for the if statement. The only difference is that it has to be proceeded by an if block (that is, an if statement followed by the indented part).

On the other end, else tells the interpreter "if none of the previous conditions were met, just do this". Because it's the last resort, it must me placed at the end of a conditions chain (that is, it can't be followed by another elif or another else). Also, notice that else can be used after an if, without there being elifs, like in this (useless) program that checks if you are over 18:

age = input("How old are you? ")
if int(age) > 18:
    print("Ok, you can enter")
else:
    print("Come back when you're older!")

文档标签和贡献者

 此页面的贡献者: wth
 最后编辑者: wth,