HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

My first finished Python program: a deck of cards

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
finishedcardsdeckprogramfirstpython

Problem

I've recently started learning how to code in Python, and have even more recently learned the basics of object-oriented programming. Feeling inspired, I started on a program that would generate random cards. I'm really excited to have completed a project like this for the first time!

I had a problem of duplicates, which was quickly solved by @user2357112 when they suggested I create a deck list.

After that, it was smooth sailing. Being a relatively new programmer though, I thought I'd get some suggestions for making the code more Pythonic, decreasing any repetition (which I kept minimal), using easier methods to do the same thing, etc.

I will also take any suggestions on code organization; being largely self-taught, my code may not be laid-out neatly as it could be.

```
# This program is practice for using classes, and doubles as a useful card deck program. Hopefully this can be of some use.
# Made by [brilliantlyInsane].

from random import randint as rand
from random import shuffle

suits = ("Spades","Hearts","Clubs","Diamonds")

class Card:
def __init__(self, rank, suit):
if rank not in range(1, 14):
raise TypeError('Rank must be an integer between 1 and 13.')
if suit not in suits:
raise TypeError('Suit must be a string: "Spades", "Hearts", "Clubs", or "Diamonds".')
# The quick check above makes sure the card being made actually exists in a standard deck of 52.
# If so, the card is created succesfully.
self.rank = rank
self.suit = suit

def cardName(self):
"""
Returns a string containing the card's name in common terms.
"""
if self.rank == 1:
trueRank = "Ace"
elif self.rank == 11:
trueRank = "Jack"
elif self.rank == 12:
trueRank = "Queen"
elif self.rank == 13:
trueRank = "King"
else:
trueRank = str(self.rank)
return "{rank} of {suit}".format(rank = t

Solution

Some comments:

Check out PEP8

PEP8 is like the style guide of Python. You don't need to adhere to it, but most people are used to reading code that does.

Avoid global variables

Like @RUser4512 mentioned, go OOP, thus avoiding global variables.

Your code will look like this:

class Card:
    def __init__(self, rank, suit): pass
    def name(self): pass
    def flip(self): pass

class Deck:
    def __init__(self): pass  # newDeck()
    def shuffle(self): pass
    def draw(self): pass
    def draw_hand(self, size): pass
    def draw_faceup(self): pass

def show_help(): pass


Using idioms like __str__()

You might want to change name() to __str__(). Then you can use str(card) to get the name. If I were you, unless you plan to implement additional behaviour for flip(), I would just avoid it and use print(card) to print the card info.

Don't print text on module load

Avoid printing anything when someone imports your module. The users of your library might not appreciate this. Instead, use a docstring at the start of your module.

If you do want to write a function to print the help, use functions

print('—' * 16 + " Hands " + '—' * 49)
print('—' * 72)


is more readable -- and easier for you to write ;) -- when replaced by

def print_line(text=None):
    if text:
        output = '-' * 16 + " {} ".format(text)
        output = output.ljust(72, "-")
    else:
        output = "-" * 72
    print(output)

print_line("Hands")
print_line()

Code Snippets

class Card:
    def __init__(self, rank, suit): pass
    def name(self): pass
    def flip(self): pass

class Deck:
    def __init__(self): pass  # newDeck()
    def shuffle(self): pass
    def draw(self): pass
    def draw_hand(self, size): pass
    def draw_faceup(self): pass

def show_help(): pass
print('—' * 16 + " Hands " + '—' * 49)
print('—' * 72)
def print_line(text=None):
    if text:
        output = '-' * 16 + " {} ".format(text)
        output = output.ljust(72, "-")
    else:
        output = "-" * 72
    print(output)

print_line("Hands")
print_line()

Context

StackExchange Code Review Q#121861, answer score: 4

Revisions (0)

No revisions yet.