Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #111731 > unrolled thread
| Started by | sigmaphine1914@gmail.com |
|---|---|
| First post | 2016-07-21 19:27 -0700 |
| Last post | 2016-07-23 11:39 -0400 |
| Articles | 11 — 8 participants |
Back to article view | Back to comp.lang.python
learning python. learning defining functions . need help sigmaphine1914@gmail.com - 2016-07-21 19:27 -0700
Re: learning python. learning defining functions . need help Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2016-07-22 09:13 -0400
Re: learning python. learning defining functions . need help Chris Angelico <rosuav@gmail.com> - 2016-07-22 23:24 +1000
Re: learning python. learning defining functions . need help justin walters <walters.justin01@gmail.com> - 2016-07-22 08:21 -0700
Re: learning python. learning defining functions . need help Steven D'Aprano <steve@pearwood.info> - 2016-07-23 11:44 +1000
Re: learning python. learning defining functions . need help Random832 <random832@fastmail.com> - 2016-07-22 11:35 -0400
Re: learning python. learning defining functions . need help Chris Angelico <rosuav@gmail.com> - 2016-07-23 01:35 +1000
Re: learning python. learning defining functions . need help "D'Arcy J.M. Cain" <darcy@Vex.Net> - 2016-07-22 11:41 -0400
Re: learning python. learning defining functions . need help MRAB <python@mrabarnett.plus.com> - 2016-07-22 19:36 +0100
Re: learning python. learning defining functions . need help Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2016-07-22 20:04 -0400
Re: learning python. learning defining functions . need help Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2016-07-23 11:39 -0400
| From | sigmaphine1914@gmail.com |
|---|---|
| Date | 2016-07-21 19:27 -0700 |
| Subject | learning python. learning defining functions . need help |
| Message-ID | <432aeb03-ea14-4ece-8e5b-a7521cf12b84@googlegroups.com> |
having a little trouble with defining functions. i have a doc called ch5.py and when i was trying the following i had issues
"
Try It Out: Defining a Function
Try saving the following in your file for Chapter 5, ch5.py.def in_fridge():
try:
count = fridge[wanted_food]
except KeyError:
count = 0
return count
How It Works
When you invoke ch5.py (press F5 while in Code Editor) with just the in_fridge function defined, you won't see any output. However, the function will be defined, and it can be invoked from the interactive Python session that you've created.
To take advantage of the in_fridge function, though, you have to ensure that there is a dictionary called fridge with food names in it. In addition, you have to have a string in the name wanted_food. This string is how you can ask, using in_fridge, whether that food is available. Therefore, from the interactive session, you can do this to use the function:
>>> fridge = {'apples':10, 'oranges':3, 'milk':2}
>>> wanted_food = 'apples'
>>> in_fridge()
10
>>> wanted_food = 'oranges'
>>> in_fridge()
3
>>> wanted_food = 'milk'
>>> in_fridge()
2"
---this is what I have and tried to run--
def in_fridge():
fridge = {'apples':10, 'oranges':3, 'milk':2}
wanted_food = 'apples'
in_fridge()
where am i going wrong
[toc] | [next] | [standalone]
| From | Dennis Lee Bieber <wlfraed@ix.netcom.com> |
|---|---|
| Date | 2016-07-22 09:13 -0400 |
| Message-ID | <mailman.47.1469193216.22221.python-list@python.org> |
| In reply to | #111731 |
On Thu, 21 Jul 2016 19:27:38 -0700 (PDT), sigmaphine1914@gmail.com
declaimed the following:
>
>"
>Try It Out: Defining a Function
>Try saving the following in your file for Chapter 5, ch5.py.def in_fridge():
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>
>
> try:
> count = fridge[wanted_food]
> except KeyError:
> count = 0
> return count
<snip>
>---this is what I have and tried to run--
>def in_fridge():
>
> fridge = {'apples':10, 'oranges':3, 'milk':2}
>wanted_food = 'apples'
>in_fridge()
>
>
>where am i going wrong
Off-hand -- you didn't follow the instructions.
Your "in_fridge" function merely attaches the local name "fridge" to a
dictionary, then exits (at which point the dictionary and local name are
garbage collected).
The assignment implies that both the dictionary "fridge" and
"wanted_food" are module (file) level globals. Module globals can be seen
and read by functions defined in the module, but normally not written.
The code you failed to include uses both globals to look up the
availability of the item and, if found, returns the count value.
Granted -- from where I sit, that whole use of globals for both the
dictionary and the search term smells like 1970s K&K BASIC using GOSUB. At
the least, the search term should have been passed as an argument in the
function call
print (in_fridge("apples"))
for example....
Now... Going much beyond the assignment (if you were having trouble
with the assignment, this will seem like magic) [Python 2.7]:
-=-=-=-=-
"""
Refrigerator Stocking Example
July 22 2016 Dennis L Bieber
"""
class Refrigerator(object):
def __init__(self, stock=None):
if stock is None or type(stock) != type(dict()):
self._stock = dict()
else:
self._stock = stock
def available(self, item):
return self._stock.get(item, 0)
def add(self, item, amount):
self._stock[item] = self.available(item) + amount
return self.available(item)
def remove(self, item, amount):
avail = min(self.available(item), amount)
self._stock[item] = self.available(item) - avail
return avail
if __name__ == "__main__":
drinks = Refrigerator({"coca cola" : 20,
"pepsi cola" : 10,
"rc cola" : 5,
"vernors" : 31})
fruits = Refrigerator()
fruits.add("apples", 30)
fruits.add("pears", 25)
fruits.add("kiwis", 10)
print "vernors", drinks.available("vernors")
print "rc cola", drinks.available("rc cola")
print "take 10 rc cola", drinks.remove("rc cola", 10)
print "rc cola left", drinks.available("rc cola")
print "take 5 vernors", drinks.remove("vernors", 5)
print "vernors left", drinks.available("vernors")
print "take 1 kiwis", fruits.remove("kiwis", 1)
print "kiwis left", fruits.available("kiwis")
print drinks._stock #going inside the class
print fruits._stock
-=-=-=-=-
C:\Users\Wulfraed\Documents\Python Progs>refrigerator.py
vernors 31
rc cola 5
take 10 rc cola 5
rc cola left 0
take 5 vernors 5
vernors left 26
take 1 kiwis 1
kiwis left 9
{'coca cola': 20, 'pepsi cola': 10, 'vernors': 26, 'rc cola': 0}
{'kiwis': 9, 'apples': 30, 'pears': 25}
C:\Users\Wulfraed\Documents\Python Progs>
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed@ix.netcom.com HTTP://wlfraed.home.netcom.com/
[toc] | [prev] | [next] | [standalone]
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2016-07-22 23:24 +1000 |
| Message-ID | <mailman.48.1469193870.22221.python-list@python.org> |
| In reply to | #111731 |
On Fri, Jul 22, 2016 at 11:13 PM, Dennis Lee Bieber
<wlfraed@ix.netcom.com> wrote:
> Now... Going much beyond the assignment (if you were having trouble
> with the assignment, this will seem like magic) [Python 2.7]:
I'm not sure, but I think your code would become Py3 compatible if you
just change your prints. Which I'd recommend - it's not difficult to
just always print a single string, and most example code is ASCII-only
and has no difficulty with the bytes/unicode distinction. But, point
of curiosity...
> class Refrigerator(object):
> def __init__(self, stock=None):
> if stock is None or type(stock) != type(dict()):
> self._stock = dict()
> else:
> self._stock = stock
... why do you call up "type(dict())"? Why not either just "dict" or "type({})"?
ChrisA
[toc] | [prev] | [next] | [standalone]
| From | justin walters <walters.justin01@gmail.com> |
|---|---|
| Date | 2016-07-22 08:21 -0700 |
| Message-ID | <mailman.55.1469200885.22221.python-list@python.org> |
| In reply to | #111731 |
On Fri, Jul 22, 2016 at 6:24 AM, Chris Angelico <rosuav@gmail.com> wrote:
> On Fri, Jul 22, 2016 at 11:13 PM, Dennis Lee Bieber
> <wlfraed@ix.netcom.com> wrote:
> > Now... Going much beyond the assignment (if you were having
> trouble
> > with the assignment, this will seem like magic) [Python 2.7]:
>
> I'm not sure, but I think your code would become Py3 compatible if you
> just change your prints. Which I'd recommend - it's not difficult to
> just always print a single string, and most example code is ASCII-only
> and has no difficulty with the bytes/unicode distinction. But, point
> of curiosity...
>
> > class Refrigerator(object):
> > def __init__(self, stock=None):
> > if stock is None or type(stock) != type(dict()):
> > self._stock = dict()
> > else:
> > self._stock = stock
>
> ... why do you call up "type(dict())"? Why not either just "dict" or
> "type({})"?
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
Hi Chris,
Try opening the interactive terminal on your command line and type the
following:
type({}) == dict()
That should illustrate why. This is because simply typing '{}' could be
interpreted as
either a dict or a set. My interpreter defaults 'type({})' to 'dict', but
it's best to not
take the risk.
You could also replace that line with:
if stock is None or type(stock) != dict:
[toc] | [prev] | [next] | [standalone]
| From | Steven D'Aprano <steve@pearwood.info> |
|---|---|
| Date | 2016-07-23 11:44 +1000 |
| Message-ID | <5792cc18$0$1597$c3e8da3$5496439d@news.astraweb.com> |
| In reply to | #111759 |
On Sat, 23 Jul 2016 01:21 am, justin walters wrote:
> That should illustrate why. This is because simply typing '{}' could be
> interpreted as
> either a dict or a set.
No. {} is always an empty dict. That is a language guarantee. Any
programming language where {} is not an empty disk is not valid Python.
> My interpreter defaults 'type({})' to 'dict', but it's best to not
> take the risk.
Are you concerned that type([]) might not be list? Or type("") might not be
str? Or that type(0) might not be int?
> You could also replace that line with:
>
> if stock is None or type(stock) != dict:
Generally speaking, the right way to test whether something is an instance
of a type is to use the isinstance() function:
if stock is None or not isinstance(stock, dict): ...
That will work correctly even if stock belongs to a subclass of dict.
--
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
[toc] | [prev] | [next] | [standalone]
| From | Random832 <random832@fastmail.com> |
|---|---|
| Date | 2016-07-22 11:35 -0400 |
| Message-ID | <mailman.56.1469201704.22221.python-list@python.org> |
| In reply to | #111731 |
On Fri, Jul 22, 2016, at 11:21, justin walters wrote:
> Try opening the interactive terminal on your command line and type the
> following:
>
> type({}) == dict()
>
> That should illustrate why.
That doesn't illustrate anything relevant at all. The reason this is
false is because dict() is a dict instance, not the dict type.
type({}) == dict == type(dict()) will always* be true.
>This is because simply typing '{}' could be interpreted as either a
>dict or a set. My interpreter defaults 'type({})' to 'dict', but it's
>best to not take the risk.
This is part of the language spec, it is not something that can be
chosen by each interpreter.
*well, assuming that "type" and "dict" have not been reassigned from
their built-in definitions.
[toc] | [prev] | [next] | [standalone]
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2016-07-23 01:35 +1000 |
| Message-ID | <mailman.57.1469201759.22221.python-list@python.org> |
| In reply to | #111731 |
On Sat, Jul 23, 2016 at 1:21 AM, justin walters
<walters.justin01@gmail.com> wrote:
> Hi Chris,
>
> Try opening the interactive terminal on your command line and type the
> following:
>
> type({}) == dict()
>
> That should illustrate why. This is because simply typing '{}' could be
> interpreted as
> either a dict or a set. My interpreter defaults 'type({})' to 'dict', but
> it's best to not
> take the risk.
Of course the type of {} is not equal to an empty dict, but it *will*
be equal to dict itself:
>>> type({}) == dict
True
And it's not ambiguous; it's always going to mean a dictionary.
There's no empty set syntax in Python (well, not as of 3.6, anyway).
> You could also replace that line with:
>
> if stock is None or type(stock) != dict:
That's exactly what I was saying. Barring shenanigans (like shadowing
'dict' with a function or something), type(dict()) will always be
dict.
ChrisA
[toc] | [prev] | [next] | [standalone]
| From | "D'Arcy J.M. Cain" <darcy@Vex.Net> |
|---|---|
| Date | 2016-07-22 11:41 -0400 |
| Message-ID | <mailman.61.1469210808.22221.python-list@python.org> |
| In reply to | #111731 |
On Fri, 22 Jul 2016 08:21:17 -0700 justin walters <walters.justin01@gmail.com> wrote: > You could also replace that line with: > > if stock is None or type(stock) != dict: Use isinstance(). That handles classes that subclass dict as well. -- D'Arcy J.M. Cain System Administrator, Vex.Net http://www.Vex.Net/ IM:darcy@Vex.Net VoIP: sip:darcy@Vex.Net
[toc] | [prev] | [next] | [standalone]
| From | MRAB <python@mrabarnett.plus.com> |
|---|---|
| Date | 2016-07-22 19:36 +0100 |
| Message-ID | <mailman.62.1469212620.22221.python-list@python.org> |
| In reply to | #111731 |
On 2016-07-22 16:41, D'Arcy J.M. Cain wrote: > On Fri, 22 Jul 2016 08:21:17 -0700 > justin walters <walters.justin01@gmail.com> wrote: >> You could also replace that line with: >> >> if stock is None or type(stock) != dict: > > Use isinstance(). That handles classes that subclass dict as well. > If you're checking that it's a dict, there's no need to check whether it's None, because None isn't a dict either!
[toc] | [prev] | [next] | [standalone]
| From | Dennis Lee Bieber <wlfraed@ix.netcom.com> |
|---|---|
| Date | 2016-07-22 20:04 -0400 |
| Message-ID | <mailman.67.1469232306.22221.python-list@python.org> |
| In reply to | #111731 |
On Fri, 22 Jul 2016 23:24:27 +1000, Chris Angelico <rosuav@gmail.com>
declaimed the following:
>
>... why do you call up "type(dict())"? Why not either just "dict" or "type({})"?
>
I seldom bother with type checks in my normal quick&dirty programs...
And wasn't certain is {} would also include sets.
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed@ix.netcom.com HTTP://wlfraed.home.netcom.com/
[toc] | [prev] | [next] | [standalone]
| From | Dennis Lee Bieber <wlfraed@ix.netcom.com> |
|---|---|
| Date | 2016-07-23 11:39 -0400 |
| Message-ID | <mailman.84.1469288392.22221.python-list@python.org> |
| In reply to | #111731 |
On Fri, 22 Jul 2016 20:04:56 -0400, Dennis Lee Bieber
<wlfraed@ix.netcom.com> declaimed the following:
>On Fri, 22 Jul 2016 23:24:27 +1000, Chris Angelico <rosuav@gmail.com>
>declaimed the following:
>
>>
>>... why do you call up "type(dict())"? Why not either just "dict" or "type({})"?
>>
> I seldom bother with type checks in my normal quick&dirty programs...
>And wasn't certain is {} would also include sets.
And I'll accept that comparing against dict() was is in error... Just
an example of how little I use those (and I was running late getting to
work -- I posted the code about 0918, needed to be at work by 1000, and
still had to take a shower/shave/etc.)
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed@ix.netcom.com HTTP://wlfraed.home.netcom.com/
[toc] | [prev] | [standalone]
Back to top | Article view | comp.lang.python
csiph-web