954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Variable Question maybe a function..

Ok, I made a very simple function to keep track of variable Gold...Ok thats easy, everything works fine, except I made the variable = 200 and when the function performs it adds like it is told to do. But I want it to evolve as I add to it, and remember what I add and change that variable 200 to whatever I add to it and so on.. here is the code bit..

def Gold_Keeper(x):
    a = 200
    if x <= a:
        print a+x,
    elif x >= a:
        print a+x,

So basicly "a" is the initial amount of Gold. I wanted it to add "x" to it so I made a sloppy <=>= and ya ;) it works.. But after I say a+x I want it to change that a = 200 to whatever a+x is and store it..and do that every time, so it kinda counts..I know there is a simple solution to this, I just can not think of it.

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 
def Gold_Keeper(x):
    a = 200
    if x <= a:
        print a+x,
    elif x >= a:
        print a+x,
    else:
        pass
evstevemd
Senior Poster
3,713 posts since Jun 2007
Reputation Points: 462
Solved Threads: 392
 

That still does not store the sum of the variable to recall at a later time.. I tried that..

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

Keep the gold amount as a list:

def goldKeeper(x):
    a = 200

    # if 'x' contains any indices
    if x:
        if x[-1] <= a:
            # store new 'x' value
            x.append(a)
        elif x[-1] >= a:
            print a + x,

    # if 'x' is a blank list
    else:
        print a+x,

gold = [100]
goldKeeper(gold)
"""my result for gold ->
[100, 200]
"""

This shows that the new value for 'gold' is added onto the end of the list so that you have a sort of history of past values.

Though I'm still thoroughly confused about why you have the conditional statements. You listed print a+x, for both of them... so what were you trying to do? I just assumed that you'd store 'a' as the new value of 'x' if 'a' is more than the current 'x' value.

Hope I helped :)

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

dang, you're good..Second time you have answered my question..I knew it was the append thing, I just could not think of it..Soon as I saw your post it hit me.. Thanks alot =)

The reason I put "a" both times was I at the time I could not think of a better way, altho there is several ways to put it. I just changed mine up a little bit and add the .append()

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

I get an error when using pieces of your code with mine, then I tried using just all your code and still got an error..
gives a Type Error, line 5, if x[-1] <= a:
When I take the[-1] out then it errors on the x.append(a)

Would this be because of different python version or a different tookkit?

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

