第十二章 if Tests and Syntax Rules

1.if Statements

General Format

if test1: # if test
     statements1 # Associated block
elif test2: # Optional elifs
     statements2

else: # Optional else
     statements3


>>> choice = 'ham'
>>> print({'spam': 1.25, # A dictionary-based 'switch'
... 'ham': 1.99, # Use has_key or get for default
... 'eggs': 0.99,
... 'bacon': 1.10}[choice])
1.99

Handling switch defaults:

>>> branch = {'spam': 1.25,
... 'ham': 1.99,
... 'eggs': 0.99}
>>> print(branch.get('spam', 'Bad choice'))
1.25
>>> print(branch.get('bacon', 'Bad choice'))
Bad choice

>>> choice = 'bacon'
>>> if choice in branch:
... print(branch[choice])
... else:
... print('Bad choice')
...
Bad choice

>>> try:
... print(branch[choice])
... except KeyError:
... print('Bad choice')
...
Bad choice

Handling larger actions:


def function(): ...
def default(): ...
branch = {'spam': lambda: ..., # A table of callable function objects
'ham': function,
'eggs': lambda: ...}
branch.get(choice, default)()

Python Syntax Revisited:

  • Statements execute one after another, until you say otherwise.
  • Block and statement boundaries are detected automatically
  • Compound statements = header + “:” + indented statements.
  • Blank lines, spaces, and comments are usually ignored.
  • Docstrings are ignored but are saved and displayed by tools.


Statement Delimiters: Lines and Continuations:

  • Statements may span multiple lines if you’re continuing an open syntactic pair. ()[]{}
  • Statements may span multiple lines if they end in a backslash. \
  • Special rules for string literals.triple-quoted

Truth Values and Boolean Tests:(使用文字,返回True False对象)

  • X and Y
  • X or Y
  • not X

>>> 2 or 3, 3 or 2 # Return left operand if true
(2, 3) # Else, return right operand (true or false)
>>> [] or 3
3
>>> [] or {}
{}


>>> 2 and 3, 3 and 2 # Return left operand if false
(3, 2) # Else, return right operand (true or false)
>>> [] and {}
[]
>>> 3 and []
[]


2. The if/else Ternary Expression

A = ((X and Y) or Z)
等价
A = Y if X else Z
等价
A = [Z, Y][bool(X)]  #not short-circuit









































  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值