MDN’s new design is in Beta! A sneak peek:




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))
    print("Unknown operator")



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

if [condition]:
    [do something]




>>> 5 == 5
>>> 5 == 4
>>> 5 == 'hello'
>>> 'hello' == 'hello'
  • 在第一例中,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.



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")
    print("Come back when you're older!")


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