简体   繁体   中英

Python method doesn't return right value

In order to learn how to use classes in Python, I'm currently coding a card game. I wanted to test the "wert_addieren" method (this method is supposed to add the value of a card to the player score), so I wrote a simple test program. But here is the problem: The only time the method "wert_addieren" returns the expected result, namely

spieler_punkte = 2

is when I change

return punkte

to

print(deck, punkte)

I hope someone is able to help me:)

Full code:

class Kartenstapel(object):
    def __init__(self):
        #Karten Abkürzungen: Kreuz = KR, Pik = PI, Herz = HE, Karo = KA
        self.karten = ["2KR", "2PI", "2HE", "2KA", "3KR", "3PI", "3HE", "3KA", "4KR", "4PI", "4HE", "4KA",
                    "5KR", "5PI", "5HE", "5KA", "6KR", "6PI", "6HE", "6KA", "7KR", "7PI", "7HE", "7KA",
                    "8KR", "8PI", "8HE", "8KA", "9KR", "9PI", "9HE", "9KA", "10KR", "10PI", "10HE", "10KA",
                    "bubeKR", "bubePI", "bubeHE", "bubeKA", "koeniginKR", "koeniginPI", "koeniginHE", "koeniginKA", 
                    "koenigKR", "koenigPI", "koenigHE", "koenigKA", "assKR", "assPI", "assHE", "assKA"]

    def wert_addieren(self, deck, punkte):
        hilf = deck[-1]
        if "2" in hilf:
            punkte += 2
        return punkte

    def karte_ziehen(self, deck):
        deck.append(self.karten[0])
        self.karten.pop(0)
        return self.karten, deck

k = Kartenstapel()
spieler = []
spieler_punkte = 0
k.karte_ziehen(spieler)
k.wert_addieren(spieler, spieler_punkte)
print(spieler, "\n", spieler_punkte)

First of all, pop method also returns the popped item, so you can just do

    def karte_ziehen(self, deck):
        deck.append(self.karten.pop(0))
        return self.karten, deck

Secondly, you are returning the values from the functions but not using them. So do something like -

k = Kartenstapel()
spieler = []
spieler_punkte = 0
karten, spieler = k.karte_ziehen(spieler)
spieler_punkte = k.wert_addieren(spieler, spieler_punkte)
print(spieler, "\n", spieler_punkte)

I have used the same variables for returned values. You can use different if needed.

when you do this k.wert_addieren(spieler, spieler_punkte) you are changing the value of spieler_punkte to 2, so you are not really using return, so you don't really need it. if you are already changing the value of the parameters you dont really need to return anything unless it is something that has no connection to the parameters.for example, a function that adds an extra card to a deck doesnt need to return anything, but a function that gives us the total value of all the cards in a deck would return a specific value which you would give to another variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM