Python If ... Else

Copyright, without permission, is prohibited reprint


chapter


If Python conditions and statements

Python supports common mathematical logic conditions:

  • equal: a == b
  • not equal to: a != b
  • Less than: a < b
  • Or less: a <= b
  • more than the: a > b
  • greater or equal to: a >= b

These conditions can be used in a variety of statements, the most common is to use the "if statement" and the loop statement.

Examples

If the statement

a = 99
b = 100
if b > a:
  print("b 大于 a")

indentation

Python dependent indentation (spaces) to define the scope of the code. Other programming languages ​​commonly used braces.

Examples

If the statement is not indented cause errors:

a = 99
b = 100
if b > a:
print("b 大于 a") # 此处会报错

elif

In python, elifkeyword, he said: "If the preceding conditions are not met, then try this condition" means.

Examples

a = 99
b = 99
if b > a:
  print("b 大于 a")
elif a == b:
  print("a, b相等") 

In this example, a equals b, so the first condition is not met, then the elifcondition is true, is printed to the screen: a, equal b.

else

In python, elsekeyword, he said: "If the preceding conditions are not true, then ...."

Examples

a = 100
b = 99
if b > a:
  print("b 大于 a")
elif a == b:
  print("a, b相等")
else:
  print("a 大于 b")

In this example, a ratio b large, so the first condition is not met, elifthe conditions are not established, so go to elseprint to the screen is: a is greater than b.

No elifof elseit is possible:

Examples

a = 100
b = 99
if b > a:
  print("b 大于 a")
else:
  print("b 不大于 a")

Compact if statement

If only one statement if the latter statement to be executed, you can put it in one line with the If statement.

Examples

Line if statement:

if a > b: print("a is greater than b")

Compact if ... else statement

The same, if ... else behind if only one statement to be executed, you can put them with conditional statements on the same line.

Examples

One line if else statements:

print("A") if a > b else print("B")

Else you can put multiple statements on the same line:

Examples

One line if else statements, there are three conditions:

print("A") if a > b else print("=") if a == b else print("B")

and

and/ With the keyword is a logical operator, for combining conditional statements:

Examples

Test a is greater than b, c is greater than a:

if a > b and c > a:
  print("两个条件都成立")

or

or/ Or keyword is a logical operator, for combining conditional statements:

Examples

Whether a test than b, that is greater than a or c:

if a > b or a > c:
  print("至少有一个条件成立")

Guess you like

Origin blog.csdn.net/weixin_43031412/article/details/93460748