python学习

# -*- coding: utf-8 -*-

import math

'''
小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)
帮小明计算他的BMI指数,并根据BMI指数:
低于18.5:过轻
18.5-25:正常
25-28:过重
28-32:肥胖
高于32:严重肥胖
判断并打印结果:
'''
height = 1.75
weight = 80.5
bmi = weight / (height**2)
strResult = '严重肥胖'
if bmi < 18.5:
    strResult = '过轻'
elif bmi < 25:
    strResult = '正常'
elif bmi < 28:
    strResult = '过重'
elif bmi <= 32:
    strResult = '肥胖'
    
print(strResult)

s1 = 72
s2 = 85
r = (s2 - s1) / 72 * 100
print('提高了{0:.2f}分'.format(s2 - s1))
print('增长率%.2f%%' % r)

# list
L = [
    ['Apple', 'Google', 'Microsoft'],
    ['Java', 'Python', 'Ruby', 'PHP'],
    ['Adam', 'Bart', 'Lisa']
]

for eachlist in L:
    for item in eachlist:
        print(item)

print(L[-1][-1],'is learning',L[1][1])

'''
from learnPython import move
'''
def move(x, y, step, angle=0):
    for each in (x, y, step, angle):
        if not isinstance(each, (int, float)):
            raise TypeError("bad operand type for move(): '%s'" % str(each))

    nx = x + step * math.cos(angle)
    ny = y - step * math.sin(angle)
    return nx, ny
    
    
'''
请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程:
ax2 + bx + c = 0 的两个解。
'''
def quadratic(a, b, c):
    for param in (a, b, c):
        if not isinstance(a, (int, float)):
            raise TypeError("bad operand type for quadratic(): '{0}'".format(str(param)))
    
    if a == 0:
        if b != 0:
            return (-c / b, None)
        else:
            if c == 0:
                return ('any', 'any')
            else:
                return (None, None)

    delta = b ** 2 - 4 * a * c
    if delta < 0:
        return (None, None)
    e = -b / (2 * a)
    d = math.sqrt(delta) / (2 * a)
    return (e+d, e-d)
    
# 测试:
print('quadratic(2, 3, 1) =', quadratic(2, 3, 1))
print('quadratic(1, 3, -4) =', quadratic(1, 3, -4))

if quadratic(2, 3, 1) != (-0.5, -1.0):
    print('测试失败')
elif quadratic(1, 3, -4) != (1.0, -4.0):
    print('测试失败')
else:
    print('测试成功')

 

廖雪峰教程-函数

posted @ 2017-12-20 16:30  shankun  阅读(219)  评论(0编辑  收藏  举报