Re: [Tutor] role playing game - help needed

2010-12-07 Thread Alan Gauld


"Al Stern"  wrote

attributes = {"strength": 0, "health": 0, "wisdom": 0, "dexterity": 
0}

MAX_POINTS = 30

How do I set the variable for available_points?

available_points = MAX_POINTS - (not sure what goes here)


Check the mail from Robert Sjoblom, he gives you the necessary clues.
You can check the archive a few weeks back(21st Nov) for his question
too and get some alternative options and discussion.

attributes["strength"] = input("\nHow many points do you want to 
assign to

strength?: ")

Please let me know if this isn't advisable.  It seems to work on the
surface.


Close, but remember that input() returns a string. You need numbers
so you need to convert strings to integers.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python vs. MATLAB

2010-12-07 Thread Robert Sjöblom
> Joel Schwartz wrote:
>> Chris,
>>
>> Can you say more about number (7) in your list? What does "pass by value"
>> mean and what are the alternatives?
>
> Oh boy, is that a can of worms... and this is going to be a long post.
> You might want to go make yourself a coffee first :)
[snipped wall of text]

That was quite an interesting read, thanks for the lesson!

best regards,
Robert S.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] role playing game - help needed

2010-12-07 Thread Robert Sjöblom
>> Thanks for the advice.  I think I have the dictionary function set up right
>>> now although I'm still not clear why it is better than the list.
>>>
>>> attributes = {"strength": 0, "health": 0, "wisdom": 0, "dexterity": 0}
>>>
>>
>> Consider where you want to update the points for "health"
>>
>> Using two lists you need to loop over the keys list to find the index
>> of "health" then access the values list to set the points. Something
>> like this:
>>
>> for x in range(len(keys)):
>>   if keys[x] == "health":
>>   values[x] = newValue
>>
>> With a dictionary you just need to do
>>
>> attributes["health"] = newValue
>>
>> That's a lot less typing and will be faster performance too.
>> I'd also say its a lot easier to see whats happening - its more readable.
[snip]
>
> Ok.  I think I am starting to get it but still not sure how to separate the
> value from the key.  Once I have this...
>
> attributes = {"strength": 0, "health": 0, "wisdom": 0, "dexterity": 0}
> MAX_POINTS = 30
>
> How do I set the variable for available_points?
>
> available_points = MAX_POINTS - (not sure what goes here)
attributes.values() will give you a list of the values inside the
attributes dictionary (remember, dictionaries work by key: value
pairs). sum() won't work on a dictionary that contains both strings
and integers, . If you only use integers in your values, the list will
only contain integers, and so you can easily use sum() on it.

> I am pretty sure I will change the values by something like this...
>
> attributes["strength"] = input("\nHow many points do you want to assign to
> strength?: ")
>
> Please let me know if this isn't advisable.  It seems to work on the
> surface.
That's how you do it.

best regards,
Robert S.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] role playing game - help needed

2010-12-07 Thread Robert Sjöblom
>> attributes["strength"] = input("\nHow many points do you want to
>> assign to
>> strength?: ")
>>
>> Please let me know if this isn't advisable.  It seems to work on the
>> surface.
>
> Close, but remember that input() returns a string. You need numbers
> so you need to convert strings to integers.

Actually, input() only accept integers, consider the following:
>>> input("input: ")
input: d

Traceback (most recent call last):
  File "", line 1, in 
input("input: ")
  File "", line 1, in 
NameError: name 'd' is not defined

if you assign d to an integer, input() will accept it, however:
>>> d = 7
>>> input("input: ")
input: d
7

>>> input("input: ")
input: 7
7

>>> help(input)
Help on built-in function input in module __builtin__:

input(...)
input([prompt]) -> value

Equivalent to eval(raw_input(prompt)).

I've been told to use input() if I know that I'll only get integers,
and raw_input() for "everything." Would you say it's better to use
raw_input() for everything and convert as necessary?

best regards,
Robert S.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] role playing game - help needed

2010-12-07 Thread Peter Otten
Robert Sjöblom wrote:

>> Close, but remember that input() returns a string. You need numbers
>> so you need to convert strings to integers.
> 
> Actually, input() only accept integers, consider the following:
 input("input: ")
