#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    1
    Rep Power
    0

    Beginner question


    I am using python 2.4 and I am having trouble creating a function that will accept corresponding values with either true or false. I want to know how to create a function where the parameters only accept boo-leans of True or False and return back a list of the corresponding parameter where each parameter is assigned a food topping. For example.

    Code:
    toppings(True, True, True, False) -> “The food has bacon lettuce tomato."
    toppings(False, True, False, True) -> “The food has lettuce mayo.”
    toppings(False, False, False, True) -> “The food has mayo"
    toppings(False, False, False, False) -> “You must be full!"
    where a=bacon, b=lettuce, c=tomato, and d=mayo.

    My attempt:



    Code:
    def toppings(bacon,lettuce,tomato,mayo):
        args = (bacon,lettuce,tomato,mayo)
        for element in args:
            if args == True:
                return "The food has "+" ".join(x for x,y in zip(args) if y) + '.'
            else:
                return "You must be full"
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2007
    Location
    Joensuu, Finland
    Posts
    430
    Rep Power
    67
    Originally Posted by dimension_3
    My attempt:



    Code:
    def toppings(bacon,lettuce,tomato,mayo):
        args = (bacon,lettuce,tomato,mayo)
        for element in args:
            if args == True:
                return "The food has "+" ".join(x for x,y in zip(args) if y) + '.'
            else:
                return "You must be full"
    There are several errors.

    First, “args” copies the values passed to the function. This is of course intended (though there are better ways of doing this) since you want to iterate through the arguments, but you must remember it evaluates to a tuple of Booleans, say “(False, True, True, False)”; the names of the toppings are nowhere. You must create another iterable to hold the names as strings.

    Secondly, “args == True” compares a tuple of Booleans to a single Boolean. You must mean something like:
    Code:
    if any(args):
    “any()” is a function that takes an iterable and returns True if any of the elements in the iterable returns True.

    Thirdly, “zip()” takes two iterable arguments. It works nicely here when you really give it those: the tuple of Booleans AND the tuple containing the names of the toppings.
    My armada: openSUSE 13.1 (home desktop, home laptop), Crunchbang Linux 11 (mini laptop, work laptop), Android 4.2.1 (tablet)
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,841
    Rep Power
    480

IMN logo majestic logo threadwatch logo seochat tools logo