美文网首页Python 成长笔记
Python拾珍:1. 条件表达式

Python拾珍:1. 条件表达式

作者: 赵者也 | 来源:发表于2018-02-26 09:58 被阅读4次

源代码 1:

if x > 0:
    y = math.log(x)
else:
    y = float('nan')

源代码 1 的条件表达式:

y = math.log(x) if x > 0 else float('nan')

源代码 2:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

源代码 2 的条件表达式:

def factorial(n):
    return 1 if n == 0 else n * factorial(n - 1)

条件表达式的另一个用途是处理可选参数。例如:

def __init__(self, name, contents=None):
    self.name = name
    if contents == None:
        contents = []
    self.pouch_contents = contents

对应的条件表达式方式为:

def __init__(self, name, contents=None):
    self.name = name
    self.pouch_contents = [] if contents == None else contents

本文参考自《像计算机科学家一样思考Python (第2版)

相关文章

网友评论

    本文标题:Python拾珍:1. 条件表达式

    本文链接:https://www.haomeiwen.com/subject/fusrtftx.html