Python 如果...否则
Python 如果...否则
Python 条件和 If 语句
Python 支持数学中的通常逻辑条件:
- 等于: a == b
- 不等于: a != b
- 小于:a < b
- 小于或等于:a <= b
- 大于:a > b
- 大于或等于: a >= b
这些条件可以以多种方式使用,最常见的是在“if语句”和循环中。
“if 语句”是通过使用if 关键字编写的。
示例
如果语句:
a = 33
b = 200
if b > a:
print("b is greater than a")
在这个例子中我们使用了两个变量,a 和 b, 它们被用作if语句的一部分来测试 b是否大于 a。 由于 a是 33,而 b是 200, 我们知道200大于33,因此我们在屏幕上打印出"b大于a"。
缩进
Python 依靠缩进(行首的空白)来定义代码中的作用域。其他编程语言通常使用花括号来实现这一目的。
示例
如果语句没有缩进(将引发错误):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
广告
埃利夫
elif [关键字是 Python 表示 "如果前面的条件不成立,那么 尝试这个条件"。]
示例
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
在这个例子中 a 等于 b,所以第一个条件不成立,但 elif 条件成立,因此我们打印到屏幕上 "a 和 b 相等"。
否则
否则关键字捕获前面条件没有捕获到的任何内容。
示例
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
在这个例子中 a 大于 b, 所以第一个条件不成立,同时 elif 条件也不成立, 所以我们进入 else 条件并打印到屏幕上 "a 大于 b"。
You can also have an [else] without the [elif]:
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example
One line if statement:
if a > b: print("a is greater than b")
Short Hand If ... Else
If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:
Example
One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
This technique is known as Ternary Operators, or Conditional Expressions.
You can also have multiple else statements on the same line:
Example
One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
And
The [and] keyword is a logical operator, and is used to combine conditional statements:
Example
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
The [or] keyword is a logical operator, and is used to combine conditional statements:
Example
测试 a是否大于 b,或者 a 是否大于c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
不
the[not] 关键字是一个逻辑运算符,并且 用于反转条件语句的结果:
示例
测试a是否不小于 b:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
嵌套的 If
你可以在[if]语句内 [if]有语句,这被称为嵌套 [if]语句。
示例
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
通过语句
[if] 语句不能为空,但如果由于某些原因你有一个[if] 无内容的语句,请插入[pass] 语句以避免出现错误。
示例
a = 33
b = 200
if b > a:
pass
