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.

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

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

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 :)

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()

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?

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 your gold 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.

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..

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

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)

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"

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...

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

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...

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: Gold = Gold + 200 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.

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.

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.

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?

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 name player.

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 with self 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 for sayHi is self? But when we call it via player.sayHi() , we don't need to pass anything because self 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

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.

Yep, and there you have the start of it! Now you can just add the methods you want, like maybe a doAttack function,

from random import randint

class Character_1:
    def __init__(self,char):
        self.char = char
        self.gold = 0
        self.level = 1
        self.attack = 7
    
    def doAttack(self):
        # get a damage amount ranging from half
        # the attack value, up to the attack value
        # note that 'minimum' is integer division, so it'll truncate,
        # i.e. 7 / 2 = 3  (it cuts off the decimal part)
        minimum = self.attack / 2
        maximum = self.attack
        damage = randint(minimum, maximum)
        return damage

Note that minimum is integer division, so it's essentially rounding down by cutting off the decimal point. And the randint function chooses a random integer in the range from minimum up to and including the maximum.

EDIT:
In response to you wanting to add 200 gold to the player upon initialization, then just change the self.gold = 0 inside __init__ to self.gold = 200 .

Nice, that will come in handy, I will change that self.gold to 200, that way I can cut out the middle man.. I will work on this some more today and post some code up ..

Ok, so here is what I have now. I basicly tied everything into Leveling up..So in order to get and do stuff you have to level up. You might know a better way, but I thought this would work well.. pay no mind to that variable 'x' that is just a place holder. And for now the 'Attack' function is just setting there..

from random import randint


class Character_1:
    
    def __init__(self,char):
        self.char = char
        self.gold = 150
        self.level = 1
        self.attack = 4
        self.defend = 6

    def Level_Up(self,x):
        player.level = player.level + 1
        player.gold = player.gold + 125
        player.attack = player.attack + 2
        player.defend = player.defend + 1
        if player.Level_Up >= 1:
            print 'Level:',
            print player.level
            print 'Gold:',
            print player.gold
            print 'Attack',
            print player.attack
            print 'Defend:',
            print player.defend
        
            
    def doAttack(self):
        player.attack
        

player = Character_1('Serf')

player.level
print 'Serf Character:'
print 'Gold:',
print player.gold
print 'Level:',
print player.level
print 'Attack:',
print player.attack
print 'Defence:',
print player.defend

I see an error. Why do you have if player.Level_Up >= 1 ? Shouldn't that be if player.level >= 1 ? The value of player.Level_Up (which is the function) will be something like <bound method Character_1.Level_Up of <__main__.Character_1 object at 0x00D89110>> And you can also simplify those additions you make by using the += operator. So instead of player.gold = player.gold + 125 you can write player.gold += 125 . Similar operators are:
-=
*=
/=

I tried changing that to .level but when I do I get an error, when I use the Level_Up I put in 0 for x and get what I asked for..I dont know.. I may have something screwie going on, I will figure it out im sure.

I will change the operators to -= and += that will make things a little cleaner..Hey at least now I am asking good questions instead of stupid ones, or just having you help me make things cleaner or neater. yay im learning lol XD

EDIT: Well maybe I do have a stupid question..How would I build a menu option that pops up before the Class Character_1 pops up? I know how to build it, but what can I do do delay the Character class from poping up? I have a thought that is is the __init__ but don't I still need that?

What I am thinking is building that class for Character_1 and haveing a class Main_Menu that pops up first and lets you choose a character that will start the next class..

Oh! How could I miss it! You're using things like player.gold and player.level , etc. That's wrong, because player is undefined within that scope. When you're changing a class' properties and such from within itself, you use self. Your Level_Up function should read:

def Level_Up(self, x):
        self.level += 1
        self.gold += 125
        self.attack += 2
        self.defend += 1
        if self.level >= 1:
            print 'Level:',
            print self.level
            print 'Gold:',
            print self.gold
            print 'Attack',
            print self.attack
            print 'Defend:',
            print self.defend

That's what has been messing it up :P

did you see the rest of my question? I noticed you posted about the time I was editing my post above^.

Also now when I change everything from player to self. I get the error 'self' is not defined when I call the function Level_Up

EDIT: never mind helps to change 'player = Character_1 to 'self'
major :P on me..

Now what about this question I had above?
EDIT: Well maybe I do have a stupid question..How would I build a menu option that pops up before the Class Character_1 pops up? I know how to build it, but what can I do do delay the Character class from poping up? I have a thought that is is the __init__ but don't I still need that?

Remember that the script executes downwards; it doesn't all happen at once. Things like raw_input also stall until input is given, then the script continues. So this is fairly easy to do; here's an outline of what you'll want:

class MainMenu(object):
    def __init__(self):
        # do your stuff here
    def askWhichClass(self):
        choice = raw_input("Which class?  ")
        return choice

# define your player classes here...

mm = MainMenu()
choice = mm.askWhichClass()
if choice == 'serf':
    player = PlayerSerf()
elif choice == 'baron':
    player = PlayerBaron()
# etc...

This first initializes an instance MainMenu class (as mm). Then we call its method for getting the user's choice (via the raw_input statement) and then we check it with if statements to make player an instance of the appropriate class.
Hope this clears up your confusion!

Perfect! If I was not so sure I would say you are a Python genius! Making my life alot easier I tend to second guess about stuff, even if I think it may work..

Thanks! Just note that with the above code you'd still need to take into account incorrect input, like a user entering an invalid option for the class, etc. You could fix the MainMenu's getWhichClass method to handle this accordingly:

class MainMenu(object):
    def __init__(self):
        # do your stuff here
    def askWhichClass(self):
        # available options in a list
        options = ['serf', 'baron']
        while True:
            choice = raw_input("Which class?  ")
            # check if the choice is in the options list
            # (convert to all lowercase first to allow for case-insensitive input)

            # if so, return the choice (which also breaks the while loop)
            if choice.lower() in options:
                return choice
           # if not, don't break out of the loop,
           # so that it regathers input until it gets a valid choice
           else:
                print 'Invalid choice!'
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.