Python的分支语句if

概述

Python支持的常用数据逻辑判断条件
等于 :a == b
不等于 :a != b
小于 :a < b
小于等于 :a <= b
大于 :a > b
大于等于 :a >= b

if语句

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

输出:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
b is greater than a
Process finished with exit code 0

if…elif语句

a = 200
b = 200
if b > a :
    print("b is greater than a")
elif b == a:
    print("b is equal a")

输出:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
b is equal a
Process finished with exit code 0

if…elif…else语句

a = 200
b = 99
if b > a :
    print("b is greater than a")
elif b == a:
    print("b is equal a")
else:
    print("b is less than a")

输出:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
b is less than a
Process finished with exit code 0

Python 依赖缩进,使用空格来定义代码中的范围。其他编程语言通常使用花括号来实现此目的

单行if语句

如果只有一条语句要执行,则可以将其与 if 语句放在同一行。

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

输出:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
a is greater than b
Process finished with exit code 0

单行if…else语句

如果只有两条语句要执行,一条用于 if,另一条用于 else,则可以将它们全部放在同一行

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

输出:

扫描二维码关注公众号,回复: 12123208 查看本文章
E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
A
Process finished with exit code 0

有三个条件的单行if…else语句

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

输出:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
A
Process finished with exit code 0

组合条件的if语句

and if语句

a = 200
b = 66
c = 500
if a > b and c > a:
  print("Both conditions are True")
else:
    print("conditions is not True")

输出:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
Both conditions are True
Process finished with exit code 0

or if语句

a = 200
b = 66
c = 500
if a > b or a > c:
  print("At least one of the conditions is True")

输出:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
At least one of the conditions is True
Process finished with exit code 0

嵌套if语句

x = 52

if x > 10:
  print("Above ten,")
  if x > 20:
    print("and also above 20!")
  else:
    print("but not above 20.")

输出:

E:\Python3\Exercise\venv\Scripts\python.exe E:/Python3/Exercise/venv/01.py
Above ten,
and also above 20!
Process finished with exit code 0

pass语句

if 语句不能为空,但是如果您处于某种原因写了无内容的 if 语句,请使用 pass 语句来避免错误。

a = 66
b = 200

if b > a:
  pass

[上一页][下一页]

猜你喜欢

转载自blog.csdn.net/wzc18743083828/article/details/109789879