python3—廖雪峰之练习(二)

函数的参数练习
请定义一个函数quadratic(a, b, c), 接收3个参数,返回一元二次方程 : $ ax^2+b+c=0 $
的两个解
提示:计算平方根可以调用math.sqrt()函数:

一元二次方程的求根方程:$ x = \frac{-b ± \sqrt{b^2 - 4ac}}{2a} $

import math
def quadratic(a, b, c):
    i = pow(b, 2) - 4*a*c
    x1 = (-b + math.sqrt(x)) / (2*a)
    x2 = (-b + math.sqrt(x)) / (2*a)
    return x1, x2

print(quadratic(2, 3, 1))
print(quadratic(1, 3, -4))

生成器练习
如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错:

>>> L = ['Hello', 'World', 18, 'Apple', None]
>>> [s.lower() for s in L]
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'

使用内建的isinstance函数可以判断一个变量是不是字符串:

>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False

请修改列表生成式,通过添加if语句保证列表生成式能正确执行:

L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = []
for x in L1:
    if instance(x):
        L2.append(x)
[x.lower() for x in L2]        
print(L2)
posted @ 2017-10-23 16:49  哨音  阅读(625)  评论(0编辑  收藏  举报