> input: d
> 
> Traceback (most recent call last):
> File "", line 1, in 
> input("input: ")
> File "", line 1, in 
> NameError: name 'd' is not defined

You are using Python 2.x where raw_input() was used to enter strings and 
input() behaved like

eval(raw_input())

From the above follows that input() in 2.x accepts arbitrary Python 
expressions:

Python 2.6.4 (r264:75706, Dec  7 2009, 18:43:55)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d = 42
>>> input()
d
42
>>> input()
d**2
1764
>>> input()
"*".join([str(d)]*5)
'42*42*42*42*42'

I think I drove the point home ;)

input() in Python 3.x on the other hand is similar to 2.x's raw_input():

Python 3.1.1+ (r311:74480, Nov  2 2009, 15:45:00)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> input()
d
'd'
>>> input()
"*".join([str(d)]*5)
'"*".join([str(d)]*5)'

Peter

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] role playing game - help needed

2010-12-07 Thread Al Stern
Apologies for all my questions.  Up to this point I have been able to work
out most of the challenges but I seem to have hit a wall.  Can't seem to
make any progress and completely frustrated.

I looked at the 11/21 discussion.  From the documentation, I realized I
needed to set the variables to view the keys and values.  Getting an error
though.

attributes = {"strength": 0, "health": 0, "wisdom": 0, "dexterity": 0}
MAX_POINTS = 30
keys = attributes.viewkeys()
values = attributes.viewvalues()

Traceback (most recent call last):
  File "C:\Users\Public\Documents\My Python programs\role_playing_game1.py",
line 8, in 
keys = attributes.viewkeys()
AttributeError: 'dict' object has no attribute 'viewkeys'




On Tue, Dec 7, 2010 at 3:44 AM, Alan Gauld wrote:

>
> "Al Stern"  wrote
>
>  attributes = {"strength": 0, "health": 0, "wisdom": 0, "dexterity": 0}
>> MAX_POINTS = 30
>>
>> How do I set the variable for available_points?
>>
>> available_points = MAX_POINTS - (not sure what goes here)
>>
>
> Check the mail from Robert Sjoblom, he gives you the necessary clues.
> You can check the archive a few weeks back(21st Nov) for his question
> too and get some alternative options and discussion.
>
>
> attributes["strength"] = input("\nHow many points do you want to assign to
>> strength?: ")
>>
>> Please let me know if this isn't advisable.  It seems to work on the
>> surface.
>>
>
> Close, but remember that input() returns a string. You need numbers
> so you need to convert strings to integers.
>
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] role playing game - help needed

2010-12-07 Thread Peter Otten
Al Stern wrote:

> Apologies for all my questions.  Up to this point I have been able to work
> out most of the challenges but I seem to have hit a wall.  Can't seem to
> make any progress and completely frustrated.
> 
> I looked at the 11/21 discussion.  From the documentation, I realized I
> needed to set the variables to view the keys and values.  Getting an error
> though.
> 
> attributes = {"strength": 0, "health": 0, "wisdom": 0, "dexterity": 0}
> MAX_POINTS = 30
> keys = attributes.viewkeys()
> values = attributes.viewvalues()
> 
> Traceback (most recent call last):
>   File "C:\Users\Public\Documents\My Python
>   programs\role_playing_game1.py",
> line 8, in 
> keys = attributes.viewkeys()
> AttributeError: 'dict' object has no attribute 'viewkeys'

The dictionary methods you are looking for are called keys() and values() 
not viewkeys() or viewvalues(). They do return view objects which may be 
causing the confusion. Have a look at the documentation at

http://docs.python.org/dev/py3k/library/stdtypes.html#dictionary-view-
objects

which shows a simple example. 
By the way you, can use the interactive interpreter to find out what 
attributes an object has to offer:

$ python3
Python 3.1.1+ (r311:74480, Nov  2 2009, 15:45:00)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {"a": 1, "b": 2}
>>> dir(d)
['__class__', '__contains__', '__delattr__', '__delitem__', '__doc__', 
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', 
'__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', 
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 
'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 
'setdefault', 'update', 'values']

