Files
2025-08-04 13:04:42 -04:00

80 lines
3.2 KiB
Python

# Implement a class to represent a playing card. Your class should have the following methods:
# __init__(self, rank, suit) rank is an integer from 1 to 13, indicating the suit (diamonds, clubs, hearts or spades).
# Create the corresponding card.
# getRank(self) returns the rank of the card.
# getSuit(self) Returns the sute of the card
#value(self) Returns the blackjack value of a card. Ace counts as 1, ace cards count as 10.
#__str__(self) Returns a string that names the card. For example, "Ace of Spades".
#Note: A method named __str__ is special in Python. If asked to convert an object into a string, python uses this method, if it's present. For example,
# c = Card(1,"s")
# print callable
# will print "Ace of Spades"
#Test your card class with a program that prints out n randomly generated cards and the associated blackjack value where n is a number supplied by the user.
import random
class PlayingCard:
def __init__(self, rank, suit): #initialize the rank and suit of the card object
self.rank = rank #assign the rank to the card object
self.suit = suit #assign the suit to the card
def getRank(self):
return self.rank #return the rank of the card
def getSuit(self):
return self.suit #return the suit of the card
def value(self):
if self.rank == 1: #if the rank of the card is 1, return 1
return 1
elif self.rank > 10: #if the rank of the card is greater than 10, return 10
return 10
else:
return self.rank #return the rank of the card
def __str__(self):
if self.rank == 1:
rank = "Ace"
elif self.rank == 11:
rank = "Jack"
elif self.rank == 12:
rank = "Queen"
elif self.rank == 13:
rank = "King"
else:
rank = self.rank
if self.suit == "d":
suit = "Diamonds"
elif self.suit == "c":
suit = "Clubs"
elif self.suit == "h":
suit = "Hearts"
elif self.suit == "s":
suit = "Spades"
return f"{rank} of {suit}"
def main():
while True:
try:
n = int(input("Enter the number of cards: ")) # ask the user to choose how many cards to "draw"
for i in range(n): # loop through the number of card the user has selected to draw
rank = random.randint(1, 13) #randomly generate the rank of the card in n round between 1 and 13
suit = random.choice("dchs") #randomly generate the suite of the card in n round between d, c, h, s
card = PlayingCard(rank, suit) # assign the previously generated values to the card object and create the card by calling the class and passing the rank and suit as arguments and assign it to the card variable and create the card object and assign it to the card variable and create the card object and assign it to the card variable
print(f"Card: {card}, Value of Card: {card.value()}") # print out the card tuple and the value of the card
except ValueError:
print("Please enter a valid number")
except:
print("An error occured")
if __name__ == "__main__":
main()