第十二章 if Tests and Syntax Rules

来源:互联网 发布:名字测试软件 编辑:程序博客网 时间:2024/05/18 01:51

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 33>>> [] 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
原创粉丝点击