Trouble with printing out of Classes in Python - python
We are supposed to use the code below to print out the parameters listed in it, currently however we are unable to do so and are using a round about method. This is supposed to print out things instead of what we print out in the Game class in the playturn function
def __str__(self):
x = self.name + ":\t"
x += "Card(s):"
for y in range(len(self.hand)):
x +=self.hand[y].face + self.hand[y].suit + " "
if (self.name != "dealer"):
x += "\t Money: $" + str(self.money)
return(x)
Here is our actual code, if you also see any other issues your input would be greatly appreciated
from random import*
#do we need to address anywhere that all face cards are worth 10?
class Card(object):
def __init__(self,suit,number):
self.number=number
self.suit=suit
def __str__(self):
return '%s'%(self.number)
class DeckofCards(object):
def __init__(self,deck):
self.deck=deck
self.shuffledeck=self.shuffle()
def shuffle(self):
b=[]
count=0
while count<len(self.deck):
a=randrange(0,len(self.deck))
if a not in b:
b.append(self.deck[a])
count+=1
return(b)
def deal(self):
if len(self.shuffledeck)>0:
return(self.shuffledeck.pop(0))
else:
shuffle(self)
return(self.shuffledeck.pop(0))
class Player(object):
def __init__(self,name,hand,inout,money,score,bid):
self.name=name
self.hand=hand
self.inout=inout
self.money=money
self.score=score
self.bid=bid
def __str__(self):
x = self.name + ":\t"
x += "Card(s):"
for y in range(len(self.hand)):
x +=self.hand[y].face + self.hand[y].suit + " "
if (self.name != "dealer"):
x += "\t Money: $" + str(self.money)
return(x)
class Game(object):
def __init__(self,deck, player):
self.player=Player(player,[],True,100,0,0)
self.dealer=Player("Dealer",[],True,100,0,0)
self.deck=DeckofCards(deck)
self.blackjack= False
def blackjacksearch(self):
if Game.gettot(self.player.hand)==21:#changed
return True
else:
return False
def firstround(self):
#self.player.inout=True#do we need this since this is above
#self.player.hand=[]#do wee need this....
#self.dealer.hand=[]#do we need this ....
self.player.hand.append(DeckofCards.deal(self.deck))
for card in self.player.hand:
a=card
print(self.player.name + ' ,you were dealt a '+str(a))
self.dealer.hand.append(DeckofCards.deal(self.deck))
for card in self.dealer.hand:
a=card
print('The Dealer has '+str(a))
playerbid=int(input(self.player.name + ' how much would you like to bet? '))
self.player.money-=playerbid
self.player.bid=playerbid
def playturn(self): #should this be changed to inout instead of hit.....we never use inout
#for player in self.player:
# a=player
#print(str(a))
hit=input('Would you like to hit? ') #should input be in loop?
while self.player.inout==True: #and self.blackjack!=True:#changed
print(self.player.name + ' , your hand has:' + str(self.player.hand)) #do we want to make this gettot? so it prints out the players total instead of a list....if we want it in a list we should print it with out brakets
self.player.hand.append(DeckofCards.deal(self.deck))
for card in self.player.hand:
a=card
print('The card that you just drew is: ' + str(a))
#print(Game.gettot(self.player.hand))
hit=input('Would you like to hit? ')
if hit=='yes':
(self.player.hand.append(DeckofCards.deal(self.deck)))#changed
self.player.inout==True#
else:
(self.player.hand) #changed
self.player.inout==False #changed
if self.player.blackjack==True:
print(self.player.name + " has blackjack ")
if hit=='no':
print (self.player.hand.gettot())
def playdealer(self):
while Game.gettot(self.dealer.hand)<17:#changed
self.dealer.hand.append(DeckofCards.deal(self.deck))
dealerhand=Game.gettot(self.dealer.hand) #changed
print(dealerhand)
if Game.gettot(self.dealer.hand)==21:#changed
self.dealer.blackhjack=True
dealerhand1=Game.gettot(self.dealer.hand)#changed
print(dealerhand1)
def gettot(self,hand):
total=0
for x in self.hand:
if x==Card('H','A'):
b=total+x
if b>21:
total+=1
else:
total+=11
if x==Card('D','A'):
b=total+x
if b>21:
total+=1
else:
total+=11
if x==Card('S','A'):
b=total+x
if b>21:
total+=1
else:
total+=11
if x==Card('C','A'):
b=total+x #changed
if b>21:
total+=1
else:
total+=11
else:
total+=x
return(total)
def playgame(self):
play = "yes"
while (play.lower() == "yes"):
self.firstround()
self.playturn()
if self.player.blackjack == True:
print(self.player.name + " got BLACKJACK! ")
self.player.money += self.player.bid * 1.5
print (self.player.name + " now has " + str(self.player.money))
print("\n")
self.player.inout = False
if self.player.score > 21:
print(self.player.name + " lost with a tot of " + str(self.player.score))
self.player.money -= self.player.bid
print (self.player.name + " now has " + str(self.player.money))
print ("\n\n")
self.player.inout = False
self.playdealer()
if self.dealer.blackjack == True:
print("Dealer got blackjack, dealer wins\n")
self.player.money -= self.player.bid
print("Round\n")
print("\t",self.dealer)
print("\t",self.player)
print("\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score))
elif self.player.inout == True:
print("Round\n")
print("\t",self.dealer)
print("\t",self.player)
print("\n\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score))
if self.dealer.score > 21:
print("\t Dealer lost with a total of " + str(self.dealer.score))
self.player.money += self.player.bid
print(self.player.name + " now has " + str(self.player.money))
elif self.player.score > self.dealer.score:
print("\t" +self.player.name + " won with a total of " + str(self.player.score))
self.player.money += self.player.bid
print("\t"+self.player.name + " now has " + str(self.player.money))
else:
print("\t Dealer won with a total of " + str(self.dealer.score))
self.player.money -= self.player.bid
print("\t"+self.player.name + " now has " + str(self.player.money))
else:
print("Round")
print("\t",self.dealer)
print("\t",self.player)
if self.player.blackjack == False:
print("\t "+ self.player.name + " lost" )
else:
print("\t "+self.player.name + " Won!")
if self.player.money <= 0:
print(self.player.name + " out of money - out of game ")
play = "no"
else:
play = input("\nAnother round? ")
print("\n\n")
print("\nGame over. ")
print(self.player.name + " ended with " + str(self.player.money) + " dollars.\n")
print("Thanks for playing. Come back soon!")
ls= [Card('H','A'),Card('H','2'),Card('H','3'),Card('H','4'),Card('H','5'),Card('H','6'),Card('H','7'),Card('H','8'),Card('H','9'),Card('H','10'),
Card('H','J'),Card('H','Q'),Card('H','K'),
Card('S','A'),Card('S','2'),Card('S','3'),Card('S','4'),Card('S','5'),
Card('S','6'),Card('S','7'),Card('S','8'),Card('S','9'),Card('S','10'),
Card('S','J'),Card('S','Q'),Card('S','K'),
Card('C','A'),Card('C','2'),Card('C','3'),Card('C','4'),Card('C','5'),
Card('C','6'),Card('C','7'),Card('C','8'),Card('C','9'),Card('C','10'),
Card('C','J'),Card('C','Q'),Card('C','K'),
Card('D','A'),Card('D','2'),Card('D','3'),Card('D','4'),Card('D','5'),
Card('D','6'),Card('D','7'),Card('D','8'),Card('D','9'),Card('D','10'),
Card('D','J'),Card('D','Q'),Card('D','K')]
def main():
x = input("Player's name? ")
blackjack = Game(ls,x)
blackjack.playgame()
main()
The problem is that, in at least some places, you're trying to print a list.
While printing anything, including a list, calls str on it, the list.__str__ method calls repr on its elements. (If you don't know the difference between str and rep, see Difference between __str__ and __repr__ in Python.)
If you want to print the str of every element in a list, you have to do it explicitly, with a map or list comprehension.
For example, instead of this:
print(self.player.name + ' , your hand has:' + str(self.player.hand))
… do this:
print(self.player.name + ' , your hand has:' + [str(card) for card in self.player.hand])
But this is still probably not what you want. You will get ['8', '9'] instead of [<__main__.Card object at 0x1007aaad0>, <__main__.Card object at 0x1007aaaf0>], but you probably wanted something more like `8H 9C'. To do that, you'd want something like:
print(self.player.name + ' , your hand has:' +
' '.join(str(card) for card in self.player.hand))
You already have similar (although more verbose) code inside Player.__str__:
for y in range(len(self.hand)):
x +=self.hand[y].face + self.hand[y].suit + " "
This code could be improved in a few ways.
First, it's going to raise an AttributeError because you're using face instead of number. But really, you shouldn't need to do this at all—the whole reason you created a Card.__str__ method is so you can just use str(Card), right?
Second, you almost never want to loop over range(len(foo)), especially if you do foo[y] inside the loop. Just loop over foo directly.
Putting that together:
for card in self.hand:
x += str(card) + " "
At any rate, you need to do the same thing in both places.
The version that uses the join method and a generator expression is a little simpler than the explicit loop, but does require a bit more Python knowledge to understand. Here's how you'd use it here:
x += " ".join(str(card) for card in self.hand) + " "
Your next problem is that Card.__str__ doesn't include the suit. So, instead of 8H 9C, you're going to get 8 9. That should be an easy fix to do on your own.
Meanwhile, if you find yourself writing the same code more than once, you probably want to abstract it out. You could just write a function that takes a hand list and turns it into a string:
def str_hand(hand):
return " ".join(str(card) for card in self.hand)
But it might be even better to create a Hand class that wraps up a list of cards, and pass that around, instead of using a list directly.
You are not running the functionality you want because you are referencing player.hand. Try changing
str(self.player.hand)
to
str(self.player)
Related
Need to make str method return string instead of printing
I need the below str method written to return a string rather than print a string. def __str__(self): """Returns the string representation of the student.""" avg = sum(self.scores) / len(self.scores) print("Name: " + str(self.name)) print("Score 1: " + str(self.scores[0])) print("Score 2: " + str(self.scores[1])) print("Score 3: " + str(self.scores[2])) print("High: " + str(int(max(self.scores)))) print("Average: %.2f\n" % avg)
What you want to do is convert all those print statements into one string, while maintaining the newlines that you already have. Something like this should work in place of str def __str__(self): avg = sum(self.scores) / len(self.scores) s = "" s += "Name: " + str(self.name) + "\n" s += "Score 1: " + str(self.scores[0]) + "\n" s += "Score 2: " + str(self.scores[1]) + "\n" s += "Score 3: " + str(self.scores[2]) + "\n" s += "High: " + str(int(max(self.scores))) + "\n" s += "Average: %.2f\n" % avg + "\n" return s
How do I display an entire object that matches my search by an attribute of that object in Python?
I am writing a program that keeps track of the animals on a farm and I want to be able to search for an animal by e.g: name, gender, age etc, which all are attributes to the objects. I am a complete noob when it comes to Python so all help is very appreciated. Here is the code i have so far for this, but it only ads the attribute that is searched for to the list and then prints it. I want to be able to add the entire object to the list and print the whole object through that list. class Djur: def __init__(self, art, namn, ålder, kön, gravid): self.art = art self.namn = namn self.age = ålder self.gender = kön self.gravid = gravid def __str__(self): return ("Art: " + str(self.art) + " " + "\n" "Namn: " + str(self.namn) + " " + "\n" "Ålder: " + str(self.age) + " " + "\n" "Kön: " + str(self.gender) + " " + "\n" "Gravid: " + str(self.gravid)) def __repr__(self): return str(self) try: val2 = input("Ange sök-text") l=[] for x in djurlista: y = x.art or x.gender or x.namn or x.gravid or x.age if y == val2: l.append(x.art) print(l) meny() except ValueError: print("Var god välj ett giltigt alternativ!")
To create a list with the objects you just need to write l.append(x) instead of l.append(x.art). Now you are just appending the property art.
Python 2.7.3 Code Loops Without a While Loop
I am relatively new to programming, so don't be surprised if there are some minor hiccups in the code, but the problem that is happening is that this code seems to loop itself, the whole thing and I don't understand why. I looked at the actual code that runs this function but it seemed fine. So I cannot find any error in this code that makes it loop itself. (If the problem isn't in this code then the looping code it beneath it) def thebeast(yourhp): foe = "Thisisirrelevant" enemy = int(random.randint(1,4)) if enemy == 1: foe = "skeleton" elif enemy == 2: foe = "man with crazy eyes" else: foe = "dog, a big and scary dog" monsteract = 1 dmg = 0 print "-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~" time.sleep(0.1) print " C O M B A T" time.sleep(0.1) print "-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~" time.sleep(0.1) print "You encounter a " + foe time.sleep(0.5) while monsteract == 1: comb = str(input("What do you do to the " + foe + "?" + " Do you feel like jabbing it or stabbing it?")) if comb in ["s", "S", "Stab", "STAB", "stab"]: if spear == 1: dmg = int(random.randint(1,4)) elif sword == 1: dmg = int(random.randint(1,3)) else: dmg = int(random.randint(1,5)) elif comb in ["j", "J", "Jab", "JAB", "jab"]: if spear == 1: dmg = int(random.randint(1,3)) elif sword == 1: dmg = int(random.randint(1,4)) else: dmg = int(random.randint(1,5)) if dmg == 1: print "You slay the " + foe + " with graceful ease" time.sleep(0.5) monsteract = 0 else: enemydmg = int(random.randint(1,3)) print "The " + foe + " strikes you for " + str(enemydmg) + " damage" time.sleep(0.3) print "That didn't work out as planned, but you pull yourself together and prepare to strike the " + foe time.sleep(0.3) yourhp = yourhp - enemydmg if yourhp < 0: yourhp = 0 print "You have " + str(yourhp) + " health left" time.sleep(0.3) if yourhp < 1: print "The " + foe + " has slain you, well done, you're dead, on the bright side the innocent " print foe + " is still alive! Every life counts, even that of a " + foe + "." monsteract = 0 return thebeast(yourhp) Looping code: def randomevents(yourhp): turn = 10 while turn > 0: time.sleep(0.1) happening = int(random.randint(1,6)) time.sleep(0.1) if yourhp < 1: turn = 0 print "You managed to escape the dungeon, by dying that is" elif happening == 1: turn = turn - 1 thebeast(yourhp) elif happening == 2: item(sword, spear) turn = turn - 1 elif happening in [3, 4, 5]: friend() turn = turn - 1 print "Well done! You escaped the dungeon! (Either by running out of it, or by having your soul sent to another world)" useless = str(input("Are you satsified with yourself?: ")) Thank you!
Look at your return statement at the end of thebeast. At the end of the function, you call the function again! Since this happens every time you call it, you will never stop calling it (until you hit the maximum recursion depth). Considering that you don't capture the return value of thebeast in randomevents, you should consider it not returning anything.
Trouble with method inside of class in python
We are having trouble getting the gettot() method to work in side of our game class. When it is called inside of our game as a whole it comes back with an error saying that we dont have the correct amount of inputs for the function to operate correctly. Currently the first iteration of the functions is commented out so we could get further in the project without it stopping our game every time that it runs. this is the gettot method we are having issues with: The purpose of this method is to get the total of the cards that a player or dealer has in their hand, if there is an ace, it decides whether or not it should be a 1 or an 11 depending on which gets it closer to 21 total points without going over. def gettot(self,hand): total=0 for x in self.hand: if x==Card('H','A'): b=total+x if b>21: total+=1 else: total+=11 if x==Card('D','A'): b=total+x if b>21: total+=1 else: total+=11 if x==Card('S','A'): b=total+x if b>21: total+=1 else: total+=11 if x==Card('C','A'): b=total+x #changed if b>21: total+=1 else: total+=11 else: total+=x return(total) from random import* #do we need to address anywhere that all face cards are worth 10? class Card(object): def __init__(self,suit,number): self.number=number self.suit=suit def __str__(self): return '%s %s'%(self.number,self.suit) class DeckofCards(object): def __init__(self,deck): self.deck=deck self.shuffledeck=self.shuffle() def shuffle(self): b=[] count=0 while count<len(self.deck): a=randrange(0,len(self.deck)) if a not in b: b.append(self.deck[a]) count+=1 return(b) def deal(self): if len(self.shuffledeck)>0: return(self.shuffledeck.pop(0)) else: shuffle(self.deck) #need to refill deck return(self.shuffledeck.pop(0)) class Player(object): def __init__(self,name,hand,inout,money,score,bid): self.name=name self.hand=hand self.inout=inout self.money=money self.score=score self.bid=bid def __str__(self): x = self.name + ":\t" x += "Card(s):" for y in range(len(self.hand)): x +=self.hand[y].face + self.hand[y].suit + " " if (self.name != "dealer"): x += "\t Money: $" + str(self.money) return(x) class Game(object): def __init__(self,deck, player): self.player=Player(player,[],True,100,0,0) self.dealer=Player("Dealer",[],True,100,0,0) self.deck=DeckofCards(deck) self.blackjack= False def blackjacksearch(self): if Game.gettot(self.player.hand)==21:#changed return True else: return False def firstround(self): #self.player.inout=True#do we need this since this is above #self.player.hand=[]#do wee need this.... #self.dealer.hand=[]#do we need this .... self.player.hand.append(DeckofCards.deal(self.deck)) for card in self.player.hand: a=card print(self.player.name + ' ,you were dealt a '+str(a)) self.dealer.hand.append(DeckofCards.deal(self.deck)) for card in self.dealer.hand: a=card print('The Dealer has '+str(a)) playerbid=int(input(self.player.name + ' how much would you like to bet? ')) self.player.money-=playerbid self.player.bid=playerbid def playturn(self): #should this be changed to inout instead of hit.....we never use inout #for player in self.player: # a=player #print(str(a)) hit=input('Would you like to hit? ') #should input be in loop? while self.player.inout==True: #and self.blackjack!=True:#changed #print(self.player.name + ' , your hand has:' + str(self.player.hand)) #do we want to make this gettot? so it prints out the players total instead of a list....if we want it in a list we should print it with out brakets self.player.hand.append(DeckofCards.deal(self.deck)) for card in self.player.hand: a=card print('The card that you just drew is: ' + str(a)) print(self.player.name + ' , your hand has:' + str([str(card) for card in self.player.hand])) #print(Game.gettot(self.player.hand)) hit=input('Would you like to hit? ') if hit=='yes': (self.player.hand.append(DeckofCards.deal(self.deck)))#changed self.player.inout==True# else: (self.player.hand) #changed self.player.inout==False #changed if self.player.blackjack==True: print(self.player.name + " has blackjack ") if hit=='no': print (self.player.hand.gettot()) def playdealer(self): while Game.gettot(self.dealer.hand)<17:#changed self.dealer.hand.append(DeckofCards.deal(self.deck)) dealerhand=Game.gettot(self.dealer.hand) #changed print(dealerhand) if Game.gettot(self.dealer.hand)==21:#changed self.dealer.blackhjack=True dealerhand1=Game.gettot(self.dealer.hand)#changed print(dealerhand1) def gettot(self,hand): total=0 for x in self.hand: if x==Card('H','A'): b=total+x if b>21: total+=1 else: total+=11 if x==Card('D','A'): b=total+x if b>21: total+=1 else: total+=11 if x==Card('S','A'): b=total+x if b>21: total+=1 else: total+=11 if x==Card('C','A'): b=total+x #changed if b>21: total+=1 else: total+=11 else: total+=x return(total) def playgame(self): play = "yes" while (play.lower() == "yes"): self.firstround() self.playturn() if self.player.blackjack == True: print(self.player.name + " got BLACKJACK! ") self.player.money += self.player.bid * 1.5 print (self.player.name + " now has " + str(self.player.money)) print("\n") self.player.inout = False if self.player.score > 21: print(self.player.name + " lost with a tot of " + str(self.player.score)) self.player.money -= self.player.bid print (self.player.name + " now has " + str(self.player.money)) print ("\n\n") self.player.inout = False self.playdealer() if self.dealer.blackjack == True: print("Dealer got blackjack, dealer wins\n") self.player.money -= self.player.bid print("Round\n") print("\t",self.dealer) print("\t",self.player) print("\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score)) elif self.player.inout == True: print("Round\n") print("\t",self.dealer) print("\t",self.player) print("\n\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score)) if self.dealer.score > 21: print("\t Dealer lost with a total of " + str(self.dealer.score)) self.player.money += self.player.bid print(self.player.name + " now has " + str(self.player.money)) elif self.player.score > self.dealer.score: print("\t" +self.player.name + " won with a total of " + str(self.player.score)) self.player.money += self.player.bid print("\t"+self.player.name + " now has " + str(self.player.money)) else: print("\t Dealer won with a total of " + str(self.dealer.score)) self.player.money -= self.player.bid print("\t"+self.player.name + " now has " + str(self.player.money)) else: print("Round") print("\t",self.dealer) print("\t",self.player) if self.player.blackjack == False: print("\t "+ self.player.name + " lost" ) else: print("\t "+self.player.name + " Won!") if self.player.money <= 0: print(self.player.name + " out of money - out of game ") play = "no" else: play = input("\nAnother round? ") print("\n\n") print("\nGame over. ") print(self.player.name + " ended with " + str(self.player.money) + " dollars.\n") print("Thanks for playing. Come back soon!") ls= [Card('H','A'),Card('H','2'),Card('H','3'),Card('H','4'),Card('H','5'),Card('H','6'),Card('H','7'),Card('H','8'),Card('H','9'),Card('H','10'), Card('H','J'),Card('H','Q'),Card('H','K'), Card('S','A'),Card('S','2'),Card('S','3'),Card('S','4'),Card('S','5'), Card('S','6'),Card('S','7'),Card('S','8'),Card('S','9'),Card('S','10'), Card('S','J'),Card('S','Q'),Card('S','K'), Card('C','A'),Card('C','2'),Card('C','3'),Card('C','4'),Card('C','5'), Card('C','6'),Card('C','7'),Card('C','8'),Card('C','9'),Card('C','10'), Card('C','J'),Card('C','Q'),Card('C','K'), Card('D','A'),Card('D','2'),Card('D','3'),Card('D','4'),Card('D','5'), Card('D','6'),Card('D','7'),Card('D','8'),Card('D','9'),Card('D','10'), Card('D','J'),Card('D','Q'),Card('D','K')] def main(): x = input("Player's name? ") blackjack = Game(ls,x) blackjack.playgame() main()
TL;DR but one thing I noticed is this: x==Card('H','A'). This won’t work unless you define your Card type to handle equality comparisons in a useful way. By default it will check if they are both the same objects, and as you create a new card, it won’t be the same object as x. class Card(object): # ... def __eq__ (self, other): return self.number == other.number and self.suit == other.suit Also, this: b=total+x. If x is a Card object, how do you imagine it being added to a number? You have to define this, or do b = total + x.number instead. Another thing is that you define gettot to take a hand parameter, but in the function, you iterate over self.hand. So any other hand you pass to the function is quietly ignored and self.hand is used instead. Also this: def blackjacksearch(self): if Game.gettot(self.player.hand)==21: # ... This method belongs to the Game type; and it’s an instance method (taking a self parameter). But you actually call it as a static method from the Game type not an instance. It should be something like self.gettot() instead (you can leave out the parameter as per above). You do the same at some other places too, trying to call instance methods by using TypeName.method. You need to have objects you call them on. I think you can make your gettot method a lot shorter too: def gettot(self,hand): total=0 for x in self.hand: if x.number == 'A': if total + 11 > 21: total += 1 else: total += 11 elif x.number == 'J' or x.number == 'Q' or x.number == 'K': pass # what to do with these? else: total += x.number return(total) Rewriting some parts of your code: class Card (object): def __init__ (self, suit, number): self.suit = suit self.number = number def getValue (self): if self.number in ('J', 'Q', 'K'): return 10 elif self.number == 'A': return 11 else return int(self.number) def isAce (self): return self.number == 'A' def __eq__ (self, other): return self.suit == other.suit and self.number == other.number def __str__ (self): return '%s %s' % (self.number,self.suit) class DeckOfCards (object): def __init__ (self, deck): self.fullDeck = deck self.shuffle() def shuffle (self): self.deck = self.fullDeck[:] # copy the full deck random.shuffle(self.deck) def deal (self): if not len(self.deck): # need to refill deck self.shuffle() return self.deck.pop(0) ls = [] for suit in ('H', 'S', 'C', 'D'): for number in ('A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'): ls.append(Card(suit, number)) Your gettot method should belong to a player, and would look like this: def gettot(self): total = 0 for card in self.hand: if card.isAce() and total > 10: total += 1 else: total += card.getValue() return total
You define gettot() to take two arguments: self, and hand. Then you never use hand, and when you call the function you only pass one argument (self.dealer.hand). Eliminate the self argument (which makes no sense anyway, since it's a function defined outside of a class), and replace the for x in self.hand line with for x in hand. Even better, make the function a method of the Player object.
There are numerous problems I would add a function to Card that asks if it is an Ace. That will work better then constructing a bunch and seeing if they are equal. You are using == instead of = for some of your assignments. == is for comparison. = is for assignment. don't say inout == True just say inout (since inout is a bool already) you keep poping off the deck. When you run out you shuffle it again, but at this point it has nothing in it. at the top of gettot you are referencing self.hand, but self doesnt have a hand it should just be hand as it is passed into gettot. player.blackjack is never defined but I would add a check there for if gettot == 21, and move gettot to a modual function for now self.player.hand.gettot() should be gettot(self.player.hand) you are total+=x where total is an int and x is a Card, you cant add those unless you define how to add an int to a Card. I would just add to Card a get_value function for now to get the face value. (you could handle face cards being value of 10 here too) then use total += x.get_value() you also want to adjust for aces at the end of gettot, otherwise you don't know if you are going to be over 21. ie. what happends if the first card in your hand is an ace? example: class Card(object): def __init__(self,suit,number): self.number=number self.suit=suit def __str__(self): return '%s %s'%(self.number,self.suit) def get_value(self): if self.number == 'A': return 11 if self.number in 'JQK': return 10 return int(self.number) def is_ace(self): return self.number == 'A' def gettot(hand): total = 0 aces = 0 for x in hand: if x.is_ace(): aces += 1 total += x.get_value() while aces and total > 21: aces -= 1 total -= 10 return total That should get you started, just keep debugging
getting rid of 'NONE' before a print statement in python
Hi I am new to python and programming, I have written some code for a wordgame and when it runs, there is a 'None' printed out before some output. is there a way to remove them, I know it has to do with the loop returning nothing but I would rather not have to change the code a lot if possible(took me long enough the first time :)) Thanks in advance. def compPlayHand(hand, wordList, n): # Keep track of the total score totalScore = 0 # As long as there are still usable letters left in the hand: while compChooseWord(hand,wordList,n) is not None: # Display the hand print "Current Hand: ", print displayHand(hand), word = compChooseWord(hand,wordList,n) # comp chooses word hand = updateHand(hand,word) # Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line getWordScore(word,n) totalScore += getWordScore(word,n) # Update the hand c = calculateHandlen(hand) print '"'+str(word)+'"' + " earned " + str(getWordScore(word,n)) +' points.' " Total: " + str(totalScore) + " points." # Otherwise (the word is valid): print if compChooseWord(hand,wordList,n) is None: # End the game (break out of the loop) print "Current Hand: ", \ displayHand(hand), print "Total score: " + str(totalScore) + " points."
We've been over this, don't print displayHand, just call it on its own. def compPlayHand(hand, wordList, n): # Keep track of the total score totalScore = 0 # As long as there are still usable letters left in the hand: while compChooseWord(hand,wordList,n) is not None: # Display the hand print "Current Hand: ", displayHand(hand) word = compChooseWord(hand,wordList,n) # comp chooses word hand = updateHand(hand,word) # Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line getWordScore(word,n) totalScore += getWordScore(word,n) # Update the hand c = calculateHandlen(hand) print '"'+str(word)+'"' + " earned " + str(getWordScore(word,n)) +' points.' " Total: " + str(totalScore) + " points." # Otherwise (the word is valid): print if compChooseWord(hand,wordList,n) is None: # End the game (break out of the loop) print "Current Hand: ", displayHand(hand) print "Total score: " + str(totalScore) + " points."