在Python 3中使用elif语句

时间:2013-06-07 02:31:08

标签: python-3.x

大家好我正在使用python 3,我在编写这段代码时遇到了麻烦。任何帮助将不胜感激,谢谢。

我有这个文档字符串,我必须做练习,但我从自动标记器中得到失败。这是docstring

'''(number) -> str

Return the size of a drink given the amount of volume of a beverage (in mL)
served. If a volume does not correspond to a drink size, return "invalid".

A kid-sized drink is any beverage of at least 100 mL but smaller
    than a large drink that isn't another drink size.
A small drink contains 200 mL of beverage.
A medium drink contains 300 mL of beverage.
A large drink contains 400 mL of beverage.
A jumbo drink contains 600 mL of beverage.
A promotional-sized drink is any beverage larger than a large drink that
    isn't another drink size.

>>> drink_size(-20)
'invalid'
>>> drink_size(200)
'small'
>>> drink_size(120)
'kid-sized'
'''

这就是我的代码看起来像

def drink_size(volume):
    if 100 <= volume < 400 and volume != 200 and volume != 300:
        return ('kid-sized')
    elif volume == 200:
        return ('small drink')
    elif volume == 300:
        return ('medium drink')
    elif volume == 400:
        return ('large drink')
    elif volume == 600:
        return ('jumbo drink')
    elif volume > 400 and volume != 600:
        return ('promotionl-sized')
    else:
        return ('invalid')    

请帮忙,我不知道为什么它不起作用

1 个答案:

答案 0 :(得分:2)

您的代码可以简化,首先检查确切的值,然后是范围值,如果值不符合任何条件(< 100那里),最后拒绝:

def drink_size(volume):
    # specific size check
    if volume == 200:
        return 'small'
    elif volume == 300:
        return 'medium'
    elif volume == 400:
        return 'large'
    elif volume == 600:
        return 'jumbo'

    # Range check
    elif 100 <= volume < 400:
        return 'kid-sized'
    elif volume > 400:
        return 'promotional-sized'
    else:
        return 'invalid'

您甚至可以重构以避免使用这一长if套件并使您的代码更具可读性:

# Create a dictionary of volume to verbose size
sizes = {200: 'small', 300: 'medium', 400: 'large', 600: 'jumbo'}

def drink_size(volume):
    # specific size check
    if volume in sizes:
        return sizes[volume]

    # Range check
    elif 100 <= volume < 400:
        return 'kid-sized'
    elif volume > 400:
        return 'promotional-sized'
    else:
        return 'invalid'