Ah, it means that you are passing an integer to your function. Do you see in my code that I declared gold as a list? A list is a different variable than an integer. ( Here's a bit of documentation on it. ) So what I did is use a list which has integers in it as the indices. So x[-1] is the last item in the list, i.e. the most current value. You need to declare yourgold variable that you pass to the goldKeeper function as a list, and then to get its current value, you need to access the last item in it by using that square-bracket notation.

It sounds like you really need to read up on the basics of Python and/or programming in general. Here's a very good, free, online Python book .

>> "...or a different toolkit?"
No, this has to do with core aspects of the language. It's like that math question you asked about wxPython . Calculations are still in Python - they aren't changed by a toolkit, unless the toolkit you're talking about introduces new mathematical possibilities, i.e. the module numpy. In this case, you're using core data structures of Python so they're the same (99.9% of the time) with whatever extra modules you're using.

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

That is what I needed is a good free source for all things python, I have been trying to self teach this stuff, and just hunting and pecking in the dark for a good source of learning, basicly I just pick up things and try to understand and modify them to figure them out..

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

So I take it that you fixed the TypeError you were getting when you didn't have your gold variable as a list?

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

No actually it still gives that error, even when I type it exactly as you have it...I'm a real n00b but I would have thought I could type it right, heck I even copy&pasted it..and kept it the same.

This errors...what did I do wrong, I swear its just like yours is..

Here it is...

def goldKeeper(x):
    a = 200
    if x:
        if x[-1] <= a:
            x.append(a)
        elif x[-1] >= a:
            print a + x,

    else:
        print a+x,

gold = [100]
goldKeeper(gold)
Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

Whne do you declare x and what happens if it is the first time through and x is empty (it will never process no matter how many times you run it because of "if x:"). Generally "gold" is passed as an iteger to the function and returned. This example subtracts instead of adds to make a point as your code will rarely be anything other than x or gold > a.

def gold_keeper(x):
    a = 200
    if x >= a:
        x -= a
        print x
    else:
        print "You don't have enough gold, %d <= %d" % (x, a)
    return x

gold = 250
gold = gold_keeper(gold)
print "\nFirst Test and gold =", gold
gold = gold_keeper(gold)
print "\nSecond Test and gold =", gold"
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

What you re-posted gives me no errors. This is assuming that you are running it all by itself without incorporating it into whatever script you already had. Save the code I posted into a .py file all by itself, then run that. You'll see that you won't get an error.

The only reason why it should mess up is if you tried to incorporate it into your pre-existing script and forgot to change something else somewhere. Please post the exact traceback error it's giving you.

EDIT:
@woooe,
I was assuming that he'd be setting 'gold' to some initial value, and that 'a' would not always be set to 200 (I thought he put it there for testing purposes). Otherwise, there really seems to be no point to this function...

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

Well, this is "was" going to be a part of a bigger picture. And "a" is not going to always = 200. It will evolve with time and progress with the other parts. When I get this part working, I did what you said, saved it as a .py just that function and I still get an error when I input a number for (x). here is exactly what it gives me. I tried to put 5 for (x). One of these days I will wrap my head around Python, I know it is the easiest to learn, but still hard for someone who has only been doing it for 2 weeks now..

Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    goldKeeper(5)
  File "C:/Python25/test", line 4, in goldKeeper
    if x[-1] <= a:
TypeError: 'int' object is unsubscriptable
Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

This is exactly what I was saying. You put 5 - that's an integer. I said that the code I wrote required a list. Please read a book on Python because if you had a good basic knowledge, you would understand that x needs to be a list because of the notation x[-1] . That square bracket notation is for iterable objects, and it returns the specified index in the list (in this case, -1, the last index from the end).

The reason I was using a list in the first place was because you said that you wanted to track the history, which is what a list would be perfect for. So, for this to work, you need to have the variable you pass to the function as a list, like I did in my example with gold = [100] . Notice the square brackets around 100? That means that 'gold' is a list, and it has one index at the moment, with a value of 100.

You could modify your goldKeeper function to take an integer, but then you'd have to pass it the last index from the 'gold' list, rather than the list itself. Either way works...

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

Are you making a game?

If you have a variable Gold and you want to add 200 to it (I'm assuming the player just got off work), why not just say: [icode=python]Gold = Gold + 200[/icode]

Too easy?

Or get fancy, say you have another variable called job:

def get_pay(job):
   job_dict = {'IT': 100,'CEO':500}
   return job_dict(job)
Job = 'IT'
Gold = Gold + get_pay(Job)


Heh heh, having a bit of fun. Depending on what you add or subtract from the player's gold total, you shouldn't store that variable in the function. Pass it to the function.

zachabesh
Junior Poster
106 posts since Jun 2008
Reputation Points: 16
Solved Threads: 17
 

I was making just a little piece of a maybe sometime way, and I mean way down the road, this may turn into some top down shooter 80s style. I have much to learn, and have a hard time finding correct ways to do stuff, I see one person dose it this way, another a different way..and so on. I do have the very basics down, I just need some lists work and more function practice. I will get there I am sure, every starts some where I just started here.

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

You should definitely look into classes then. It's a steeper learning curve, but definitely definitely better. For example, you could have a class like this:

class NewPlayer:
    def __init__(self,name):
        self.name = name
        self.gold = 0

player = NewPlayer('Paul')

player.gold = player.gold + 200


That way you always know where the player's gold is. Functions are no good for remembering things. Store them in classes.

zachabesh
Junior Poster
106 posts since Jun 2008
Reputation Points: 16
Solved Threads: 17
 

Why is it I understand what you did for the Class very good. But functions I struggle at..Weird.
So Class can be anything as long as Class is stated.
then the def __init__ < initial start of the function? always have (self,whatever you want) You do not have to define self, since python dose that.. then you can make basicly self.anything under the function, as long as you define it?

They only big thing I am not sure or understand properly is how do you call that function __init__(self,name) under a class, you can call the class by typing NewPlayer but what about the function under it?

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

The __init__ function is called when you create a new instance of that class. So when zac said player = NewPlayer('Paul') , the __init__ function of the NewPlayer class was called, and the instance of that class was stored by the nameplayer.

If you want to call methods in the class, then you can do so by simple using that dot notation like you did for the variables: player.someFunction() . Note however, that the functions contained in the class must be defined withself as the first parameter, but when you make calls to them, self is assigned automatically based on the object instance you're making the call from.

class NewPlayer:
    def __init__(self,name):
        self.name = name
        self.gold = 0
    def sayHi(self):
        print 'hello!'

player = NewPlayer('Paul')
player.sayHi()

Note that the first argument forsayHi is self? But when we call it via player.sayHi() , we don't need to pass anything becauseself is given by player, the variable whose method we're calling. And the same goes for calls to those functions from within a class; if we wanted to call sayHi from within the __init__ function, we'd use self.sayHi() .

Hope that helped a bit :P

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

It did help... I took your advice and spent 4 hours yesterday reading up on functions/classes, and everything from the super basics.. So that being done, I have this made up right now, its still early and needs a ton of work before it can do what it needs to do but.. I will let you take a look and you can maybe help make it simpler but I think I got it pretty good.

class Character_1:
    def __init__(self,char):
        self.char = char
        self.gold = 0
        self.level = 1

player = Character_1('Serf')
player.gold = player.gold + 200
player.level
print 'Serf Character:'
print 'Gold:',
print player.gold
print 'Level:',
print player.level


If all this looks okay, then the next thing is a function or something that can add to the gold(200) when you first initiate the player character. I was thinking a function because I dont want to give gold everytime the player is initiated, just whenever a certian task is described and then I can call that function to fill in the rest.

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You