Classes And Ice Cream

What will the program output when you run

1
2
chocolate = IceCream("chocolate",4,1,6)
print chocolate.scoop()

using the below code?

Try to walk through the program in your head to find the answer before you actually run the code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class IceCream(object):
    def __init__(self, flavor, numScoops, costPerScoop, remaining_icecream):
        self.flavor = flavor
        self.numScoops = numScoops
        self.costPerScoop = costPerScoop
        self.remaining_icecream = remaining_icecream

    def scoop(self):
                #shows the amount of ice cream remaining after an order is scooped
        #scoops icecream and decreases the number of scoops left
        self.remaining_icecream -= self.numScoops
        return self.remaining_icecream

    def total_cost(self):
        #vanilla ice cream is sold at a discount of half off!
        if self.flavor == "vanilla":
            total_cost = self.numScoops * .5*self.costPerScoop

        else:
            total_cost = self.numScoops * self.costPerScoop

        return total_cost

0 1 2 3 4

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

3 solutions

Karleigh Moore
Jun 14, 2016

The answer is 2.

The number of scoops available at the beginning is 6. Then the customer orders 4 scoops. 6 - 4 = 2 scoops remaining.

Run the code to verify.

Sorry, but what is the name of programme that uses code?

M T - 4 years, 12 months ago

Log in to reply

I'm not sure if I'm understanding your question, but to run this code, copy it into some text editor (or you can do this in a python shell) and save the file as a .py file. You can name it whatever you like as long as it is the form FileName.py. (I named this iceCream.py on my computer).

Karleigh Moore - 4 years, 12 months ago

Log in to reply

Oh, Thank you!! :) I just want to know where to run the code. I am quite curious. :)

M T - 4 years, 12 months ago

Why does it return the number of scoops remaining? The last line of code says "return total_cost," so why would it not output the total cost?

Michael Vargas - 3 years, 6 months ago

total cost is only returned chocolate.total cost() is called. In the code above chocolate.scoop() is called which returns the value of remaining_icecream - numScoops

Alfred Esposito - 2 years, 3 months ago
Yoftahe Mekonnen
Jun 15, 2020

remaining icecream = 6, numScoops = 4 then self.remaining icecream -= self.numScoops =2

Kevin Chweya
Apr 6, 2018

Flavor = Chocolate, remaining_icecream = 6 & numScoops = 4. Number of Scoops remaining is 6 - 4 = 2

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...