Python 入门日记(五)—— if 语句

2020.07.07 Python 入门的 Day4

成就:if 语句的使用。

  • 与 C 语言类似,Python 中“相等”的判断用“==”;“不等”用“!=”……
  • 使用 in 或 not in 来判断特定值是/否包含在列表中。
  • 布尔表达式的结果为 True 或 False。
requested_toppings = ["mushrooms", "onions", "pineapple"]
if "mushrooms" in requested_toppings:
    print("Mushrooms")
if "onions" not in requested_toppings:
    print("Onions")
  • Python 中的 and 相当于 C 语言中的 &&,or 相当于 C 语言中的 ||。
if ("onions" not in requested_toppings) and ("mushrooms" in requested_toppings):
    print("NEW BIRD")
  • 同样使用缩进来表示 if 语句下执行的语句。
  • if , if-else , if-elif-else , if-elif-elif-else ……
if ("onions" not in requested_toppings) and ("mushrooms" in requested_toppings):
    print("NEW BIRD")
elif "onions" in requested_toppings:
    print("NB BIRD")
else:
    print("OLD BIRD")
  • 可使用 if 语句判断一个列表是不是空的。
requested_toppings = []
if requested_toppings:
    print("Nice")
else: print("WOW")
原文地址:https://www.cnblogs.com/A-Tree/p/13262307.html