Peter

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python vs. MATLAB

2010-12-07 Thread Joel Schwartz
Steven,

Thanks for taking the time to write such a detailed and illuminating
response! 

I learned programming in Pascal in college in the early 1980s and used
Fortran in grad school in the late 80s. That was pretty much the end of my
contact with programming until I began learning R last year and now Python.
About a paragraph into reading your response, something clunked into place
in the dark recesses of my brain and suddenly "pass by value" and "pass by
reference" started sounding familiar. But whatever I knew about these terms
20+ years ago was obviously quite simplistic when compared to where things
stand now.

Thanks again,
Joel 

> -Original Message-
> From: tutor-bounces+joel=joelschwartz@python.org 
> [mailto:tutor-bounces+joel=joelschwartz@python.org] On 
> Behalf Of Steven D'Aprano
> Sent: Monday, December 06, 2010 3:17 PM
> To: tutor@python.org
> Subject: Re: [Tutor] Python vs. MATLAB
> 
> Joel Schwartz wrote:
> > Chris,
> > 
> > Can you say more about number (7) in your list? What does 
> "pass by value"
> > mean and what are the alternatives?
> 
> Oh boy, is that a can of worms... and this is going to be a 
> long post. 
> You might want to go make yourself a coffee first :)
> 
> Pass by whatever (also written as "call by ...") is one of 
> those frustrating topics where people have added vast amounts 
> of confusion where no confusion need exist.
> 
> Take a variable, "x", and give it a value, say, 42. When you 
> pass that variable to a function, func(x), what happens?
> 
> Such a simple question, but you wouldn't believe how many 
> angry words have been written about it.
> 
> The problem is that there are a whole lot of answers to that 
> question, used by many different programming languages, but 
> most people are only familiar with *two*: pass by value, and 
> pass by reference. This is particularly strange since most 
> popular modern languages, like Ruby, Python and Java, don't 
> use either of those! Nevertheless, people have got it in 
> their head that there are only two calling conventions, and 
> so they hammer the square peg of the language's actual 
> behaviour until it will fit one or the other of the round 
> holes in their mind.
> 
> So there are huge flame wars about whether Python is pass by 
> value or pass by reference, with some people wrongly claiming 
> that Python is p-b-v for "simple" objects like numbers and 
> strings and p-b-r for "complicated" objected like lists. This 
> is nonsense.
> 
> But that pales before the craziness of the Java community, 
> that claims that Java is pass by value so long as you 
> understand that that values being passed are references and 
> not the value of the variable. But don't make the mistake of 
> thinking that makes Java pass by reference! Pass by 
> value-which-is-actually-a-reference is completely different 
> from pass by reference. Only the Java people don't call it 
> that, they just call it pass by value, even though Java's 
> behaviour is different from pass by value in common languages 
> like C, Pascal and Visual Basic.
> 
> How is this helpful? Even if *technically* true, for some 
> definition of "reference" and "value", it is gobbledygook. 
> It's as helpful as claiming that every language ever written, 
> without exception, is actually pass by flipping bits. No 
> values are actually passed anywhere, it's all just flipping 
> bits in memory.
> 
> 100% true, and 100% useless.
> 
> Translated into Python terms, the Java argument is this:
> 
> Take a variable, call it "x". When you say x = 42, the value 
> of x is not actually the number 42, like naive non-Java 
> programmers might think, but some invisible reference to 42. 
> Then when you call function(x), what gets passed to the 
> function is not 42 itself (what Pascal or C programmers call 
> "pass by value"), nor is it a reference to the
> *variable* "x" (which would be "pass by reference"), but the 
> invisible reference to 42. Since this is the "true" value of 
> x, Java is pass by value.
> 
> (The situation is made more complicated because Java actually 
> does pass ints like 5 by value, in the C or Pascal sense. The 
> above description should be understood as referring to 
> "boxed" integers, rather than unboxed. If this means nothing 
> to you, be glad. All you need know is that in Java terms, all 
> Python integers are boxed.)
> 
> And note that in the Ruby community, they call the exact same 
> behaviour "pass by reference". And then folks wonder why 
> people get confused.
> 
> All this because people insist on the false dichotomy that 
> there are only two argument passing conventions, pass by 
> value and pass by reference. But as this Wikipedia page 
> shows, there are actually many more than that:
> 
> http://en.wikipedia.org/wiki/Evaluation_strategy
> 
> 
> Let's go back to my earlier question. You have a variable x = 
> 42, and you pass it to a function. What happens?
> 
> In Pascal, or C, the compiler keeps a table mapping varia

