0

大家好,我正在使用 python 3,但我在执行此代码时遇到了麻烦。任何帮助将不胜感激,谢谢。

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

'''(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')    

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

4

1 回答 1

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'
于 2014-05-20T07:00:30.117 回答