[Tutor] Save file in a specific directory

2010-12-07 Thread Susana Iraiis Delgado Rodriguez
I make a script to redirect a txt file from an external directory, but in
this directory I don't have permission to write, just to read data. So I
make this module:
import os, time,fnmatch
from xlwt import Workbook
from osgeo import ogr,gdal,osr
from dbf import *
gdal.AllRegister()
file_list = []
folders = None
for root, folders, files in os.walk( "R:\\" ):
for filename in fnmatch.filter(files, '*.shp'):
file_list.append(os.path.join(root, filename))
wrkbk = Workbook()
wksht = wrkbk.add_sheet('shp')
wksht.row(0).write(0,'ruta')
wksht.row(0).write(1,'archivo')
wksht.row(0).write(2,'estructura bd')
for row, filepath in enumerate(file_list, start=1):
wksht.row(row).write(0, filepath)
(ruta, filename) = os.path.split(filepath)
 wksht.row(row).write(1, filename)
 f = os.path.splitext(filename)
 t = f[0]+'_bd.txt'
 d = n[0]+'.dbf'
 if os.path.lexists(d):
   filepath = "C:\\Python26\\"
   a = open (filepath +t,"w+")
   dbf = Dbf(d,new=False)
   for fldName in dbf.fieldDefs:
a.write(fldName.name)
a.write(" || ")
a.write(fldName.typeCode)
a.write("\n")
   dbf.close()
   a.close()
wksht.row(row).write(2, t)
   else:
   print "El archivo " +n[0]+".shp" " no tiene dbf"
   wksht.row(row).write(10, "Sin bd")


wrkbk.save('C\\Python26\\biblio_shp.xls')
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Save file in a specific directory

2010-12-07 Thread Susana Iraiis Delgado Rodriguez
My other message was incomplete, it was a mistake: This is the correct one

2010/12/7 Susana Iraiis Delgado Rodriguez 

> I make a script to redirect a txt file from an external directory, but in
> this directory I don't have permission to write, just to read data. So I
> make this module:
> import os, time,fnmatch
> from xlwt import Workbook
> from osgeo import ogr,gdal,osr
> from dbf import *
> gdal.AllRegister()
> file_list = []
> folders = None
> for root, folders, files in os.walk( "R:\\" ):
> for filename in fnmatch.filter(files, '*.shp'):
> file_list.append(os.path.join(root, filename))
> wrkbk = Workbook()
> wksht = wrkbk.add_sheet('shp')
> wksht.row(0).write(0,'ruta')
> wksht.row(0).write(1,'archivo')
> wksht.row(0).write(2,'estructura bd')
> for row, filepath in enumerate(file_list, start=1):
> wksht.row(row).write(0, filepath)
> (ruta, filename) = os.path.split(filepath)
>  wksht.row(row).write(1, filename)
>  f = os.path.splitext(filename)
>  t = f[0]+'_bd.txt'
>  d = n[0]+'.dbf'
>  if os.path.lexists(d):
>filepath = "C:\\Python26\\"
>a = open (filepath +t,"w+")
>dbf = Dbf(d,new=False)
>for fldName in dbf.fieldDefs:
>a.write(fldName.name)
>a.write(" || ")
>a.write(fldName.typeCode)
>a.write("\n")
>dbf.close()
>a.close()
>wksht.row(row).write(2, t)
>   else:
>   print "El archivo " +n[0]+".shp" " no tiene dbf"
>   wksht.row(row).write(10, "Sin bd"
> wrkbk.save('C:\\Python26\\biblio_shp.xls')
>
When I run the script I got the next error:
>>> import crawler_shp
Traceback (most recent call last):
  File "", line 1, in 
  File "crawler_shp.py", line 105, in 
dbf = Dbf(d,new=False)
  File "C:\Python26\lib\site-packages\dbf.py", line 125, in __init__
self.stream = file(f, ("r+b", "rb")[bool(readOnly)])
IOError: [Errno 13] Permission denied: 'R:\\Aplicaciones\\IRISv3\\mis
proyectos\
\HURACAN\\BUFFER1000.dbf'

The error is pointing to a library I used to make the script run: dbf.py. in
thid lines:
if isinstance(f, basestring):
# a filename
self.name = f
if new:
# new table (table file must be
# created or opened and truncated)
self.stream = file(f, "w+b")
else:
# tabe file must exist
self.stream = file(f, ("r+b", "rb")[bool(readOnly)])


>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python vs. MATLAB

2010-12-07 Thread Sander Sweers
On 7 December 2010 00:16, Steven D'Aprano  wrote:
> Oh boy, is that a can of worms... and this is going to be a long post. You
> might want to go make yourself a coffee first :)

Great writeup and much appreciated :-).

Thx
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Save file in a specific directory

2010-12-07 Thread Joel Goldstick
On Tue, Dec 7, 2010 at 12:20 PM, Susana Iraiis Delgado Rodriguez <
susana.delgad...@utzmg.edu.mx> wrote:

> My other message was incomplete, it was a mistake: This is the correct one
>
> 2010/12/7 Susana Iraiis Delgado Rodriguez 
>
>  I make a script to redirect a txt file from an external directory, but in
>> this directory I don't have permission to write, just to read data. So I
>> make this module:
>> import os, time,fnmatch
>> from xlwt import Workbook
>> from osgeo import ogr,gdal,osr
>> from dbf import *
>> gdal.AllRegister()
>> file_list = []
>> folders = None
>> for root, folders, files in os.walk( "R:\\" ):
>> for filename in fnmatch.filter(files, '*.shp'):
>> file_list.append(os.path.join(root, filename))
>> wrkbk = Workbook()
>> wksht = wrkbk.add_sheet('shp')
>> wksht.row(0).write(0,'ruta')
>> wksht.row(0).write(1,'archivo')
>> wksht.row(0).write(2,'estructura bd')
>> for row, filepath in enumerate(file_list, start=1):
>> wksht.row(row).write(0, filepath)
>> (ruta, filename) = os.path.split(filepath)
>>  wksht.row(row).write(1, filename)
>>  f = os.path.splitext(filename)
>>  t = f[0]+'_bd.txt'
>>  d = n[0]+'.dbf'
>>  if os.path.lexists(d):
>>filepath = "C:\\Python26\\"
>>a = open (filepath +t,"w+")
>>dbf = Dbf(d,new=False)
>>for fldName in dbf.fieldDefs:
>>a.write(fldName.name)
>>a.write(" || ")
>>a.write(fldName.typeCode)
>>a.write("\n")
>>dbf.close()
>>a.close()
>>wksht.row(row).write(2, t)
>>   else:
>>   print "El archivo " +n[0]+".shp" " no tiene dbf"
>>   wksht.row(row).write(10, "Sin bd"
>> wrkbk.save('C:\\Python26\\biblio_shp.xls')
>>
> When I run the script I got the next error:
> >>> import crawler_shp
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "crawler_shp.py", line 105, in 
>
> dbf = Dbf(d,new=False)
>   File "C:\Python26\lib\site-packages\dbf.py", line 125, in __init__
> self.stream = file(f, ("r+b", "rb")[bool(readOnly)])
> IOError: [Errno 13] Permission denied: 'R:\\Aplicaciones\\IRISv3\\mis
> proyectos\
> \HURACAN\\BUFFER1000.dbf'
>
> The error is pointing to a library I used to make the script run: dbf.py.
> in thid lines:
> if isinstance(f, basestring):
> # a filename
> self.name = f
> if new:
> # new table (table file must be
> # created or opened and truncated)
> self.stream = file(f, "w+b")
> else:
> # tabe file must exist
> self.stream = file(f, ("r+b", "rb")[bool(readOnly)])
>
>
>>
>>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
Do you have write privilege in the directory where you want to create the
file?

-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Save file in a specific directory

2010-12-07 Thread Jerry Hill
> When I run the script I got the next error:
 import crawler_shp
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "crawler_shp.py", line 105, in 
>     dbf = Dbf(d,new=False)
>   File "C:\Python26\lib\site-packages\dbf.py", line 125, in __init__
>     self.stream = file(f, ("r+b", "rb")[bool(readOnly)])
> IOError: [Errno 13] Permission denied: 'R:\\Aplicaciones\\IRISv3\\mis
> proyectos\
> \HURACAN\\BUFFER1000.dbf'
>
> The error is pointing to a library I used to make the script run: dbf.py. in
> thid lines:
> if isinstance(f, basestring):
>     # a filename
>     self.name = f
>     if new:
>     # new table (table file must be
>     # created or opened and truncated)
>     self.stream = file(f, "w+b")
>     else:
>     # tabe file must exist
>     self.stream = file(f, ("r+b", "rb")[bool(readOnly)])


Sounds like you need to change your dbf object to something like this:
 dbf = Dbf(d,new=False, readOnly=True)

Note that I don't know anything about the Dbf module, other than what
you just posted.  If you really have read permission, but not write
permissions, this should do what you want though.

-- 
Jerry
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] role playing game - help needed

2010-12-07 Thread Al Stern
Tried to use the documentation but still getting the errors...

The 1st one has to do with the available_points

# set variables
attributes = {"strength": 0, "health": 0, "wisdom": 0, "dexterity": 0}
MAX_POINTS = 30
available_points = MAX_POINTS - attributes.values()
keys = attributes.keys()
values = attributes.values()

this is the error i'm getting...

Traceback (most recent call last):
  File "C:\Users\Public\Documents\My Python programs\role_playing_game1.py",
line 8, in 
available_points = MAX_POINTS - attributes.values()
TypeError: unsupported operand type(s) for -: 'int' and 'dict_values'

I know using attributes.values here isn't correct but I can't figure out how
to put the sum of the values into that equation.

I looked up this part f the docs...
http://docs.python.org/py3k/library/stdtypes.html?highlight=values#dict.values
and tried to copy the format into my program. I am attempting to get the
total of the values of everything in my dictionary.   Not sure what is
different between my 'attributes' dictionary and the 'dishes' dictionary
they use.  I used the following code and got the following error.

attributes["strength"] = input("\nHow many points do you want to assign to
strength?: ")

#point allocation
point_total = 0
for val in values:
  point_total += val
  print (point_total)

and get this error...

Traceback (most recent call last):
  File "C:\Users\Public\Documents\My Python programs\role_playing_game1.py",
line 26, in 
point_total += val
TypeError: unsupported operand type(s) for +=: 'int' and 'str'




On Tue, Dec 7, 2010 at 10:06 AM, Peter Otten <__pete...@web.de> wrote:

> Al Stern wrote:
>
> > Apologies for all my questions.  Up to this point I have been able to
> work
> > out most of the challenges but I seem to have hit a wall.  Can't seem to
> > make any progress and completely frustrated.
> >
> > I looked at the 11/21 discussion.  From the documentation, I realized I
> > needed to set the variables to view the keys and values.  Getting an
> error
> > though.
> >
> > attributes = {"strength": 0, "health": 0, "wisdom": 0, "dexterity": 0}
> > MAX_POINTS = 30
> > keys = attributes.viewkeys()
> > values = attributes.viewvalues()
> >
> > Traceback (most recent call last):
> >   File "C:\Users\Public\Documents\My Python
> >   programs\role_playing_game1.py",
> > line 8, in 
> > keys = attributes.viewkeys()
> > AttributeError: 'dict' object has no attribute 'viewkeys'
>
> The dictionary methods you are looking for are called keys() and values()
> not viewkeys() or viewvalues(). They do return view objects which may be
> causing the confusion. Have a look at the documentation at
>
> http://docs.python.org/dev/py3k/library/stdtypes.html#dictionary-view-
> objects
>
> which shows a simple example.
> By the way you, can use the interactive interpreter to find out what
> attributes an object has to offer:
>
> $ python3
> Python 3.1.1+ (r311:74480, Nov  2 2009, 15:45:00)
> [GCC 4.4.1] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> d = {"a": 1, "b": 2}
> >>> dir(d)
> ['__class__', '__contains__', '__delattr__', '__delitem__', '__doc__',
> '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
> '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__',
> '__lt__',
> '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
> '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__',
> 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem',
> 'setdefault', 'update', 'values']
>
> Peter
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] role playing game - help needed

2010-12-07 Thread Adam Bark

On 07/12/10 22:10, Al Stern wrote:

Tried to use the documentation but still getting the errors...
The 1st one has to do with the available_points
# set variables
attributes = {"strength": 0, "health": 0, "wisdom": 0, "dexterity": 0}
MAX_POINTS = 30
available_points = MAX_POINTS - attributes.values()
keys = attributes.keys()
values = attributes.values()
this is the error i'm getting...
Traceback (most recent call last):
  File "C:\Users\Public\Documents\My Python 
programs\role_playing_game1.py", line 8, in 

available_points = MAX_POINTS - attributes.values()
TypeError: unsupported operand type(s) for -: 'int' and 'dict_values'
I know using attributes.values here isn't correct but I can't figure 
out how to put the sum of the values into that equation.


Using attributes.values is fine. There is a built in function for 
summing all the values in a sequence, it's called "sum".


HTH
Adam.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] calling a method within a function

2010-12-07 Thread John
Hello,

I have a strange problem with a piece of code I've written. It's a bit
overly complicated to make an example with, but the gist is below. But
in the example below, it works. However, in my example, when I call
the method from within the function, it returns something other than
what I expect. If I call the method outside the function, it behaves
properly???



class DataHolder():
def __init__(self):
self.x = np.arange(100)
def f(self,wl):
f = np.sin(self.x) ** wl
return f


def function(DH,wl=20):
f = DH.f(wl)
plt.plot(DH.x,f)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] calling a method within a function

2010-12-07 Thread Adam Bark

On 07/12/10 22:36, John wrote:

Hello,

I have a strange problem with a piece of code I've written. It's a bit
overly complicated to make an example with, but the gist is below. But
in the example below, it works. However, in my example, when I call
the method from within the function, it returns something other than
what I expect. If I call the method outside the function, it behaves
properly???

   
It's hard to tell, from an example that doesn't display the same 
behaviour, what the problem is but it sounds like there must be some 
problem with the way you're calling the method from your function that 
isn't happening otherwise. Can you post the full source somewhere and 
mail a link to the mailing list?

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] role playing game - help needed

2010-12-07 Thread Peter Otten
Al Stern wrote:

> I used the following code and got the following error.

The result of input is always a string. 
 
> attributes["strength"] = input("\nHow many points do you want to assign to
> strength?: ")

Say you type 42 when you run your script. Then the above assignment is 
effectively

attributes["strength"] = "42"

and when you loop over the values you try to add a string to an integer 
which is what Python complains about:

>>> 42 + "42"
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'int' and 'str'

To get an integer you have to convert the string explicitly:

>>> 42 + int("42")
84

The best place to do that is as early as possible, even before you put the 
value into the dictionary:

attributes["strength"] = int(input(...))

(In a real application you'd guard against values that cannot be converted 
to integers)

> #point allocation
> point_total = 0
> for val in values:
> point_total += val
> print (point_total)
> 
> and get this error...
> 
> Traceback (most recent call last):
> File "C:\Users\Public\Documents\My Python programs\role_playing_game1.py",
> line 26, in 
> point_total += val
> TypeError: unsupported operand type(s) for +=: 'int' and 'str'


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] calling a method within a function

2010-12-07 Thread Alan Gauld


"John"  wrote

I have a strange problem with a piece of code I've written. It's a 
bit
overly complicated to make an example with, but the gist is below. 
But

in the example below, it works. However, in my example, when I call
the method from within the function, it returns something other than
what I expect.


Care to give us a clue?

What did you expect?
What did you get?
What does the real code look like?

Its a bit hard to diagnose your problem based on a bit of code that
works and a loose description of your dissapointment with another
bit of code that may or may not work - depending on what you
expected!


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor